withruntime 0.35.0 → 0.45.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.
Files changed (60) hide show
  1. package/BLAXEL.md +207 -204
  2. package/COMPATIBILITY.md +367 -337
  3. package/DAYTONA.md +180 -173
  4. package/E2B.md +246 -230
  5. package/README.md +182 -142
  6. package/README.src.md +182 -142
  7. package/VERCEL.md +173 -168
  8. package/agent-platforms-inventory.json +387 -0
  9. package/dist/agents-cli.d.ts +7 -1
  10. package/dist/agents-cli.js +470 -6
  11. package/dist/agents-deploy.d.ts +1 -1
  12. package/dist/agents-deploy.js +62 -1
  13. package/dist/apps-cli.d.ts +3 -3
  14. package/dist/apps-cli.js +10 -5
  15. package/dist/browsers-cli.d.ts +1 -1
  16. package/dist/browsers-cli.js +122 -3
  17. package/dist/ci-cli.d.ts +11 -1
  18. package/dist/ci-cli.js +69 -6
  19. package/dist/cli-update.d.ts +11 -0
  20. package/dist/cli-update.js +46 -0
  21. package/dist/cli-words.js +1 -0
  22. package/dist/cli.d.ts +4 -6
  23. package/dist/cli.js +249 -58
  24. package/dist/daytona/daytona.js +1 -1
  25. package/dist/e2b/sandbox.d.ts +6 -5
  26. package/dist/e2b/sandbox.js +6 -5
  27. package/dist/errors.d.ts +4 -3
  28. package/dist/errors.js +7 -3
  29. package/dist/index.d.ts +5 -5
  30. package/dist/inngest/index.d.ts +96 -0
  31. package/dist/inngest/index.js +183 -0
  32. package/dist/jobs-code/cron.d.ts +12 -0
  33. package/dist/jobs-code/cron.js +93 -0
  34. package/dist/jobs-code/registry.d.ts +31 -0
  35. package/dist/jobs-code/registry.js +30 -0
  36. package/dist/jobs-code/runner.d.ts +1 -0
  37. package/dist/jobs-code/runner.js +74 -0
  38. package/dist/jobs-deploy.d.ts +22 -0
  39. package/dist/jobs-deploy.js +247 -0
  40. package/dist/jobs-import.d.ts +15 -0
  41. package/dist/jobs-import.js +231 -0
  42. package/dist/products/agents.d.ts +413 -2
  43. package/dist/products/agents.js +176 -0
  44. package/dist/products/apps.d.ts +2 -1
  45. package/dist/products/browsers.d.ts +87 -0
  46. package/dist/products/browsers.js +67 -0
  47. package/dist/products/builds.d.ts +11 -2
  48. package/dist/products/ci.d.ts +21 -1
  49. package/dist/products/jobs.d.ts +77 -0
  50. package/dist/products/jobs.js +5 -0
  51. package/dist/products/observability.d.ts +31 -3
  52. package/dist/products/plans.d.ts +5 -3
  53. package/dist/products/secrets.d.ts +67 -14
  54. package/dist/products/secrets.js +41 -12
  55. package/dist/transport.d.ts +6 -1
  56. package/dist/transport.js +38 -1
  57. package/dist/trigger/index.d.ts +202 -0
  58. package/dist/trigger/index.js +244 -0
  59. package/dist/types.d.ts +14 -0
  60. package/package.json +14 -3
@@ -201,10 +201,11 @@ export declare class Sandbox {
201
201
  getPublicHost(port: number): Promise<string>;
202
202
  get git(): never;
203
203
  /** E2B's metrics, from Runtime's measured readings (`sbx.metrics()`): CPU
204
- * as a percent of the sandbox's vCPUs and resident memory, one entry per
205
- * host reading (every minute by default) between `start` and `end`, kept
206
- * 24 hours at that resolution. Disk use inside the sandbox is not measured:
207
- * `diskUsed` is null and `diskTotal` is the disk's size. */
204
+ * as a percent of the sandbox's vCPUs, resident memory and the bytes used
205
+ * on the root file system (`df /`), one entry per bucket between `start`
206
+ * and `end` (10 s buckets over the last 15 minutes, of readings every
207
+ * 30 s), kept 24 hours at that resolution. `diskTotal` is the disk's size;
208
+ * `diskUsed` is null only for a reading the sandbox did not answer. */
208
209
  getMetrics(opts?: MetricsOpts): Promise<E2BSandboxMetrics[]>;
209
210
  static getMetrics(sandboxId: string, opts?: MetricsOpts & SandboxApiOpts): Promise<E2BSandboxMetrics[]>;
210
211
  updateNetwork(): Promise<never>;
@@ -240,7 +241,7 @@ export type E2BSandboxMetrics = {
240
241
  cpuCount: number;
241
242
  memUsed: number;
242
243
  memTotal: number;
243
- /** Not measured by Runtime: null. */
244
+ /** Bytes used on the root file system; null where a reading carries none. */
244
245
  diskUsed: number | null;
245
246
  diskTotal: number;
246
247
  };
@@ -567,10 +567,11 @@ export class Sandbox {
567
567
  throw new NotSupportedError("E2B's git module (deprecated by E2B too)", "Run git with sandbox.commands.run('git ...'); git is installed.");
568
568
  }
569
569
  /** E2B's metrics, from Runtime's measured readings (`sbx.metrics()`): CPU
570
- * as a percent of the sandbox's vCPUs and resident memory, one entry per
571
- * host reading (every minute by default) between `start` and `end`, kept
572
- * 24 hours at that resolution. Disk use inside the sandbox is not measured:
573
- * `diskUsed` is null and `diskTotal` is the disk's size. */
570
+ * as a percent of the sandbox's vCPUs, resident memory and the bytes used
571
+ * on the root file system (`df /`), one entry per bucket between `start`
572
+ * and `end` (10 s buckets over the last 15 minutes, of readings every
573
+ * 30 s), kept 24 hours at that resolution. `diskTotal` is the disk's size;
574
+ * `diskUsed` is null only for a reading the sandbox did not answer. */
574
575
  async getMetrics(opts = {}) {
575
576
  return e2bMetrics(this.#runtime, opts);
576
577
  }
@@ -774,7 +775,7 @@ async function e2bMetrics(runtime, opts) {
774
775
  cpuCount: metrics.vcpu,
775
776
  memUsed: point.memoryBytes,
776
777
  memTotal: metrics.memoryLimitBytes,
777
- diskUsed: null,
778
+ diskUsed: point.diskUsedBytes ?? null,
778
779
  diskTotal: metrics.diskLimitBytes,
779
780
  }));
780
781
  }
package/dist/errors.d.ts CHANGED
@@ -3,8 +3,9 @@
3
3
  * (runtime.feedback.submit, `runtime feedback`, or support). */
4
4
  /** A product switched off on this deployment, or paused on purpose: the API
5
5
  * answers these with 501 (503 from an older server) in fixed words, and
6
- * retrying cannot change them. host_unavailable and busy pass, and are
7
- * retried. The API also says so itself (`retryable: false`); this set is for
6
+ * retrying cannot change them. host_unavailable, busy and secret_withheld (a
7
+ * host that cannot give a machine its real-value secret right now) pass, and
8
+ * are retried. The API also says so itself (`retryable: false`); this set is for
8
9
  * a server too old to. */
9
10
  export declare const DELIBERATE: ReadonlySet<string>;
10
11
  /** Refusals that guarantee nothing ran: a sandbox running as many commands
@@ -15,7 +16,7 @@ export declare const DELIBERATE: ReadonlySet<string>;
15
16
  export declare const NOTHING_RAN: ReadonlySet<string>;
16
17
  /** Refusals of a create that clear when a sandbox stops or pauses, or a host
17
18
  * frees room: an account without credit's four at once and its total, an
18
- * email domain's, the account's quota and the region's capacity. `sandboxes.create` waits them out, retrying
19
+ * email domain's, the account's quota, its share of the region's servers and the region's capacity. `sandboxes.create` waits them out, retrying
19
20
  * with the same key and input, for up to `waitForCapacityMs`. */
20
21
  export declare const WAITS_FOR_ROOM: ReadonlySet<string>;
21
22
  export declare class RuntimeError extends Error {
package/dist/errors.js CHANGED
@@ -3,8 +3,9 @@
3
3
  * (runtime.feedback.submit, `runtime feedback`, or support). */
4
4
  /** A product switched off on this deployment, or paused on purpose: the API
5
5
  * answers these with 501 (503 from an older server) in fixed words, and
6
- * retrying cannot change them. host_unavailable and busy pass, and are
7
- * retried. The API also says so itself (`retryable: false`); this set is for
6
+ * retrying cannot change them. host_unavailable, busy and secret_withheld (a
7
+ * host that cannot give a machine its real-value secret right now) pass, and
8
+ * are retried. The API also says so itself (`retryable: false`); this set is for
8
9
  * a server too old to. */
9
10
  export const DELIBERATE = new Set([
10
11
  "unavailable",
@@ -36,7 +37,7 @@ export const NOTHING_RAN = new Set(["guest_busy", "busy", "rate_limited"]);
36
37
  const PASSING = new Set(["no_capacity", "no_credit_running_limit", "no_credit_total_limit"]);
37
38
  /** Refusals of a create that clear when a sandbox stops or pauses, or a host
38
39
  * frees room: an account without credit's four at once and its total, an
39
- * email domain's, the account's quota and the region's capacity. `sandboxes.create` waits them out, retrying
40
+ * email domain's, the account's quota, its share of the region's servers and the region's capacity. `sandboxes.create` waits them out, retrying
40
41
  * with the same key and input, for up to `waitForCapacityMs`. */
41
42
  export const WAITS_FOR_ROOM = new Set([
42
43
  "no_credit_running_limit",
@@ -44,6 +45,9 @@ export const WAITS_FOR_ROOM = new Set([
44
45
  "no_credit_domain_limit",
45
46
  "no_credit_capacity_full",
46
47
  "quota_exceeded",
48
+ // The account holds its share of every server that could run it: clears
49
+ // as its own sandboxes end.
50
+ "account_share_full",
47
51
  "no_capacity",
48
52
  // A volume whose last sandbox is stopping: free once the stop lets go of
49
53
  // its disk, up to about a minute (measured 50 to 60 s, 6 October 2026).
package/dist/index.d.ts CHANGED
@@ -25,11 +25,11 @@ export type { FileEvent, FileEventType, WatchHandle, WatchNotice, WatchOptions,
25
25
  export type { Mount, MountBucket } from "./products/mounts.js";
26
26
  export type { TailscaleJoin, TailscaleJoined, TailscaleNode, TailscaleStatus, } from "./products/tailscale.js";
27
27
  export type { Volume, VolumeBackup, VolumeBackupKeep, VolumeBackupSchedule, CreateVolume, VolumeAttachment, } from "./products/volumes.js";
28
- export type { CreateJob, Job, JobAlert, JobAlertDelivery, JobCompute, JobDefinition, JobLogs, JobRun, JobRunState, JobSchedule, UpdateJob, } from "./products/jobs.js";
28
+ export type { CreateJob, Job, JobAlert, JobAlertDelivery, JobCompute, JobDefinition, JobImportJob, JobImportPlan, JobImportRequest, JobImportSchedule, JobLogs, JobRun, JobRunState, JobSchedule, UpdateJob, } from "./products/jobs.js";
29
29
  export type { CheckedDomain, DnsRecord, Domain, EgressAddress, TcpPort, Tunnel as PrivateTunnel, TunnelPeer, TunnelPeerCreated, SetUpstreamProxy, UpstreamProxy, } from "./products/network-products.js";
30
30
  export type { PrivateNetwork } from "./products/private-network.js";
31
31
  export type { SignedRequests } from "./products/signed-requests.js";
32
- export { verifyWebhook, WebhookVerificationError, type MetricPoint, type MetricRange, type OtelExport, type RuntimeEvent, type SandboxMetrics, type Webhook, type WebhookDelivery, type WebhookEventType, } from "./products/observability.js";
32
+ export { verifyWebhook, WebhookVerificationError, type MetricPoint, type MetricRange, type OtelExport, type OtelSignal, type RuntimeEvent, type SandboxMetrics, type Webhook, type WebhookDelivery, type WebhookEventType, } from "./products/observability.js";
33
33
  export { Snapshots, type Snapshot, type SnapshotOptions } from "./snapshots.js";
34
34
  export { Transport, VERSION, apiOrigin, type RequestOptions, type Call } from "./transport.js";
35
35
  export * from "./errors.js";
@@ -78,10 +78,10 @@ export { openWalletAccount, claimWalletAccount, rekeyWalletAccount, type OpenedW
78
78
  export type { Topup } from "./products/billing.js";
79
79
  export type { NewKey, LimitedKey, LimitedKeyAction, MadeKey, ListedKey, KeyUsage, } from "./products/api-keys.js";
80
80
  export type { SsoConnection, SsoStatus } from "./products/sso.js";
81
- export type { Agent, AgentAsk, AgentAskState, AgentDefinition, AgentEvent, AgentHeldCall, AgentMemoryEntry, AgentMemoryFile, AgentMemoryHit, AgentMemoryPage, AgentMemoryUsage, AgentMemoryWritten, AgentSession, AgentSessionHandle, AgentSessionState, AgentTemplate, AgentTemplateKey, AgentTrigger, AgentTriggerCall, AgentTriggerCallOutcome, AgentTriggerKind, AgentTriggerRules, AgentUse, AnswerAgentAsk, CreateAgent, CreateAgentTrigger, ListAgentAsks, StartAgentSession, } from "./products/agents.js";
81
+ export type { Agent, AgentAdvisor, AgentAsk, AgentAskState, AgentDefinition, AgentEvent, AgentHeldCall, AgentMemoryEntry, AgentMemoryFile, AgentMemoryHit, AgentMemoryPage, AgentMemoryUsage, AgentMemoryWritten, AgentPermissionPolicy, AgentPermissions, AgentSession, AgentSessionHandle, AgentSessionOverrideLimits, AgentSessionOverrides, AgentSessionState, AgentTemplate, AgentTemplateKey, AgentAskToolCall, AgentTokens, AgentToolCall, AgentTrace, AgentTraceOtlp, AgentTracePage, AgentTrigger, AgentTriggerCall, AgentTriggerCallOutcome, AgentTriggerKind, AgentTriggerRules, AgentTurn, AgentUse, AgentWorkflow, AgentWorkflowHandle, AgentWorkflowPhase, AgentWorkflowState, AgentWorkflowStep, AnswerAgentAsk, CreateAgent, CreateAgentTrigger, ListAgentAsks, RunAgentWorkflow, SlackInstallLink, SlackTeam, StartAgentSession, } from "./products/agents.js";
82
82
  export { AGENT_TEMPLATES, AGENT_USES } from "./products/agents.js";
83
83
  export type { AgentsDeployChange, AgentsDeployOptions, AgentsDeployResult, AgentsFile, AgentsFileAgent, AgentsFileTrigger, AgentsSource, } from "./agents-deploy.js";
84
84
  export type { Container, ContainerState, CreateContainer, UpdateContainer, } from "./products/containers.js";
85
- export type { Browser, BrowserConnectOptions, BrowserInfo, BrowserScreenshot, BrowserScreenshotResult, CreateBrowser, UpdateBrowser, } from "./products/browsers.js";
85
+ export type { Browser, BrowserConnectOptions, BrowserInfo, BrowserScreenshot, BrowserScreenshotResult, BrowserRun, BrowserRunInput, BrowserRunState, BrowserRunStep, BrowserRunSteps, CreateBrowser, UpdateBrowser, } from "./products/browsers.js";
86
86
  export type { CreateDesktop, Desktop, DesktopAct, DesktopState, UpdateDesktop, } from "./products/desktops.js";
87
- export type { CiFlake, CiFlakeDetail, CiReleaseStep, CiRepository, CiTestResult, ConnectCiRepository, ListCiFlakes, ListCiReleaseSteps, ListCiRepositories, UpdateCiFlake, } from "./products/ci.js";
87
+ export type { CiAnnotation, CiFlake, CiFlakeDetail, CiReleaseStep, CiRepository, CiTestResult, ConnectCiRepository, ListCiFlakes, ListCiReleaseSteps, ListCiRepositories, UpdateCiFlake, } from "./products/ci.js";
@@ -0,0 +1,96 @@
1
+ export declare class NonRetriableError extends Error {
2
+ }
3
+ export declare class RetryAfterError extends Error {
4
+ }
5
+ export declare class CompatibilityError extends Error {
6
+ readonly code = "not_supported";
7
+ }
8
+ export type EventPayload = {
9
+ name: string;
10
+ data?: unknown;
11
+ id?: string;
12
+ ts?: number;
13
+ user?: unknown;
14
+ };
15
+ type Trigger = {
16
+ cron: string;
17
+ } | {
18
+ event: string;
19
+ if?: string;
20
+ };
21
+ type FunctionOptions = {
22
+ id: string;
23
+ name?: string;
24
+ retries?: number;
25
+ timeouts?: {
26
+ start?: string;
27
+ finish?: string;
28
+ };
29
+ [option: string]: unknown;
30
+ };
31
+ /** "30s", "5m", "2h", "1d", "1w", or milliseconds. */
32
+ export declare function durationMs(value: string | number): number;
33
+ /** Inngest's `TZ=Europe/Paris 0 12 * * 5`, as an expression and a zone. */
34
+ export declare function cronOf(text: string): {
35
+ cron: string;
36
+ timezone: string;
37
+ };
38
+ declare function stepTools(client: Inngest): {
39
+ run: <T>(_id: string, fn: () => Promise<T> | T) => Promise<T>;
40
+ sleep: (_id: string, duration: string | number) => Promise<void>;
41
+ sleepUntil: (_id: string, until: Date | string) => Promise<void>;
42
+ sendEvent: (_id: string, events: EventPayload | EventPayload[]) => Promise<{
43
+ ids: string[];
44
+ }>;
45
+ waitForEvent: () => never;
46
+ invoke: () => never;
47
+ ai: {
48
+ infer: () => never;
49
+ wrap: <T>(_id: string, fn: (...a: unknown[]) => T, ...args: unknown[]) => Promise<T>;
50
+ };
51
+ };
52
+ type Handler = (context: {
53
+ event: EventPayload;
54
+ events: EventPayload[];
55
+ step: ReturnType<typeof stepTools>;
56
+ logger: Pick<Console, "info" | "warn" | "error" | "debug">;
57
+ runId: string;
58
+ attempt: number;
59
+ }) => unknown;
60
+ export type InngestFunction = {
61
+ id: (prefix?: string) => string;
62
+ name: string;
63
+ triggers: Trigger[];
64
+ };
65
+ export declare class Inngest {
66
+ readonly id: string;
67
+ constructor(options: {
68
+ id: string;
69
+ [option: string]: unknown;
70
+ });
71
+ /** `createFunction(options, trigger, handler)`, or, as Inngest's newer
72
+ * SDKs write it, `createFunction({ ...options, triggers }, handler)`. */
73
+ createFunction(options: FunctionOptions & {
74
+ triggers: Trigger | Trigger[];
75
+ }, handler: Handler): InngestFunction;
76
+ createFunction(options: FunctionOptions, trigger: Trigger | Trigger[], handler: Handler): InngestFunction;
77
+ /** Runs every function of this app triggered by each event's name, once,
78
+ * now, in a fresh sandbox, with the event as its payload. The functions
79
+ * must be imported where this is called (as serve() imports them) and
80
+ * deployed with `runtime jobs deploy`. */
81
+ send(payload: EventPayload | EventPayload[]): Promise<{
82
+ ids: string[];
83
+ }>;
84
+ }
85
+ /** serve() of every adapter (inngest/next, /express, /hono, ...): nothing
86
+ * calls the app's endpoint once its functions run as jobs, so it answers 410
87
+ * with where they run now. */
88
+ export declare function serve(_options: {
89
+ client: Inngest;
90
+ functions: InngestFunction[];
91
+ }): (() => Response) & {
92
+ GET: () => Response;
93
+ POST: () => Response;
94
+ PUT: () => Response;
95
+ };
96
+ export {};
@@ -0,0 +1,183 @@
1
+ /* Inngest's SDK, run on Runtime Jobs: change `inngest` (and `inngest/next`,
2
+ `inngest/express` and the other serve adapters) to `withruntime/inngest`,
3
+ then `npx withruntime jobs deploy`. Each function with a cron trigger
4
+ becomes a Runtime job on that schedule; each function with an event
5
+ trigger becomes a job that `inngest.send` runs once, in a fresh sandbox,
6
+ per matching event. `step.run` runs its code in the run and returns its
7
+ result; `step.sleep` and `step.sleepUntil` wait in the run, which counts
8
+ toward its timeout. A function's `retries` become the job's attempts.
9
+
10
+ What has no equivalent is refused by name when called, never ignored:
11
+ step.waitForEvent, step.invoke, concurrency keys, throttling, debounce and
12
+ batching. Its serve() answers an Inngest server's calls with 410, since
13
+ nothing calls the app any more. */
14
+ import { numericCron } from "../trigger/index.js";
15
+ import { jobNameOf, registerTask, tasksRegistry } from "../jobs-code/registry.js";
16
+ export class NonRetriableError extends Error {
17
+ }
18
+ export class RetryAfterError extends Error {
19
+ }
20
+ export class CompatibilityError extends Error {
21
+ code = "not_supported";
22
+ }
23
+ const refuse = (what, instead) => {
24
+ throw new CompatibilityError(`${what} has no equivalent on Runtime Jobs: ${instead}`);
25
+ };
26
+ /** "30s", "5m", "2h", "1d", "1w", or milliseconds. */
27
+ export function durationMs(value) {
28
+ if (typeof value === "number")
29
+ return value;
30
+ let total = 0;
31
+ const re = /(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)/g;
32
+ let matched = "";
33
+ for (const m of value.matchAll(re)) {
34
+ matched += m[0];
35
+ total +=
36
+ Number(m[1]) *
37
+ { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }[m[2]];
38
+ }
39
+ if (!matched || matched.replace(/\s/g, "") !== value.replace(/\s/g, ""))
40
+ throw new Error(`"${value}" is not a duration such as 30s, 5m, 2h or 1d`);
41
+ return total;
42
+ }
43
+ /** Inngest's `TZ=Europe/Paris 0 12 * * 5`, as an expression and a zone. */
44
+ export function cronOf(text) {
45
+ const found = /^\s*(?:(?:TZ|CRON_TZ)=(\S+)\s+)?(.+)$/.exec(text);
46
+ return { cron: numericCron(found[2]), timezone: found[1] ?? "UTC" };
47
+ }
48
+ const sleep = (ms) => new Promise((done) => setTimeout(done, Math.max(0, ms)));
49
+ function stepTools(client) {
50
+ return {
51
+ run: async (_id, fn) => fn(),
52
+ sleep: (_id, duration) => sleep(durationMs(duration)),
53
+ sleepUntil: (_id, until) => sleep(new Date(until).getTime() - Date.now()),
54
+ sendEvent: (_id, events) => client.send(events),
55
+ waitForEvent: () => refuse("step.waitForEvent", "a run cannot pause for an event; send the event to start a function instead"),
56
+ invoke: () => refuse("step.invoke", "call the function's code directly, or send an event it is triggered by"),
57
+ ai: {
58
+ infer: () => refuse("step.ai.infer", "call the model's API in step.run"),
59
+ wrap: async (_id, fn, ...args) => fn(...args),
60
+ },
61
+ };
62
+ }
63
+ export class Inngest {
64
+ id;
65
+ constructor(options) {
66
+ if (!options?.id)
67
+ throw new Error("new Inngest({ id }) needs the app's id.");
68
+ this.id = options.id;
69
+ }
70
+ createFunction(options, triggerOrHandler, maybeHandler) {
71
+ const handler = (typeof triggerOrHandler === "function" ? triggerOrHandler : maybeHandler);
72
+ const trigger = typeof triggerOrHandler === "function" ? (options.triggers ?? []) : triggerOrHandler;
73
+ for (const key of [
74
+ "concurrency",
75
+ "throttle",
76
+ "debounce",
77
+ "batchEvents",
78
+ "rateLimit",
79
+ "priority",
80
+ "cancelOn",
81
+ ])
82
+ if (options[key] !== undefined)
83
+ refuse(`${options.id}'s ${key}`, "a function's runs here each get their own sandbox; remove it to deploy");
84
+ const triggers = Array.isArray(trigger) ? trigger : [trigger];
85
+ if (!triggers.length)
86
+ refuse(`${options.id} with no trigger`, "give it a cron or an event");
87
+ const crons = triggers.flatMap((t) => ("cron" in t ? [cronOf(t.cron)] : []));
88
+ const events = triggers.flatMap((t) => ("event" in t ? [t.event] : []));
89
+ if (crons.length > 1)
90
+ refuse(`${options.id}'s ${crons.length} cron triggers`, "a job has one schedule; split it into one function per cron");
91
+ const finish = options.timeouts?.finish
92
+ ? Math.ceil(durationMs(options.timeouts.finish) / 1000)
93
+ : undefined;
94
+ registerTask({
95
+ kind: "inngest",
96
+ id: options.id,
97
+ schedule: crons[0] ?? null,
98
+ ...(events.length ? { events } : {}),
99
+ ...(finish ? { maxDuration: finish } : {}),
100
+ // Inngest retries 4 times unless told otherwise; a job makes at most 5 attempts.
101
+ retry: { maxAttempts: Math.min(5, (options.retries ?? 4) + 1) },
102
+ invoke: async ({ payload, attempt, runId }) => {
103
+ const event = payload ?? {
104
+ name: "inngest/scheduled.timer",
105
+ data: { cron: crons[0]?.cron },
106
+ ts: Date.now(),
107
+ };
108
+ try {
109
+ return await handler({
110
+ event,
111
+ events: [event],
112
+ step: stepTools(this),
113
+ logger: console,
114
+ runId,
115
+ attempt: attempt - 1,
116
+ });
117
+ }
118
+ catch (error) {
119
+ // A NonRetriableError ends the run as succeeded-with-error, as
120
+ // Inngest marks it failed but tries no more: exit 0 stops retries.
121
+ if (error instanceof NonRetriableError) {
122
+ console.error(`NonRetriableError: ${error.message}`);
123
+ return undefined;
124
+ }
125
+ throw error;
126
+ }
127
+ },
128
+ });
129
+ return {
130
+ id: (prefix) => (prefix ? `${prefix}-${options.id}` : options.id),
131
+ name: options.name ?? options.id,
132
+ triggers,
133
+ };
134
+ }
135
+ /** Runs every function of this app triggered by each event's name, once,
136
+ * now, in a fresh sandbox, with the event as its payload. The functions
137
+ * must be imported where this is called (as serve() imports them) and
138
+ * deployed with `runtime jobs deploy`. */
139
+ async send(payload) {
140
+ const events = Array.isArray(payload) ? payload : [payload];
141
+ const listening = [...tasksRegistry().values()].filter((t) => t.kind === "inngest");
142
+ const { Runtime } = await import("../client.js");
143
+ const runtime = new Runtime();
144
+ const jobs = new Map();
145
+ for await (const job of await runtime.jobs.list({ limit: 100 }))
146
+ if (job.state === "active" || job.state === "paused")
147
+ jobs.set(job.name, job);
148
+ const ids = [];
149
+ for (const event of events) {
150
+ const full = { id: crypto.randomUUID(), ts: Date.now(), data: {}, ...event };
151
+ for (const fn of listening.filter((t) => t.events?.includes(event.name))) {
152
+ const name = jobNameOf(this.id, fn.id);
153
+ const template = jobs.get(name);
154
+ if (!template)
155
+ throw new Error(`No job ${name} for function "${fn.id}": deploy it with \`npx withruntime jobs deploy\`.`);
156
+ const body = Buffer.from(JSON.stringify(full)).toString("base64");
157
+ if (body.length > 65_536)
158
+ throw new Error(`Event ${event.name} is over 64 KiB as JSON.`);
159
+ const d = template.definition;
160
+ const run = await runtime.jobs.create({
161
+ name: `${name.slice(0, 60)}-${Date.now().toString(36)}`,
162
+ schedule: { at: Date.now() },
163
+ command: [...d.command.argv.slice(0, 6), body],
164
+ ...(d.image ? { image: d.image } : {}),
165
+ compute: d.compute,
166
+ timeoutSeconds: d.timeoutSeconds,
167
+ retry: d.retry,
168
+ ...(d.secrets?.length ? { secrets: d.secrets } : {}),
169
+ });
170
+ ids.push(run.id);
171
+ }
172
+ }
173
+ return { ids };
174
+ }
175
+ }
176
+ /** serve() of every adapter (inngest/next, /express, /hono, ...): nothing
177
+ * calls the app's endpoint once its functions run as jobs, so it answers 410
178
+ * with where they run now. */
179
+ export function serve(_options) {
180
+ const gone = () => new Response(JSON.stringify({ message: "These functions run on Runtime Jobs now: `runtime jobs ls`." }), { status: 410, headers: { "content-type": "application/json" } });
181
+ const handler = Object.assign(gone, { GET: gone, POST: gone, PUT: gone });
182
+ return handler;
183
+ }
@@ -0,0 +1,12 @@
1
+ type Fields = {
2
+ minutes: Set<number>;
3
+ hours: Set<number>;
4
+ days: Set<number> | null;
5
+ months: Set<number>;
6
+ weekdays: Set<number> | null;
7
+ };
8
+ export declare function parseCron(expression: string): Fields;
9
+ /** Up to `count` times from `from` (inclusive), forward or back, within 400
10
+ * days; an hour whose wall clock cannot match is skipped whole. */
11
+ export declare function cronTimes(expression: string, timeZone: string, from: number, direction: 1 | -1, count: number): Date[];
12
+ export {};
@@ -0,0 +1,93 @@
1
+ /* A cron's times in a zone, as Runtime's scheduler finds them (five numeric
2
+ fields, packages/db/src/schedule.ts): the run's own time, the one before it
3
+ and the next ones, for the payload a Trigger.dev scheduled task receives. A
4
+ run starts within seconds of its time, so its time is the latest match at
5
+ or before now. */
6
+ function setOf(field, low, high) {
7
+ const out = new Set();
8
+ for (const part of field.split(",")) {
9
+ const [range, stepText] = part.split("/");
10
+ const step = stepText === undefined ? 1 : Number(stepText);
11
+ let from;
12
+ let to;
13
+ if (range === "*")
14
+ [from, to] = [low, high];
15
+ else if (range.includes("-"))
16
+ [from, to] = range.split("-").map(Number);
17
+ else
18
+ [from, to] = [Number(range), stepText === undefined ? Number(range) : high];
19
+ if (![from, to, step].every(Number.isInteger) ||
20
+ step < 1 ||
21
+ from < low ||
22
+ to > high ||
23
+ from > to)
24
+ throw new Error(`"${field}" is not a cron field from ${low} to ${high}`);
25
+ for (let n = from; n <= to; n += step)
26
+ out.add(n);
27
+ }
28
+ return out;
29
+ }
30
+ export function parseCron(expression) {
31
+ const f = expression.trim().split(/\s+/);
32
+ if (f.length !== 5)
33
+ throw new Error(`"${expression}" is not five cron fields`);
34
+ const weekdays = f[4] === "*" ? null : setOf(f[4], 0, 7);
35
+ if (weekdays?.has(7))
36
+ weekdays.add(0);
37
+ return {
38
+ minutes: setOf(f[0], 0, 59),
39
+ hours: setOf(f[1], 0, 23),
40
+ days: f[2] === "*" ? null : setOf(f[2], 1, 31),
41
+ months: setOf(f[3], 1, 12),
42
+ weekdays,
43
+ };
44
+ }
45
+ /** The wall clock of an instant in a zone. */
46
+ function wall(at, timeZone) {
47
+ const parts = new Intl.DateTimeFormat("en-US", {
48
+ timeZone,
49
+ hourCycle: "h23",
50
+ month: "numeric",
51
+ day: "numeric",
52
+ hour: "numeric",
53
+ minute: "numeric",
54
+ weekday: "short",
55
+ }).formatToParts(new Date(at));
56
+ const n = (type) => Number(parts.find((p) => p.type === type)?.value);
57
+ const weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(parts.find((p) => p.type === "weekday")?.value ?? "");
58
+ return { month: n("month"), day: n("day"), hour: n("hour"), minute: n("minute"), weekday };
59
+ }
60
+ function matches(f, w) {
61
+ if (!f.months.has(w.month) || !f.hours.has(w.hour) || !f.minutes.has(w.minute))
62
+ return false;
63
+ // As in cron: with both day fields set, either matches.
64
+ if (f.days && f.weekdays)
65
+ return f.days.has(w.day) || f.weekdays.has(w.weekday);
66
+ if (f.days)
67
+ return f.days.has(w.day);
68
+ if (f.weekdays)
69
+ return f.weekdays.has(w.weekday);
70
+ return true;
71
+ }
72
+ const MINUTE = 60_000;
73
+ const HOUR = 3_600_000;
74
+ /** Up to `count` times from `from` (inclusive), forward or back, within 400
75
+ * days; an hour whose wall clock cannot match is skipped whole. */
76
+ export function cronTimes(expression, timeZone, from, direction, count) {
77
+ const f = parseCron(expression);
78
+ const out = [];
79
+ let at = Math.floor(from / MINUTE) * MINUTE;
80
+ const end = from + direction * 400 * 24 * HOUR;
81
+ while (out.length < count && (direction === 1 ? at <= end : at >= end)) {
82
+ const w = wall(at, timeZone);
83
+ if (!f.hours.has(w.hour) || !f.months.has(w.month)) {
84
+ // To the next (or previous) hour boundary of this zone's clock.
85
+ at = direction === 1 ? at + (60 - w.minute) * MINUTE : at - (w.minute + 1) * MINUTE;
86
+ continue;
87
+ }
88
+ if (matches(f, w))
89
+ out.push(new Date(at));
90
+ at += direction * MINUTE;
91
+ }
92
+ return out;
93
+ }
@@ -0,0 +1,31 @@
1
+ export type CodeTask = {
2
+ /** "trigger" or "inngest": which drop-in declared it. */
3
+ kind: "trigger" | "inngest";
4
+ id: string;
5
+ /** Five cron fields and a zone; null for a task run on demand. */
6
+ schedule: {
7
+ cron: string;
8
+ timezone: string;
9
+ } | null;
10
+ /** Inngest: the event names that run it. */
11
+ events?: string[];
12
+ compute?: {
13
+ vcpu: number;
14
+ memoryMiB: number;
15
+ };
16
+ /** Seconds. */
17
+ maxDuration?: number;
18
+ retry?: {
19
+ maxAttempts: number;
20
+ };
21
+ /** Calls the task with what the runner hands it. */
22
+ invoke(input: {
23
+ payload: unknown;
24
+ attempt: number;
25
+ runId: string;
26
+ }): Promise<unknown>;
27
+ };
28
+ export declare function tasksRegistry(): Map<string, CodeTask>;
29
+ export declare function registerTask(task: CodeTask): void;
30
+ /** The name of the Runtime job that runs a task. */
31
+ export declare function jobNameOf(project: string, id: string): string;
@@ -0,0 +1,30 @@
1
+ /* The tasks a project's code declares through a drop-in (withruntime/trigger,
2
+ withruntime/inngest), kept on globalThis under one symbol so the runner
3
+ (runner.ts, copied into the job's image) finds them whatever copy of the
4
+ SDK the project installed. `runtime jobs deploy` asks the runner to list
5
+ them, then makes one Runtime job per task; each run imports the task's file
6
+ and calls it. */
7
+ const KEY = Symbol.for("withruntime.jobs.tasks");
8
+ export function tasksRegistry() {
9
+ const g = globalThis;
10
+ let found = g[KEY];
11
+ if (!found) {
12
+ found = new Map();
13
+ g[KEY] = found;
14
+ }
15
+ return found;
16
+ }
17
+ export function registerTask(task) {
18
+ const registry = tasksRegistry();
19
+ const key = `${task.kind}:${task.id}`;
20
+ if (registry.has(key))
21
+ throw new Error(`Two ${task.kind} tasks have the id "${task.id}"; each id is one Runtime job.`);
22
+ registry.set(key, task);
23
+ }
24
+ /** The name of the Runtime job that runs a task. */
25
+ export function jobNameOf(project, id) {
26
+ return `${project}-${id}`
27
+ .replace(/[^A-Za-z0-9_.-]/g, "-")
28
+ .replace(/^[^A-Za-z0-9]+/, "")
29
+ .slice(0, 80);
30
+ }
@@ -0,0 +1 @@
1
+ export declare function main(argv: string[]): Promise<number>;