@trigger.dev/core 3.0.0-beta.12 → 3.0.0-beta.14

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/v3/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var zod = require('zod');
4
4
  var api = require('@opentelemetry/api');
5
+ var zodValidationError = require('zod-validation-error');
5
6
  var async_hooks = require('async_hooks');
6
7
  var socket_ioClient = require('socket.io-client');
7
8
  var crypto = require('crypto');
@@ -91,6 +92,7 @@ var TaskRunStringError = zod.z.object({
91
92
  });
92
93
  var TaskRunErrorCodes = {
93
94
  COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
95
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
94
96
  CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
95
97
  TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
96
98
  TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
@@ -98,12 +100,14 @@ var TaskRunErrorCodes = {
98
100
  TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
99
101
  TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
100
102
  TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
101
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR"
103
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
104
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
102
105
  };
103
106
  var TaskRunInternalError = zod.z.object({
104
107
  type: zod.z.literal("INTERNAL_ERROR"),
105
108
  code: zod.z.enum([
106
109
  "COULD_NOT_FIND_EXECUTOR",
110
+ "COULD_NOT_FIND_TASK",
107
111
  "CONFIGURED_INCORRECTLY",
108
112
  "TASK_ALREADY_RUNNING",
109
113
  "TASK_EXECUTION_FAILED",
@@ -111,7 +115,8 @@ var TaskRunInternalError = zod.z.object({
111
115
  "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
112
116
  "TASK_RUN_CANCELLED",
113
117
  "TASK_OUTPUT_ERROR",
114
- "HANDLE_ERROR_ERROR"
118
+ "HANDLE_ERROR_ERROR",
119
+ "GRACEFUL_EXIT_TIMEOUT"
115
120
  ]),
116
121
  message: zod.z.string().optional()
117
122
  });
@@ -448,15 +453,17 @@ var QueueOptions = zod.z.object({
448
453
  });
449
454
  var TaskMetadata = zod.z.object({
450
455
  id: zod.z.string(),
451
- exportName: zod.z.string(),
452
456
  packageVersion: zod.z.string(),
453
457
  queue: QueueOptions.optional(),
454
458
  retry: RetryOptions.optional(),
455
- machine: Machine.partial().optional()
459
+ machine: Machine.partial().optional(),
460
+ triggerSource: zod.z.string().optional()
456
461
  });
457
- var TaskMetadataWithFilePath = TaskMetadata.extend({
458
- filePath: zod.z.string()
462
+ var TaskFileMetadata = zod.z.object({
463
+ filePath: zod.z.string(),
464
+ exportName: zod.z.string()
459
465
  });
466
+ var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
460
467
  var UncaughtExceptionMessage = zod.z.object({
461
468
  version: zod.z.literal("v1").default("v1"),
462
469
  error: zod.z.object({
@@ -608,7 +615,8 @@ var TaskResource = zod.z.object({
608
615
  exportName: zod.z.string(),
609
616
  queue: QueueOptions.optional(),
610
617
  retry: RetryOptions.optional(),
611
- machine: Machine.partial().optional()
618
+ machine: Machine.partial().optional(),
619
+ triggerSource: zod.z.string().optional()
612
620
  });
613
621
  var BackgroundWorkerMetadata = zod.z.object({
614
622
  packageVersion: zod.z.string(),
@@ -664,7 +672,9 @@ var TriggerTaskRequestBody = zod.z.object({
664
672
  lockToVersion: zod.z.string().optional(),
665
673
  queue: QueueOptions.optional(),
666
674
  concurrencyKey: zod.z.string().optional(),
667
- test: zod.z.boolean().optional()
675
+ idempotencyKey: zod.z.string().optional(),
676
+ test: zod.z.boolean().optional(),
677
+ payloadType: zod.z.string().optional()
668
678
  }).optional()
669
679
  });
670
680
  var TriggerTaskResponse = zod.z.object({
@@ -760,6 +770,87 @@ var ReplayRunResponse = zod.z.object({
760
770
  var CanceledRunResponse = zod.z.object({
761
771
  message: zod.z.string()
762
772
  });
773
+ var ScheduledTaskPayload = zod.z.object({
774
+ /** The schedule id associated with this run (you can have many schedules for the same task).
775
+ You can use this to remove the schedule, update it, etc */
776
+ scheduleId: zod.z.string(),
777
+ /** When the task was scheduled to run.
778
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
779
+ timestamp: zod.z.date(),
780
+ /** When the task was last run (it has been).
781
+ This can be undefined if it's never been run */
782
+ lastTimestamp: zod.z.date().optional(),
783
+ /** You can optionally provide an external id when creating the schedule.
784
+ Usually you would use a userId or some other unique identifier.
785
+ This defaults to undefined if you didn't provide one. */
786
+ externalId: zod.z.string().optional(),
787
+ /** The next 5 dates this task is scheduled to run */
788
+ upcoming: zod.z.array(zod.z.date())
789
+ });
790
+ var CreateScheduleOptions = zod.z.object({
791
+ /** The id of the task you want to attach to. */
792
+ task: zod.z.string(),
793
+ /** The schedule in CRON format.
794
+ *
795
+ * ```txt
796
+ * * * * * *
797
+ ┬ ┬ ┬ ┬ ┬
798
+ │ │ │ │ |
799
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
800
+ │ │ │ └───── month (1 - 12)
801
+ │ │ └────────── day of month (1 - 31, L)
802
+ │ └─────────────── hour (0 - 23)
803
+ └──────────────────── minute (0 - 59)
804
+ * ```
805
+
806
+ "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
807
+
808
+ */
809
+ cron: zod.z.string(),
810
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
811
+ *
812
+ * This is useful if you don't want to create duplicate schedules for a user. */
813
+ deduplicationKey: zod.z.string().optional(),
814
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
815
+ *
816
+ * This allows you to have per-user CRON tasks.
817
+ */
818
+ externalId: zod.z.string().optional()
819
+ });
820
+ var UpdateScheduleOptions = CreateScheduleOptions;
821
+ var ScheduleObject = zod.z.object({
822
+ id: zod.z.string(),
823
+ task: zod.z.string(),
824
+ active: zod.z.boolean(),
825
+ deduplicationKey: zod.z.string().nullish(),
826
+ externalId: zod.z.string().nullish(),
827
+ generator: zod.z.object({
828
+ type: zod.z.literal("CRON"),
829
+ expression: zod.z.string(),
830
+ description: zod.z.string()
831
+ }),
832
+ nextRun: zod.z.coerce.date().nullish(),
833
+ environments: zod.z.array(zod.z.object({
834
+ id: zod.z.string(),
835
+ type: zod.z.string(),
836
+ userName: zod.z.string().nullish()
837
+ }))
838
+ });
839
+ var DeletedScheduleObject = zod.z.object({
840
+ id: zod.z.string()
841
+ });
842
+ var ListSchedulesResult = zod.z.object({
843
+ data: zod.z.array(ScheduleObject),
844
+ pagination: zod.z.object({
845
+ currentPage: zod.z.number(),
846
+ totalPages: zod.z.number(),
847
+ count: zod.z.number()
848
+ })
849
+ });
850
+ var ListScheduleOptions = zod.z.object({
851
+ page: zod.z.number().optional(),
852
+ perPage: zod.z.number().optional()
853
+ });
763
854
  var PostStartCauses = zod.z.enum([
764
855
  "index",
765
856
  "create",
@@ -791,7 +882,8 @@ var Config = zod.z.object({
791
882
  zod.z.string(),
792
883
  RegexSchema
793
884
  ])).optional(),
794
- logLevel: zod.z.string().optional()
885
+ logLevel: zod.z.string().optional(),
886
+ enableConsoleLogging: zod.z.boolean().optional()
795
887
  });
796
888
  var WaitReason = zod.z.enum([
797
889
  "WAIT_FOR_DURATION",
@@ -1447,101 +1539,384 @@ var SpanMessagingEvent = zod.z.object({
1447
1539
  destination: zod.z.string().optional()
1448
1540
  });
1449
1541
 
1450
- // src/zodfetch.ts
1542
+ // src/v3/apiErrors.ts
1543
+ var _APIError = class _APIError extends Error {
1544
+ constructor(status, error, message, headers) {
1545
+ super(`${_APIError.makeMessage(status, error, message)}`);
1546
+ this.status = status;
1547
+ this.headers = headers;
1548
+ const data = error;
1549
+ this.error = data;
1550
+ this.code = data?.["code"];
1551
+ this.param = data?.["param"];
1552
+ this.type = data?.["type"];
1553
+ }
1554
+ static makeMessage(status, error, message) {
1555
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1556
+ if (status && msg) {
1557
+ return `${status} ${msg}`;
1558
+ }
1559
+ if (status) {
1560
+ return `${status} status code (no body)`;
1561
+ }
1562
+ if (msg) {
1563
+ return msg;
1564
+ }
1565
+ return "(no status code or body)";
1566
+ }
1567
+ static generate(status, errorResponse, message, headers) {
1568
+ if (!status) {
1569
+ return new APIConnectionError({
1570
+ cause: castToError(errorResponse)
1571
+ });
1572
+ }
1573
+ const error = errorResponse?.["error"];
1574
+ if (status === 400) {
1575
+ return new BadRequestError(status, error, message, headers);
1576
+ }
1577
+ if (status === 401) {
1578
+ return new AuthenticationError(status, error, message, headers);
1579
+ }
1580
+ if (status === 403) {
1581
+ return new PermissionDeniedError(status, error, message, headers);
1582
+ }
1583
+ if (status === 404) {
1584
+ return new NotFoundError(status, error, message, headers);
1585
+ }
1586
+ if (status === 409) {
1587
+ return new ConflictError(status, error, message, headers);
1588
+ }
1589
+ if (status === 422) {
1590
+ return new UnprocessableEntityError(status, error, message, headers);
1591
+ }
1592
+ if (status === 429) {
1593
+ return new RateLimitError(status, error, message, headers);
1594
+ }
1595
+ if (status >= 500) {
1596
+ return new InternalServerError(status, error, message, headers);
1597
+ }
1598
+ return new _APIError(status, error, message, headers);
1599
+ }
1600
+ };
1601
+ __name(_APIError, "APIError");
1602
+ var APIError = _APIError;
1603
+ var _APIConnectionError = class _APIConnectionError extends APIError {
1604
+ constructor({ message, cause }) {
1605
+ super(void 0, void 0, message || "Connection error.", void 0);
1606
+ __publicField(this, "status");
1607
+ if (cause)
1608
+ this.cause = cause;
1609
+ }
1610
+ };
1611
+ __name(_APIConnectionError, "APIConnectionError");
1612
+ var APIConnectionError = _APIConnectionError;
1613
+ var _BadRequestError = class _BadRequestError extends APIError {
1614
+ constructor() {
1615
+ super(...arguments);
1616
+ __publicField(this, "status", 400);
1617
+ }
1618
+ };
1619
+ __name(_BadRequestError, "BadRequestError");
1620
+ var BadRequestError = _BadRequestError;
1621
+ var _AuthenticationError = class _AuthenticationError extends APIError {
1622
+ constructor() {
1623
+ super(...arguments);
1624
+ __publicField(this, "status", 401);
1625
+ }
1626
+ };
1627
+ __name(_AuthenticationError, "AuthenticationError");
1628
+ var AuthenticationError = _AuthenticationError;
1629
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1630
+ constructor() {
1631
+ super(...arguments);
1632
+ __publicField(this, "status", 403);
1633
+ }
1634
+ };
1635
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1636
+ var PermissionDeniedError = _PermissionDeniedError;
1637
+ var _NotFoundError = class _NotFoundError extends APIError {
1638
+ constructor() {
1639
+ super(...arguments);
1640
+ __publicField(this, "status", 404);
1641
+ }
1642
+ };
1643
+ __name(_NotFoundError, "NotFoundError");
1644
+ var NotFoundError = _NotFoundError;
1645
+ var _ConflictError = class _ConflictError extends APIError {
1646
+ constructor() {
1647
+ super(...arguments);
1648
+ __publicField(this, "status", 409);
1649
+ }
1650
+ };
1651
+ __name(_ConflictError, "ConflictError");
1652
+ var ConflictError = _ConflictError;
1653
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1654
+ constructor() {
1655
+ super(...arguments);
1656
+ __publicField(this, "status", 422);
1657
+ }
1658
+ };
1659
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1660
+ var UnprocessableEntityError = _UnprocessableEntityError;
1661
+ var _RateLimitError = class _RateLimitError extends APIError {
1662
+ constructor() {
1663
+ super(...arguments);
1664
+ __publicField(this, "status", 429);
1665
+ }
1666
+ };
1667
+ __name(_RateLimitError, "RateLimitError");
1668
+ var RateLimitError = _RateLimitError;
1669
+ var _InternalServerError = class _InternalServerError extends APIError {
1670
+ };
1671
+ __name(_InternalServerError, "InternalServerError");
1672
+ var InternalServerError = _InternalServerError;
1673
+ function castToError(err) {
1674
+ if (err instanceof Error)
1675
+ return err;
1676
+ return new Error(err);
1677
+ }
1678
+ __name(castToError, "castToError");
1679
+
1680
+ // src/retry.ts
1681
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
1682
+ if (!resets)
1683
+ return;
1684
+ switch (format) {
1685
+ case "iso_8601_duration_openai_variant": {
1686
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
1687
+ }
1688
+ case "iso_8601": {
1689
+ return calculateISO8601ResetAt(resets, now);
1690
+ }
1691
+ case "unix_timestamp": {
1692
+ return calculateUnixTimestampResetAt(resets, now);
1693
+ }
1694
+ case "unix_timestamp_in_ms": {
1695
+ return calculateUnixTimestampInMsResetAt(resets, now);
1696
+ }
1697
+ }
1698
+ }
1699
+ __name(calculateResetAt, "calculateResetAt");
1700
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
1701
+ if (!resets)
1702
+ return void 0;
1703
+ const resetAt = parseInt(resets, 10);
1704
+ if (isNaN(resetAt))
1705
+ return void 0;
1706
+ return new Date(resetAt * 1e3);
1707
+ }
1708
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
1709
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
1710
+ if (!resets)
1711
+ return void 0;
1712
+ const resetAt = parseInt(resets, 10);
1713
+ if (isNaN(resetAt))
1714
+ return void 0;
1715
+ return new Date(resetAt);
1716
+ }
1717
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
1718
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
1719
+ if (!resets)
1720
+ return void 0;
1721
+ const resetAt = new Date(resets);
1722
+ if (isNaN(resetAt.getTime()))
1723
+ return void 0;
1724
+ return resetAt;
1725
+ }
1726
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
1727
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
1728
+ if (!resets)
1729
+ return void 0;
1730
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
1731
+ const match = resets.match(pattern);
1732
+ if (!match)
1733
+ return void 0;
1734
+ const days = parseInt(match[1], 10) || 0;
1735
+ const hours = parseInt(match[2], 10) || 0;
1736
+ const minutes = parseInt(match[3], 10) || 0;
1737
+ const seconds = parseFloat(match[4]) || 0;
1738
+ const milliseconds = parseInt(match[5], 10) || 0;
1739
+ const resetAt = new Date(now);
1740
+ resetAt.setDate(resetAt.getDate() + days);
1741
+ resetAt.setHours(resetAt.getHours() + hours);
1742
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
1743
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
1744
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
1745
+ return resetAt;
1746
+ }
1747
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
1748
+
1749
+ // src/v3/utils/retries.ts
1750
+ var defaultRetryOptions = {
1751
+ maxAttempts: 3,
1752
+ factor: 2,
1753
+ minTimeoutInMs: 1e3,
1754
+ maxTimeoutInMs: 6e4,
1755
+ randomize: true
1756
+ };
1757
+ var defaultFetchRetryOptions = {
1758
+ byStatus: {
1759
+ "429,408,409,5xx": {
1760
+ strategy: "backoff",
1761
+ ...defaultRetryOptions
1762
+ }
1763
+ },
1764
+ connectionError: defaultRetryOptions,
1765
+ timeout: defaultRetryOptions
1766
+ };
1767
+ function calculateNextRetryDelay(options, attempt) {
1768
+ const opts = {
1769
+ ...defaultRetryOptions,
1770
+ ...options
1771
+ };
1772
+ if (attempt >= opts.maxAttempts) {
1773
+ return;
1774
+ }
1775
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1776
+ const random = randomize ? Math.random() + 1 : 1;
1777
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1778
+ return Math.round(timeout);
1779
+ }
1780
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1781
+ function calculateResetAt2(resets, format, now = Date.now()) {
1782
+ const resetAt = calculateResetAt(resets, format, new Date(now));
1783
+ return resetAt?.getTime();
1784
+ }
1785
+ __name(calculateResetAt2, "calculateResetAt");
1786
+
1787
+ // src/v3/zodfetch.ts
1788
+ var defaultRetryOptions2 = {
1789
+ maxAttempts: 3,
1790
+ factor: 2,
1791
+ minTimeoutInMs: 1e3,
1792
+ maxTimeoutInMs: 6e4,
1793
+ randomize: false
1794
+ };
1451
1795
  async function zodfetch(schema, url, requestInit, options) {
1452
1796
  return await _doZodFetch(schema, url, requestInit, options);
1453
1797
  }
1454
1798
  __name(zodfetch, "zodfetch");
1455
1799
  async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1456
1800
  try {
1457
- const response = await fetch(url, requestInit);
1458
- if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1459
- return {
1460
- ok: false,
1461
- error: `404: ${response.statusText}`
1462
- };
1463
- }
1464
- if (response.status >= 400 && response.status < 500 && response.status !== 429) {
1465
- const body = await response.json();
1466
- if (!body.error) {
1467
- return {
1468
- ok: false,
1469
- error: "Something went wrong"
1470
- };
1801
+ const response = await fetch(url, requestInitWithCache(requestInit));
1802
+ const responseHeaders = createResponseHeaders(response.headers);
1803
+ if (!response.ok) {
1804
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1805
+ if (retryResult.retry) {
1806
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1807
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1808
+ } else {
1809
+ const errText = await response.text().catch((e) => castToError2(e).message);
1810
+ const errJSON = safeJsonParse(errText);
1811
+ const errMessage = errJSON ? void 0 : errText;
1812
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1471
1813
  }
1472
- return {
1473
- ok: false,
1474
- error: body.error
1475
- };
1476
1814
  }
1477
- if (response.status === 429 || response.status >= 500) {
1478
- if (!options?.retry) {
1479
- return {
1480
- ok: false,
1481
- error: `Failed to fetch ${url}, got status code ${response.status}`
1482
- };
1483
- }
1815
+ const jsonBody = await response.json();
1816
+ const parsedResult = schema.safeParse(jsonBody);
1817
+ if (parsedResult.success) {
1818
+ return parsedResult.data;
1819
+ }
1820
+ throw zodValidationError.fromZodError(parsedResult.error);
1821
+ } catch (error) {
1822
+ if (error instanceof APIError) {
1823
+ throw error;
1824
+ }
1825
+ if (options?.retry) {
1484
1826
  const retry = {
1485
- ...defaultRetryOptions,
1827
+ ...defaultRetryOptions2,
1486
1828
  ...options.retry
1487
1829
  };
1488
- if (attempt > retry.maxAttempts) {
1489
- return {
1490
- ok: false,
1491
- error: `Failed to fetch ${url}, got status code ${response.status}`
1492
- };
1493
- }
1494
1830
  const delay = calculateNextRetryDelay(retry, attempt);
1495
- await new Promise((resolve) => setTimeout(resolve, delay));
1496
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1497
- }
1498
- if (response.status !== 200) {
1499
- return {
1500
- ok: false,
1501
- error: `Failed to fetch ${url}, got status code ${response.status}`
1502
- };
1831
+ if (delay) {
1832
+ await new Promise((resolve) => setTimeout(resolve, delay));
1833
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1834
+ }
1503
1835
  }
1504
- const jsonBody = await response.json();
1505
- const parsedResult = schema.safeParse(jsonBody);
1506
- if (parsedResult.success) {
1836
+ throw new APIConnectionError({
1837
+ cause: castToError2(error)
1838
+ });
1839
+ }
1840
+ }
1841
+ __name(_doZodFetch, "_doZodFetch");
1842
+ function castToError2(err) {
1843
+ if (err instanceof Error)
1844
+ return err;
1845
+ return new Error(err);
1846
+ }
1847
+ __name(castToError2, "castToError");
1848
+ function shouldRetry(response, attempt, retryOptions) {
1849
+ function shouldRetryForOptions() {
1850
+ const retry = {
1851
+ ...defaultRetryOptions2,
1852
+ ...retryOptions
1853
+ };
1854
+ const delay = calculateNextRetryDelay(retry, attempt);
1855
+ if (delay) {
1507
1856
  return {
1508
- ok: true,
1509
- data: parsedResult.data
1857
+ retry: true,
1858
+ delay
1510
1859
  };
1511
- }
1512
- if ("error" in jsonBody) {
1860
+ } else {
1513
1861
  return {
1514
- ok: false,
1515
- error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1862
+ retry: false
1516
1863
  };
1517
1864
  }
1865
+ }
1866
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1867
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1868
+ if (shouldRetryHeader === "true")
1869
+ return shouldRetryForOptions();
1870
+ if (shouldRetryHeader === "false")
1518
1871
  return {
1519
- ok: false,
1520
- error: parsedResult.error.message
1872
+ retry: false
1521
1873
  };
1522
- } catch (error) {
1523
- if (options?.retry) {
1524
- const retry = {
1525
- ...defaultRetryOptions,
1526
- ...options.retry
1527
- };
1528
- if (attempt > retry.maxAttempts) {
1529
- return {
1530
- ok: false,
1531
- error: error instanceof Error ? error.message : JSON.stringify(error)
1532
- };
1533
- }
1534
- const delay = calculateNextRetryDelay(retry, attempt);
1535
- await new Promise((resolve) => setTimeout(resolve, delay));
1536
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1874
+ if (response.status === 408)
1875
+ return shouldRetryForOptions();
1876
+ if (response.status === 409)
1877
+ return shouldRetryForOptions();
1878
+ if (response.status === 429)
1879
+ return shouldRetryForOptions();
1880
+ if (response.status >= 500)
1881
+ return shouldRetryForOptions();
1882
+ return {
1883
+ retry: false
1884
+ };
1885
+ }
1886
+ __name(shouldRetry, "shouldRetry");
1887
+ function safeJsonParse(text) {
1888
+ try {
1889
+ return JSON.parse(text);
1890
+ } catch (e) {
1891
+ return void 0;
1892
+ }
1893
+ }
1894
+ __name(safeJsonParse, "safeJsonParse");
1895
+ function createResponseHeaders(headers) {
1896
+ return new Proxy(Object.fromEntries(
1897
+ // @ts-ignore
1898
+ headers.entries()
1899
+ ), {
1900
+ get(target, name) {
1901
+ const key = name.toString();
1902
+ return target[key.toLowerCase()] || target[key];
1537
1903
  }
1538
- return {
1539
- ok: false,
1540
- error: error instanceof Error ? error.message : JSON.stringify(error)
1904
+ });
1905
+ }
1906
+ __name(createResponseHeaders, "createResponseHeaders");
1907
+ function requestInitWithCache(requestInit) {
1908
+ try {
1909
+ const withCache = {
1910
+ ...requestInit,
1911
+ cache: "no-cache"
1541
1912
  };
1913
+ const _ = new Request("http://localhost", withCache);
1914
+ return withCache;
1915
+ } catch (error) {
1916
+ return requestInit ?? {};
1542
1917
  }
1543
1918
  }
1544
- __name(_doZodFetch, "_doZodFetch");
1919
+ __name(requestInitWithCache, "requestInitWithCache");
1545
1920
 
1546
1921
  // src/v3/utils/flattenAttributes.ts
1547
1922
  function flattenAttributes(obj, prefix) {
@@ -1693,7 +2068,8 @@ var SemanticInternalAttributes = {
1693
2068
  SDK_LANGUAGE: "sdk.language",
1694
2069
  RETRY_AT: "retry.at",
1695
2070
  RETRY_DELAY: "retry.delay",
1696
- RETRY_COUNT: "retry.count"
2071
+ RETRY_COUNT: "retry.count",
2072
+ LINK_TITLE: "$link.title"
1697
2073
  };
1698
2074
 
1699
2075
  // src/v3/tasks/taskContextManager.ts
@@ -1829,7 +2205,7 @@ __name(getEnvVar, "getEnvVar");
1829
2205
  // src/v3/apiClient/index.ts
1830
2206
  var zodFetchOptions = {
1831
2207
  retry: {
1832
- maxAttempts: 5,
2208
+ maxAttempts: 3,
1833
2209
  minTimeoutInMs: 1e3,
1834
2210
  maxTimeoutInMs: 3e4,
1835
2211
  factor: 2,
@@ -1881,6 +2257,57 @@ var _ApiClient = class _ApiClient {
1881
2257
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1882
2258
  }, zodFetchOptions);
1883
2259
  }
2260
+ createSchedule(options) {
2261
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
2262
+ method: "POST",
2263
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2264
+ body: JSON.stringify(options)
2265
+ });
2266
+ }
2267
+ listSchedules(options) {
2268
+ const searchParams = new URLSearchParams();
2269
+ if (options?.page) {
2270
+ searchParams.append("page", options.page.toString());
2271
+ }
2272
+ if (options?.perPage) {
2273
+ searchParams.append("perPage", options.perPage.toString());
2274
+ }
2275
+ return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
2276
+ method: "GET",
2277
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2278
+ });
2279
+ }
2280
+ retrieveSchedule(scheduleId) {
2281
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2282
+ method: "GET",
2283
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2284
+ });
2285
+ }
2286
+ updateSchedule(scheduleId, options) {
2287
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2288
+ method: "PUT",
2289
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2290
+ body: JSON.stringify(options)
2291
+ });
2292
+ }
2293
+ deactivateSchedule(scheduleId) {
2294
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
2295
+ method: "POST",
2296
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2297
+ });
2298
+ }
2299
+ activateSchedule(scheduleId) {
2300
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
2301
+ method: "POST",
2302
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2303
+ });
2304
+ }
2305
+ deleteSchedule(scheduleId) {
2306
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2307
+ method: "DELETE",
2308
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2309
+ });
2310
+ }
1884
2311
  };
1885
2312
  _getHeaders = new WeakSet();
1886
2313
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
@@ -2794,11 +3221,6 @@ __name(unregisterGlobal, "unregisterGlobal");
2794
3221
  var _NoopRuntimeManager = class _NoopRuntimeManager {
2795
3222
  disable() {
2796
3223
  }
2797
- registerTasks() {
2798
- }
2799
- getTaskMetadata(id) {
2800
- return void 0;
2801
- }
2802
3224
  waitForDuration(ms) {
2803
3225
  return Promise.resolve();
2804
3226
  }
@@ -2858,12 +3280,6 @@ var _RuntimeAPI = class _RuntimeAPI {
2858
3280
  __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2859
3281
  unregisterGlobal(API_NAME);
2860
3282
  }
2861
- registerTasks(tasks) {
2862
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).registerTasks(tasks);
2863
- }
2864
- getTaskMetadata(id) {
2865
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).getTaskMetadata(id);
2866
- }
2867
3283
  };
2868
3284
  _getRuntimeManager = new WeakSet();
2869
3285
  getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
@@ -3009,7 +3425,7 @@ var _OtelTaskLogger = class _OtelTaskLogger {
3009
3425
  _emitLog = new WeakSet();
3010
3426
  emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
3011
3427
  let attributes = {
3012
- ...flattenAttributes(properties)
3428
+ ...flattenAttributes(safeJsonProcess(properties))
3013
3429
  };
3014
3430
  const icon = iconStringForSeverity(severityNumber);
3015
3431
  if (icon !== void 0) {
@@ -3046,6 +3462,14 @@ var _NoopTaskLogger = class _NoopTaskLogger {
3046
3462
  };
3047
3463
  __name(_NoopTaskLogger, "NoopTaskLogger");
3048
3464
  var NoopTaskLogger = _NoopTaskLogger;
3465
+ function safeJsonProcess(value) {
3466
+ try {
3467
+ return JSON.parse(JSON.stringify(value));
3468
+ } catch {
3469
+ return value;
3470
+ }
3471
+ }
3472
+ __name(safeJsonProcess, "safeJsonProcess");
3049
3473
 
3050
3474
  // src/v3/logger/index.ts
3051
3475
  var API_NAME3 = "logger";
@@ -3096,6 +3520,78 @@ var LoggerAPI = _LoggerAPI;
3096
3520
  // src/v3/logger-api.ts
3097
3521
  var logger = LoggerAPI.getInstance();
3098
3522
 
3523
+ // src/v3/task-catalog/noopTaskCatalog.ts
3524
+ var _NoopTaskCatalog = class _NoopTaskCatalog {
3525
+ registerTaskMetadata(task) {
3526
+ }
3527
+ registerTaskFileMetadata(id, metadata) {
3528
+ }
3529
+ updateTaskMetadata(id, updates) {
3530
+ }
3531
+ getAllTaskMetadata() {
3532
+ return [];
3533
+ }
3534
+ getTaskMetadata(id) {
3535
+ return void 0;
3536
+ }
3537
+ getTask(id) {
3538
+ return void 0;
3539
+ }
3540
+ disable() {
3541
+ }
3542
+ };
3543
+ __name(_NoopTaskCatalog, "NoopTaskCatalog");
3544
+ var NoopTaskCatalog = _NoopTaskCatalog;
3545
+
3546
+ // src/v3/task-catalog/index.ts
3547
+ var API_NAME4 = "task-catalog";
3548
+ var NOOP_TASK_CATALOG = new NoopTaskCatalog();
3549
+ var _getCatalog, getCatalog_fn;
3550
+ var _TaskCatalogAPI = class _TaskCatalogAPI {
3551
+ constructor() {
3552
+ __privateAdd(this, _getCatalog);
3553
+ }
3554
+ static getInstance() {
3555
+ if (!this._instance) {
3556
+ this._instance = new _TaskCatalogAPI();
3557
+ }
3558
+ return this._instance;
3559
+ }
3560
+ setGlobalTaskCatalog(taskCatalog2) {
3561
+ return registerGlobal(API_NAME4, taskCatalog2);
3562
+ }
3563
+ disable() {
3564
+ unregisterGlobal(API_NAME4);
3565
+ }
3566
+ registerTaskMetadata(task) {
3567
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
3568
+ }
3569
+ updateTaskMetadata(id, updates) {
3570
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).updateTaskMetadata(id, updates);
3571
+ }
3572
+ registerTaskFileMetadata(id, metadata) {
3573
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskFileMetadata(id, metadata);
3574
+ }
3575
+ getAllTaskMetadata() {
3576
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getAllTaskMetadata();
3577
+ }
3578
+ getTaskMetadata(id) {
3579
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTaskMetadata(id);
3580
+ }
3581
+ getTask(id) {
3582
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTask(id);
3583
+ }
3584
+ };
3585
+ _getCatalog = new WeakSet();
3586
+ getCatalog_fn = /* @__PURE__ */ __name(function() {
3587
+ return getGlobal(API_NAME4) ?? NOOP_TASK_CATALOG;
3588
+ }, "#getCatalog");
3589
+ __name(_TaskCatalogAPI, "TaskCatalogAPI");
3590
+ var TaskCatalogAPI = _TaskCatalogAPI;
3591
+
3592
+ // src/v3/task-catalog-api.ts
3593
+ var taskCatalog = TaskCatalogAPI.getInstance();
3594
+
3099
3595
  // src/v3/limits.ts
3100
3596
  var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
3101
3597
  var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
@@ -3213,34 +3709,32 @@ function formatDurationInDays(milliseconds) {
3213
3709
  return duration;
3214
3710
  }
3215
3711
  __name(formatDurationInDays, "formatDurationInDays");
3712
+ async function unboundedTimeout(delay = 0, value, options) {
3713
+ const maxDelay = 2147483647;
3714
+ const fullTimeouts = Math.floor(delay / maxDelay);
3715
+ const remainingDelay = delay % maxDelay;
3716
+ let lastTimeoutResult = await promises.setTimeout(remainingDelay, value, options);
3717
+ for (let i = 0; i < fullTimeouts; i++) {
3718
+ lastTimeoutResult = await promises.setTimeout(maxDelay, value, options);
3719
+ }
3720
+ return lastTimeoutResult;
3721
+ }
3722
+ __name(unboundedTimeout, "unboundedTimeout");
3216
3723
 
3217
3724
  // src/v3/runtime/devRuntimeManager.ts
3218
3725
  var _DevRuntimeManager = class _DevRuntimeManager {
3219
3726
  constructor() {
3220
3727
  __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3221
3728
  __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3222
- __publicField(this, "_tasks", /* @__PURE__ */ new Map());
3223
3729
  __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3224
3730
  }
3225
3731
  disable() {
3226
3732
  }
3227
- registerTasks(tasks) {
3228
- for (const task of tasks) {
3229
- this._tasks.set(task.id, task);
3230
- }
3231
- }
3232
- getTaskMetadata(id) {
3233
- return this._tasks.get(id);
3234
- }
3235
3733
  async waitForDuration(ms) {
3236
- return new Promise((resolve) => {
3237
- setTimeout(resolve, ms);
3238
- });
3734
+ await unboundedTimeout(ms);
3239
3735
  }
3240
3736
  async waitUntil(date) {
3241
- return new Promise((resolve) => {
3242
- setTimeout(resolve, date.getTime() - Date.now());
3243
- });
3737
+ return this.waitForDuration(date.getTime() - Date.now());
3244
3738
  }
3245
3739
  async waitForTask(params) {
3246
3740
  const pendingCompletion = this._pendingCompletionNotifications.get(params.id);
@@ -3303,27 +3797,20 @@ var _DevRuntimeManager = class _DevRuntimeManager {
3303
3797
  };
3304
3798
  __name(_DevRuntimeManager, "DevRuntimeManager");
3305
3799
  var DevRuntimeManager = _DevRuntimeManager;
3800
+
3801
+ // src/v3/runtime/prodRuntimeManager.ts
3306
3802
  var _ProdRuntimeManager = class _ProdRuntimeManager {
3307
3803
  constructor(ipc, options = {}) {
3308
3804
  this.ipc = ipc;
3309
3805
  this.options = options;
3310
3806
  this._taskWaits = /* @__PURE__ */ new Map();
3311
3807
  this._batchWaits = /* @__PURE__ */ new Map();
3312
- this._tasks = /* @__PURE__ */ new Map();
3313
3808
  }
3314
3809
  disable() {
3315
3810
  }
3316
- registerTasks(tasks) {
3317
- for (const task of tasks) {
3318
- this._tasks.set(task.id, task);
3319
- }
3320
- }
3321
- getTaskMetadata(id) {
3322
- return this._tasks.get(id);
3323
- }
3324
3811
  async waitForDuration(ms) {
3325
3812
  const now = Date.now();
3326
- const resolveAfterDuration = promises.setTimeout(ms, "duration");
3813
+ const resolveAfterDuration = unboundedTimeout(ms, "duration");
3327
3814
  if (ms <= this.waitThresholdInMs) {
3328
3815
  await resolveAfterDuration;
3329
3816
  return;
@@ -3525,11 +4012,12 @@ __name(_TriggerTracer, "TriggerTracer");
3525
4012
  var TriggerTracer = _TriggerTracer;
3526
4013
  var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3527
4014
  var _ConsoleInterceptor = class _ConsoleInterceptor {
3528
- constructor(logger2) {
4015
+ constructor(logger2, sendToStdIO) {
3529
4016
  __privateAdd(this, _handleLog);
3530
4017
  __privateAdd(this, _getTimestampInHrTime2);
3531
4018
  __privateAdd(this, _getAttributes);
3532
4019
  this.logger = logger2;
4020
+ this.sendToStdIO = sendToStdIO;
3533
4021
  }
3534
4022
  // Intercept the console and send logs to the OpenTelemetry logger
3535
4023
  // during the execution of the callback
@@ -3538,12 +4026,14 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3538
4026
  log: console2.log,
3539
4027
  info: console2.info,
3540
4028
  warn: console2.warn,
3541
- error: console2.error
4029
+ error: console2.error,
4030
+ debug: console2.debug
3542
4031
  };
3543
4032
  console2.log = this.log.bind(this);
3544
4033
  console2.info = this.info.bind(this);
3545
4034
  console2.warn = this.warn.bind(this);
3546
4035
  console2.error = this.error.bind(this);
4036
+ console2.debug = this.debug.bind(this);
3547
4037
  try {
3548
4038
  return await callback();
3549
4039
  } finally {
@@ -3551,8 +4041,12 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3551
4041
  console2.info = originalConsole.info;
3552
4042
  console2.warn = originalConsole.warn;
3553
4043
  console2.error = originalConsole.error;
4044
+ console2.debug = originalConsole.debug;
3554
4045
  }
3555
4046
  }
4047
+ debug(...args) {
4048
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
4049
+ }
3556
4050
  log(...args) {
3557
4051
  __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3558
4052
  }
@@ -3569,6 +4063,13 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3569
4063
  _handleLog = new WeakSet();
3570
4064
  handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3571
4065
  const body = util__default.default.format(...args);
4066
+ if (this.sendToStdIO) {
4067
+ if (severityNumber === apiLogs.SeverityNumber.ERROR) {
4068
+ process.stderr.write(body);
4069
+ } else {
4070
+ process.stdout.write(body);
4071
+ }
4072
+ }
3572
4073
  const parsed = tryParseJSON(body);
3573
4074
  if (parsed.ok) {
3574
4075
  this.logger.emit({
@@ -3644,113 +4145,6 @@ function tryParseJSON(value) {
3644
4145
  }
3645
4146
  __name(tryParseJSON, "tryParseJSON");
3646
4147
 
3647
- // src/retry.ts
3648
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3649
- if (!resets)
3650
- return;
3651
- switch (format) {
3652
- case "iso_8601_duration_openai_variant": {
3653
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3654
- }
3655
- case "iso_8601": {
3656
- return calculateISO8601ResetAt(resets, now);
3657
- }
3658
- case "unix_timestamp": {
3659
- return calculateUnixTimestampResetAt(resets, now);
3660
- }
3661
- case "unix_timestamp_in_ms": {
3662
- return calculateUnixTimestampInMsResetAt(resets, now);
3663
- }
3664
- }
3665
- }
3666
- __name(calculateResetAt, "calculateResetAt");
3667
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3668
- if (!resets)
3669
- return void 0;
3670
- const resetAt = parseInt(resets, 10);
3671
- if (isNaN(resetAt))
3672
- return void 0;
3673
- return new Date(resetAt * 1e3);
3674
- }
3675
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3676
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3677
- if (!resets)
3678
- return void 0;
3679
- const resetAt = parseInt(resets, 10);
3680
- if (isNaN(resetAt))
3681
- return void 0;
3682
- return new Date(resetAt);
3683
- }
3684
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3685
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3686
- if (!resets)
3687
- return void 0;
3688
- const resetAt = new Date(resets);
3689
- if (isNaN(resetAt.getTime()))
3690
- return void 0;
3691
- return resetAt;
3692
- }
3693
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3694
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3695
- if (!resets)
3696
- return void 0;
3697
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3698
- const match = resets.match(pattern);
3699
- if (!match)
3700
- return void 0;
3701
- const days = parseInt(match[1], 10) || 0;
3702
- const hours = parseInt(match[2], 10) || 0;
3703
- const minutes = parseInt(match[3], 10) || 0;
3704
- const seconds = parseFloat(match[4]) || 0;
3705
- const milliseconds = parseInt(match[5], 10) || 0;
3706
- const resetAt = new Date(now);
3707
- resetAt.setDate(resetAt.getDate() + days);
3708
- resetAt.setHours(resetAt.getHours() + hours);
3709
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
3710
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3711
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3712
- return resetAt;
3713
- }
3714
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3715
-
3716
- // src/v3/utils/retries.ts
3717
- var defaultRetryOptions = {
3718
- maxAttempts: 3,
3719
- factor: 2,
3720
- minTimeoutInMs: 1e3,
3721
- maxTimeoutInMs: 6e4,
3722
- randomize: true
3723
- };
3724
- var defaultFetchRetryOptions = {
3725
- byStatus: {
3726
- "429,408,409,5xx": {
3727
- strategy: "backoff",
3728
- ...defaultRetryOptions
3729
- }
3730
- },
3731
- connectionError: defaultRetryOptions,
3732
- timeout: defaultRetryOptions
3733
- };
3734
- function calculateNextRetryDelay(options, attempt) {
3735
- const opts = {
3736
- ...defaultRetryOptions,
3737
- ...options
3738
- };
3739
- if (attempt >= opts.maxAttempts) {
3740
- return;
3741
- }
3742
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3743
- const random = randomize ? Math.random() + 1 : 1;
3744
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3745
- return Math.round(timeout);
3746
- }
3747
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3748
- function calculateResetAt2(resets, format, now = Date.now()) {
3749
- const resetAt = calculateResetAt(resets, format, new Date(now));
3750
- return resetAt?.getTime();
3751
- }
3752
- __name(calculateResetAt2, "calculateResetAt");
3753
-
3754
4148
  // src/v3/utils/styleAttributes.ts
3755
4149
  function accessoryAttributes(accessory) {
3756
4150
  return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
@@ -4111,6 +4505,7 @@ async function stringifyIO(value) {
4111
4505
  };
4112
4506
  } catch {
4113
4507
  return {
4508
+ data: value,
4114
4509
  dataType: "application/json"
4115
4510
  };
4116
4511
  }
@@ -4155,23 +4550,20 @@ __name(packetRequiresOffloading, "packetRequiresOffloading");
4155
4550
  async function exportPacket(packet, pathPrefix) {
4156
4551
  const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
4157
4552
  const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
4158
- if (presignedResponse.ok) {
4159
- const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
4160
- method: "PUT",
4161
- headers: {
4162
- "Content-Type": packet.dataType
4163
- },
4164
- body: packet.data
4165
- });
4166
- if (!uploadResponse.ok) {
4167
- throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
4168
- }
4169
- return {
4170
- data: filename,
4171
- dataType: "application/store"
4172
- };
4553
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
4554
+ method: "PUT",
4555
+ headers: {
4556
+ "Content-Type": packet.dataType
4557
+ },
4558
+ body: packet.data
4559
+ });
4560
+ if (!uploadResponse.ok) {
4561
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
4173
4562
  }
4174
- return packet;
4563
+ return {
4564
+ data: filename,
4565
+ dataType: "application/store"
4566
+ };
4175
4567
  }
4176
4568
  __name(exportPacket, "exportPacket");
4177
4569
  async function conditionallyImportPacket(packet, tracer) {
@@ -4200,19 +4592,16 @@ async function importPacket(packet, span) {
4200
4592
  return packet;
4201
4593
  }
4202
4594
  const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
4203
- if (presignedResponse.ok) {
4204
- const response = await fetch(presignedResponse.data.presignedUrl);
4205
- if (!response.ok) {
4206
- throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
4207
- }
4208
- const data = await response.text();
4209
- span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4210
- return {
4211
- data,
4212
- dataType: response.headers.get("content-type") ?? "application/json"
4213
- };
4595
+ const response = await fetch(presignedResponse.presignedUrl);
4596
+ if (!response.ok) {
4597
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
4214
4598
  }
4215
- return packet;
4599
+ const data = await response.text();
4600
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4601
+ return {
4602
+ data,
4603
+ dataType: response.headers.get("content-type") ?? "application/json"
4604
+ };
4216
4605
  }
4217
4606
  __name(importPacket, "importPacket");
4218
4607
  async function createPacketAttributes(packet, dataKey, dataTypeKey) {
@@ -4265,7 +4654,7 @@ async function createPacketAttributesAsJson(data, dataType) {
4265
4654
  case "application/super+json":
4266
4655
  const { deserialize } = await loadSuperJSON();
4267
4656
  const deserialized = deserialize(data);
4268
- const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
4657
+ const jsonify = safeJsonParse2(JSON.stringify(deserialized, safeReplacer));
4269
4658
  return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
4270
4659
  case "application/store":
4271
4660
  return data;
@@ -4279,10 +4668,16 @@ async function prettyPrintPacket(rawData, dataType) {
4279
4668
  return "";
4280
4669
  }
4281
4670
  if (dataType === "application/super+json") {
4671
+ if (typeof rawData === "string") {
4672
+ rawData = safeJsonParse2(rawData);
4673
+ }
4282
4674
  const { deserialize } = await loadSuperJSON();
4283
4675
  return await prettyPrintPacket(deserialize(rawData), "application/json");
4284
4676
  }
4285
4677
  if (dataType === "application/json") {
4678
+ if (typeof rawData === "string") {
4679
+ rawData = safeJsonParse2(rawData);
4680
+ }
4286
4681
  return JSON.stringify(rawData, safeReplacer, 2);
4287
4682
  }
4288
4683
  if (typeof rawData === "string") {
@@ -4328,14 +4723,14 @@ async function loadSuperJSON() {
4328
4723
  return await import('superjson');
4329
4724
  }
4330
4725
  __name(loadSuperJSON, "loadSuperJSON");
4331
- function safeJsonParse(value) {
4726
+ function safeJsonParse2(value) {
4332
4727
  try {
4333
4728
  return JSON.parse(value);
4334
4729
  } catch {
4335
4730
  return;
4336
4731
  }
4337
4732
  }
4338
- __name(safeJsonParse, "safeJsonParse");
4733
+ __name(safeJsonParse2, "safeJsonParse");
4339
4734
 
4340
4735
  // src/v3/workers/taskExecutor.ts
4341
4736
  var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
@@ -4607,7 +5002,8 @@ var dependencies = {
4607
5002
  superjson: "^2.2.1",
4608
5003
  ulidx: "^2.2.1",
4609
5004
  zod: "3.22.3",
4610
- "zod-error": "1.5.0"
5005
+ "zod-error": "1.5.0",
5006
+ "zod-validation-error": "^1.5.0"
4611
5007
  };
4612
5008
 
4613
5009
  // src/v3/utils/detectDependencyVersion.ts
@@ -4616,6 +5012,84 @@ function detectDependencyVersion(dependency) {
4616
5012
  }
4617
5013
  __name(detectDependencyVersion, "detectDependencyVersion");
4618
5014
 
5015
+ // src/v3/task-catalog/standardTaskCatalog.ts
5016
+ var _StandardTaskCatalog = class _StandardTaskCatalog {
5017
+ constructor() {
5018
+ __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
5019
+ __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
5020
+ __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
5021
+ }
5022
+ registerTaskMetadata(task) {
5023
+ const { fns, ...metadata } = task;
5024
+ this._taskMetadata.set(task.id, metadata);
5025
+ this._taskFunctions.set(task.id, fns);
5026
+ }
5027
+ updateTaskMetadata(id, updates) {
5028
+ const existingMetadata = this._taskMetadata.get(id);
5029
+ if (existingMetadata) {
5030
+ this._taskMetadata.set(id, {
5031
+ ...existingMetadata,
5032
+ ...updates
5033
+ });
5034
+ }
5035
+ if (updates.fns) {
5036
+ const existingFunctions = this._taskFunctions.get(id);
5037
+ if (existingFunctions) {
5038
+ this._taskFunctions.set(id, {
5039
+ ...existingFunctions,
5040
+ ...updates.fns
5041
+ });
5042
+ }
5043
+ }
5044
+ }
5045
+ registerTaskFileMetadata(id, metadata) {
5046
+ this._taskFileMetadata.set(id, metadata);
5047
+ }
5048
+ // Return all the tasks, without the functions
5049
+ getAllTaskMetadata() {
5050
+ const result = [];
5051
+ for (const [id, metadata] of this._taskMetadata) {
5052
+ const fileMetadata = this._taskFileMetadata.get(id);
5053
+ if (!fileMetadata) {
5054
+ continue;
5055
+ }
5056
+ result.push({
5057
+ ...metadata,
5058
+ ...fileMetadata
5059
+ });
5060
+ }
5061
+ return result;
5062
+ }
5063
+ getTaskMetadata(id) {
5064
+ const metadata = this._taskMetadata.get(id);
5065
+ const fileMetadata = this._taskFileMetadata.get(id);
5066
+ if (!metadata || !fileMetadata) {
5067
+ return void 0;
5068
+ }
5069
+ return {
5070
+ ...metadata,
5071
+ ...fileMetadata
5072
+ };
5073
+ }
5074
+ getTask(id) {
5075
+ const metadata = this._taskMetadata.get(id);
5076
+ const fileMetadata = this._taskFileMetadata.get(id);
5077
+ const fns = this._taskFunctions.get(id);
5078
+ if (!metadata || !fns || !fileMetadata) {
5079
+ return void 0;
5080
+ }
5081
+ return {
5082
+ ...metadata,
5083
+ ...fileMetadata,
5084
+ fns
5085
+ };
5086
+ }
5087
+ disable() {
5088
+ }
5089
+ };
5090
+ __name(_StandardTaskCatalog, "StandardTaskCatalog");
5091
+ var StandardTaskCatalog = _StandardTaskCatalog;
5092
+
4619
5093
  // src/v3/index.ts
4620
5094
  function parseTriggerTaskRequestBody(body) {
4621
5095
  return TriggerTaskRequestBody.safeParse(body);
@@ -4626,12 +5100,16 @@ function parseBatchTriggerTaskRequestBody(body) {
4626
5100
  }
4627
5101
  __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
4628
5102
 
5103
+ exports.APIConnectionError = APIConnectionError;
5104
+ exports.APIError = APIError;
4629
5105
  exports.ApiClient = ApiClient;
4630
5106
  exports.ApiClientManager = ApiClientManager;
5107
+ exports.AuthenticationError = AuthenticationError;
4631
5108
  exports.BackgroundWorkerClientMessages = BackgroundWorkerClientMessages;
4632
5109
  exports.BackgroundWorkerMetadata = BackgroundWorkerMetadata;
4633
5110
  exports.BackgroundWorkerProperties = BackgroundWorkerProperties;
4634
5111
  exports.BackgroundWorkerServerMessages = BackgroundWorkerServerMessages;
5112
+ exports.BadRequestError = BadRequestError;
4635
5113
  exports.BatchTaskRunExecutionResult = BatchTaskRunExecutionResult;
4636
5114
  exports.BatchTriggerTaskRequestBody = BatchTriggerTaskRequestBody;
4637
5115
  exports.BatchTriggerTaskResponse = BatchTriggerTaskResponse;
@@ -4639,13 +5117,16 @@ exports.CanceledRunResponse = CanceledRunResponse;
4639
5117
  exports.CancellationSpanEvent = CancellationSpanEvent;
4640
5118
  exports.ClientToSharedQueueMessages = ClientToSharedQueueMessages;
4641
5119
  exports.Config = Config;
5120
+ exports.ConflictError = ConflictError;
4642
5121
  exports.ConsoleInterceptor = ConsoleInterceptor;
4643
5122
  exports.CoordinatorToPlatformMessages = CoordinatorToPlatformMessages;
4644
5123
  exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
4645
5124
  exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
4646
5125
  exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
4647
5126
  exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
5127
+ exports.CreateScheduleOptions = CreateScheduleOptions;
4648
5128
  exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
5129
+ exports.DeletedScheduleObject = DeletedScheduleObject;
4649
5130
  exports.DeploymentErrorData = DeploymentErrorData;
4650
5131
  exports.DevRuntimeManager = DevRuntimeManager;
4651
5132
  exports.DurableClock = PreciseWallClock;
@@ -4672,9 +5153,13 @@ exports.GetProjectsResponseBody = GetProjectsResponseBody;
4672
5153
  exports.ImageDetailsMetadata = ImageDetailsMetadata;
4673
5154
  exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
4674
5155
  exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
5156
+ exports.InternalServerError = InternalServerError;
5157
+ exports.ListScheduleOptions = ListScheduleOptions;
5158
+ exports.ListSchedulesResult = ListSchedulesResult;
4675
5159
  exports.Machine = Machine;
4676
5160
  exports.MachineCpu = MachineCpu;
4677
5161
  exports.MachineMemory = MachineMemory;
5162
+ exports.NotFoundError = NotFoundError;
4678
5163
  exports.OFFLOAD_IO_PACKET_LENGTH_LIMIT = OFFLOAD_IO_PACKET_LENGTH_LIMIT;
4679
5164
  exports.OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT;
4680
5165
  exports.OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT;
@@ -4687,6 +5172,7 @@ exports.OTEL_SPAN_EVENT_COUNT_LIMIT = OTEL_SPAN_EVENT_COUNT_LIMIT;
4687
5172
  exports.OtelTaskLogger = OtelTaskLogger;
4688
5173
  exports.OtherSpanEvent = OtherSpanEvent;
4689
5174
  exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
5175
+ exports.PermissionDeniedError = PermissionDeniedError;
4690
5176
  exports.PlatformToCoordinatorMessages = PlatformToCoordinatorMessages;
4691
5177
  exports.PlatformToProviderMessages = PlatformToProviderMessages;
4692
5178
  exports.PostStartCauses = PostStartCauses;
@@ -4700,9 +5186,12 @@ exports.ProdWorkerToChildMessages = ProdWorkerToChildMessages;
4700
5186
  exports.ProdWorkerToCoordinatorMessages = ProdWorkerToCoordinatorMessages;
4701
5187
  exports.ProviderToPlatformMessages = ProviderToPlatformMessages;
4702
5188
  exports.QueueOptions = QueueOptions;
5189
+ exports.RateLimitError = RateLimitError;
4703
5190
  exports.RateLimitOptions = RateLimitOptions;
4704
5191
  exports.ReplayRunResponse = ReplayRunResponse;
4705
5192
  exports.RetryOptions = RetryOptions;
5193
+ exports.ScheduleObject = ScheduleObject;
5194
+ exports.ScheduledTaskPayload = ScheduledTaskPayload;
4706
5195
  exports.SemanticInternalAttributes = SemanticInternalAttributes;
4707
5196
  exports.SharedQueueToClientMessages = SharedQueueToClientMessages;
4708
5197
  exports.SimpleStructuredLogger = SimpleStructuredLogger;
@@ -4710,11 +5199,13 @@ exports.SlidingWindowRateLimit = SlidingWindowRateLimit;
4710
5199
  exports.SpanEvent = SpanEvent;
4711
5200
  exports.SpanEvents = SpanEvents;
4712
5201
  exports.SpanMessagingEvent = SpanMessagingEvent;
5202
+ exports.StandardTaskCatalog = StandardTaskCatalog;
4713
5203
  exports.StartDeploymentIndexingRequestBody = StartDeploymentIndexingRequestBody;
4714
5204
  exports.StartDeploymentIndexingResponseBody = StartDeploymentIndexingResponseBody;
4715
5205
  exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
4716
5206
  exports.TaskEventStyle = TaskEventStyle;
4717
5207
  exports.TaskExecutor = TaskExecutor;
5208
+ exports.TaskFileMetadata = TaskFileMetadata;
4718
5209
  exports.TaskMetadata = TaskMetadata;
4719
5210
  exports.TaskMetadataFailedToParseData = TaskMetadataFailedToParseData;
4720
5211
  exports.TaskMetadataWithFilePath = TaskMetadataWithFilePath;
@@ -4745,6 +5236,8 @@ exports.TriggerTaskRequestBody = TriggerTaskRequestBody;
4745
5236
  exports.TriggerTaskResponse = TriggerTaskResponse;
4746
5237
  exports.TriggerTracer = TriggerTracer;
4747
5238
  exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
5239
+ exports.UnprocessableEntityError = UnprocessableEntityError;
5240
+ exports.UpdateScheduleOptions = UpdateScheduleOptions;
4748
5241
  exports.WaitReason = WaitReason;
4749
5242
  exports.WhoAmIResponseSchema = WhoAmIResponseSchema;
4750
5243
  exports.ZodIpcConnection = ZodIpcConnection;
@@ -4801,6 +5294,7 @@ exports.runtime = runtime;
4801
5294
  exports.serverWebsocketMessages = serverWebsocketMessages;
4802
5295
  exports.stringPatternMatchers = stringPatternMatchers;
4803
5296
  exports.stringifyIO = stringifyIO;
5297
+ exports.taskCatalog = taskCatalog;
4804
5298
  exports.taskContextManager = taskContextManager;
4805
5299
  exports.unflattenAttributes = unflattenAttributes;
4806
5300
  exports.workerToChildMessages = workerToChildMessages;