@relayflows/sdk 2.0.15 → 2.0.17

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 (155) hide show
  1. package/dist/agent-artifacts.d.ts +20 -0
  2. package/dist/agent-artifacts.d.ts.map +1 -0
  3. package/dist/agent-artifacts.js +81 -0
  4. package/dist/agent-artifacts.js.map +1 -0
  5. package/dist/authored-flow-error.d.ts +1 -1
  6. package/dist/authored-flow-error.d.ts.map +1 -1
  7. package/dist/authored-flow-error.js.map +1 -1
  8. package/dist/authored-flow-executor.d.ts +3 -3
  9. package/dist/authored-flow-executor.d.ts.map +1 -1
  10. package/dist/authored-flow-executor.js +93 -7
  11. package/dist/authored-flow-executor.js.map +1 -1
  12. package/dist/authored-flow-lifecycle.d.ts +10 -0
  13. package/dist/authored-flow-lifecycle.d.ts.map +1 -1
  14. package/dist/authored-flow-lifecycle.js +7 -0
  15. package/dist/authored-flow-lifecycle.js.map +1 -1
  16. package/dist/authored-flow-operation.d.ts +11 -0
  17. package/dist/authored-flow-operation.d.ts.map +1 -1
  18. package/dist/authored-flow-operation.js +32 -7
  19. package/dist/authored-flow-operation.js.map +1 -1
  20. package/dist/authored-node-runner.d.ts.map +1 -1
  21. package/dist/authored-node-runner.js +37 -14
  22. package/dist/authored-node-runner.js.map +1 -1
  23. package/dist/authored-step-output.d.ts +2 -0
  24. package/dist/authored-step-output.d.ts.map +1 -1
  25. package/dist/authored-step-output.js +5 -1
  26. package/dist/authored-step-output.js.map +1 -1
  27. package/dist/authored-worker-step.d.ts.map +1 -1
  28. package/dist/authored-worker-step.js +15 -8
  29. package/dist/authored-worker-step.js.map +1 -1
  30. package/dist/cli/check-triggers.d.ts.map +1 -1
  31. package/dist/cli/check-triggers.js +10 -0
  32. package/dist/cli/check-triggers.js.map +1 -1
  33. package/dist/cli/check.d.ts +14 -0
  34. package/dist/cli/check.d.ts.map +1 -1
  35. package/dist/cli/check.js +6 -1
  36. package/dist/cli/check.js.map +1 -1
  37. package/dist/cli/cloud-deploy.d.ts +30 -0
  38. package/dist/cli/cloud-deploy.d.ts.map +1 -0
  39. package/dist/cli/cloud-deploy.js +162 -0
  40. package/dist/cli/cloud-deploy.js.map +1 -0
  41. package/dist/cli/cloud-run.d.ts +3 -1
  42. package/dist/cli/cloud-run.d.ts.map +1 -1
  43. package/dist/cli/cloud-run.js +37 -5
  44. package/dist/cli/cloud-run.js.map +1 -1
  45. package/dist/cli/cloud-schedule.d.ts +29 -0
  46. package/dist/cli/cloud-schedule.d.ts.map +1 -0
  47. package/dist/cli/cloud-schedule.js +131 -0
  48. package/dist/cli/cloud-schedule.js.map +1 -0
  49. package/dist/cli/cloud-sync.d.ts +13 -0
  50. package/dist/cli/cloud-sync.d.ts.map +1 -0
  51. package/dist/cli/cloud-sync.js +39 -0
  52. package/dist/cli/cloud-sync.js.map +1 -0
  53. package/dist/cli/direct-run.js +1 -1
  54. package/dist/cli/direct-run.js.map +1 -1
  55. package/dist/cli/run.d.ts +1 -1
  56. package/dist/cli/run.d.ts.map +1 -1
  57. package/dist/cli/run.js +17 -4
  58. package/dist/cli/run.js.map +1 -1
  59. package/dist/cli.d.ts.map +1 -1
  60. package/dist/cli.js +117 -12
  61. package/dist/cli.js.map +1 -1
  62. package/dist/cloud-deploy.d.ts +70 -0
  63. package/dist/cloud-deploy.d.ts.map +1 -0
  64. package/dist/cloud-deploy.js +192 -0
  65. package/dist/cloud-deploy.js.map +1 -0
  66. package/dist/cloud-http.d.ts +52 -2
  67. package/dist/cloud-http.d.ts.map +1 -1
  68. package/dist/cloud-http.js +135 -9
  69. package/dist/cloud-http.js.map +1 -1
  70. package/dist/cloud-run.d.ts +53 -0
  71. package/dist/cloud-run.d.ts.map +1 -1
  72. package/dist/cloud-run.js +97 -25
  73. package/dist/cloud-run.js.map +1 -1
  74. package/dist/cloud-schedule.d.ts +48 -0
  75. package/dist/cloud-schedule.d.ts.map +1 -0
  76. package/dist/cloud-schedule.js +125 -0
  77. package/dist/cloud-schedule.js.map +1 -0
  78. package/dist/cloud-sync.d.ts +66 -0
  79. package/dist/cloud-sync.d.ts.map +1 -0
  80. package/dist/cloud-sync.js +287 -0
  81. package/dist/cloud-sync.js.map +1 -0
  82. package/dist/failure-kinds.d.ts +10 -3
  83. package/dist/failure-kinds.d.ts.map +1 -1
  84. package/dist/failure-kinds.js +10 -0
  85. package/dist/failure-kinds.js.map +1 -1
  86. package/dist/index.d.ts +5 -0
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +5 -0
  89. package/dist/index.js.map +1 -1
  90. package/dist/named-gate-lowering.js +9 -0
  91. package/dist/named-gate-lowering.js.map +1 -1
  92. package/dist/named-gates.d.ts +1 -1
  93. package/dist/named-gates.d.ts.map +1 -1
  94. package/dist/named-gates.js +11 -1
  95. package/dist/named-gates.js.map +1 -1
  96. package/dist/preflight.d.ts.map +1 -1
  97. package/dist/preflight.js +155 -9
  98. package/dist/preflight.js.map +1 -1
  99. package/dist/schedule-trigger.d.ts +35 -0
  100. package/dist/schedule-trigger.d.ts.map +1 -0
  101. package/dist/schedule-trigger.js +53 -0
  102. package/dist/schedule-trigger.js.map +1 -0
  103. package/dist/spec.d.ts +11 -1
  104. package/dist/spec.d.ts.map +1 -1
  105. package/dist/spec.js.map +1 -1
  106. package/dist/trigger-executor.js +1 -1
  107. package/dist/trigger-executor.js.map +1 -1
  108. package/dist/validate.js +1 -1
  109. package/dist/validate.js.map +1 -1
  110. package/dist/worker-cli.d.ts +10 -0
  111. package/dist/worker-cli.d.ts.map +1 -1
  112. package/dist/worker-cli.js +51 -22
  113. package/dist/worker-cli.js.map +1 -1
  114. package/dist/worker.d.ts.map +1 -1
  115. package/dist/worker.js +9 -0
  116. package/dist/worker.js.map +1 -1
  117. package/dist/wrapper-session.d.ts +3 -1
  118. package/dist/wrapper-session.d.ts.map +1 -1
  119. package/dist/wrapper-session.js +6 -3
  120. package/dist/wrapper-session.js.map +1 -1
  121. package/package.json +3 -3
  122. package/src/agent-artifacts.ts +76 -0
  123. package/src/authored-flow-error.ts +1 -0
  124. package/src/authored-flow-executor.ts +95 -8
  125. package/src/authored-flow-lifecycle.ts +7 -0
  126. package/src/authored-flow-operation.ts +35 -10
  127. package/src/authored-node-runner.ts +35 -13
  128. package/src/authored-step-output.ts +6 -1
  129. package/src/authored-worker-step.ts +16 -9
  130. package/src/cli/check-triggers.ts +9 -0
  131. package/src/cli/check.ts +21 -1
  132. package/src/cli/cloud-deploy.ts +157 -0
  133. package/src/cli/cloud-run.ts +37 -6
  134. package/src/cli/cloud-schedule.ts +135 -0
  135. package/src/cli/cloud-sync.ts +37 -0
  136. package/src/cli/direct-run.ts +1 -1
  137. package/src/cli/run.ts +18 -5
  138. package/src/cli.ts +107 -12
  139. package/src/cloud-deploy.ts +247 -0
  140. package/src/cloud-http.ts +173 -9
  141. package/src/cloud-run.ts +143 -24
  142. package/src/cloud-schedule.ts +158 -0
  143. package/src/cloud-sync.ts +315 -0
  144. package/src/failure-kinds.ts +10 -0
  145. package/src/index.ts +14 -0
  146. package/src/named-gate-lowering.ts +9 -0
  147. package/src/named-gates.ts +11 -1
  148. package/src/preflight.ts +132 -9
  149. package/src/schedule-trigger.ts +73 -0
  150. package/src/spec.ts +12 -1
  151. package/src/trigger-executor.ts +1 -1
  152. package/src/validate.ts +1 -1
  153. package/src/worker-cli.ts +41 -0
  154. package/src/worker.ts +9 -0
  155. package/src/wrapper-session.ts +5 -1
package/src/cloud-run.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { RUN_COMPLETION_REASONS } from '@relayflows/surface';
1
+ import { RUN_COMPLETION_REASONS, type ScheduleTriggerSource } from '@relayflows/surface';
2
2
  import type { RunCompletionReason } from './protocol.js';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { createHash } from 'node:crypto';
@@ -10,9 +10,10 @@ import type { FlowSpec } from './spec.js';
10
10
  import { snapshotJsonValue, type JsonValue } from './json-value.js';
11
11
  import { loadAuthoredFlow, type SurfaceModuleAuthority } from './authored-flow-loader.js';
12
12
  import {
13
- CloudFlowError, cloudConnection, cloudRequest, cloudRunId, isCloudRecord,
13
+ CloudFlowError, cloudConnection, cloudFetch, cloudRequest, cloudRunId, isCloudRecord,
14
14
  type CloudConnectionOptions,
15
15
  } from './cloud-http.js';
16
+ import { packWorkingTree, prepareCloudSync, uploadCloudCode } from './cloud-sync.js';
16
17
 
17
18
  export type CloudFlowSource = FlowSpec | { path: string };
18
19
  export interface RunInCloudOptions extends CloudConnectionOptions {
@@ -20,6 +21,21 @@ export interface RunInCloudOptions extends CloudConnectionOptions {
20
21
  workspaceId?: string;
21
22
  /** Exact JSON input. Required at runtime for authored .flow.ts; refused for declarative source. */
22
23
  input?: JsonValue;
24
+ /**
25
+ * Upload this working tree before submission so the hosted run executes
26
+ * inside it (v1's `--sync-code`). Cloud-API storage only; see cloud-sync.ts.
27
+ * The submitted flow still travels as source in the request body, so it
28
+ * must remain self-contained: sibling imports inside the tree are not
29
+ * resolved by the hosted runner.
30
+ */
31
+ syncCode?: { root: string };
32
+ /**
33
+ * Called immediately before the one non-idempotent request, the run
34
+ * submission. Everything before it (prepare, pack, upload) is safe to
35
+ * retry, so a caller classifying an interruption can tell "nothing was
36
+ * admitted" from "admission unknown".
37
+ */
38
+ onSubmit?: () => void;
23
39
  }
24
40
  export interface CloudRunReceipt {
25
41
  runId: string;
@@ -28,6 +44,8 @@ export interface CloudRunReceipt {
28
44
  specHash: string;
29
45
  /** Authenticated run API resource; this is not a public sharing URL. */
30
46
  apiUrl: string;
47
+ /** Present when a working tree was synced: what was uploaded, by count and size. */
48
+ synced?: { files: number; bytes: number; skippedLinks: string[] };
31
49
  }
32
50
  export interface CloudAuthoredAuthority {
33
51
  readonly schemaVersion: 1;
@@ -35,6 +53,17 @@ export interface CloudAuthoredAuthority {
35
53
  readonly byteLength: number;
36
54
  readonly surface: SurfaceModuleAuthority;
37
55
  }
56
+ /** The request-body fields a submission contributes; identical for a run and a schedule. */
57
+ export function cloudSubmissionBody(submission: CloudSubmission): Record<string, unknown> {
58
+ return {
59
+ workflow: submission.workflow,
60
+ fileType: submission.fileType,
61
+ relayflowVersion: 'v2',
62
+ ...(submission.authoredAuthority === undefined ? {} : { authoredAuthority: submission.authoredAuthority }),
63
+ ...(submission.inputPresent ? { inputs: submission.inputs } : {}),
64
+ };
65
+ }
66
+
38
67
  export type CloudRunState =
39
68
  | { runId: string; status: 'pending' | 'launching' | 'running' }
40
69
  | { runId: string; status: 'completed' | 'failed' | 'cancelled'; completionReason: RunCompletionReason };
@@ -44,13 +73,31 @@ export type CloudRunState =
44
73
  * happens here; Cloud owns provisioning and the Rust engine owns execution.
45
74
  * Returns acceptance, not completion. No local daemon, CLI probe, or node up.
46
75
  */
47
- export async function runInCloud(
76
+ /**
77
+ * What a Cloud submission carries, before any request: the exact source or
78
+ * canonical spec, the pinned authority for authored source, the input, and a
79
+ * local correlation hash. Shared by `runInCloud` and `scheduleInCloud`, so a
80
+ * schedule stores exactly what a run would send.
81
+ */
82
+ export interface CloudSubmission {
83
+ readonly workflow: string;
84
+ readonly fileType: 'yaml' | 'ts';
85
+ readonly authoredAuthority?: CloudAuthoredAuthority;
86
+ readonly inputs?: JsonValue;
87
+ readonly inputPresent: boolean;
88
+ readonly specHash: string;
89
+ /** The authored flow's declared name, or the spec name. */
90
+ readonly name: string;
91
+ /** Authored `schedule.*` handlers, for `flows schedule` to pick up. */
92
+ readonly schedules: readonly ScheduleTriggerSource[];
93
+ }
94
+
95
+ export async function prepareCloudSubmission(
48
96
  flow: CloudFlowSource,
49
- options: RunInCloudOptions = {},
50
- ): Promise<CloudRunReceipt> {
51
- const { baseUrl } = cloudConnection(options);
97
+ options: { input?: JsonValue; signal?: AbortSignal } = {},
98
+ ): Promise<CloudSubmission> {
52
99
  let spec: FlowSpec | undefined;
53
- let authored: { source: string; authority: CloudAuthoredAuthority } | undefined;
100
+ let authored: { source: string; authority: CloudAuthoredAuthority; name: string; schedules: ScheduleTriggerSource[] } | undefined;
54
101
  const inputPresent = Object.prototype.hasOwnProperty.call(options, 'input');
55
102
  let authoredInput: JsonValue | undefined;
56
103
  try {
@@ -62,14 +109,27 @@ export async function runInCloud(
62
109
  if (!bytes.length || Buffer.from(source, 'utf8').compare(bytes) !== 0) {
63
110
  throw new CloudFlowError('invalid_input', 'Authored source must be nonempty, lossless UTF-8.');
64
111
  }
65
- const loaded = await loadAuthoredFlow(flow.path);
66
- loaded.getDefinition(loaded.handle);
112
+ let loaded: Awaited<ReturnType<typeof loadAuthoredFlow>>;
113
+ let definition: ReturnType<typeof loaded.getDefinition>;
114
+ try {
115
+ loaded = await loadAuthoredFlow(flow.path);
116
+ definition = loaded.getDefinition(loaded.handle);
117
+ } catch (error) {
118
+ // An authored source that does not load is an authoring problem, and
119
+ // the most common one is `@relayflows/surface` not being resolvable
120
+ // from the flow's directory. Name it; do not call it a spec problem.
121
+ throw new CloudFlowError('unsupported_source',
122
+ `${flow.path} is not a loadable authored flow: ${error instanceof Error ? error.message : String(error)}. `
123
+ + 'Run `flows check` on it from the same directory.');
124
+ }
67
125
  if (loaded.graph.length !== 1) {
68
126
  throw new CloudFlowError('unsupported_source',
69
127
  'Cloud authored submission currently accepts one self-contained .flow.ts source without use dependencies.');
70
128
  }
71
129
  authored = {
72
130
  source,
131
+ name: definition.name,
132
+ schedules: definition.handlers.flatMap(h => h.trigger.kind === 'schedule' ? [h.trigger] : []),
73
133
  authority: Object.freeze({
74
134
  schemaVersion: 1,
75
135
  sourceSha256: createHash('sha256').update(bytes).digest('hex'),
@@ -112,27 +172,86 @@ export async function runInCloud(
112
172
  throw new CloudFlowError('invalid_input', 'Cannot read or compile the declarative flow. Check the file path and YAML/JSON spec.');
113
173
  }
114
174
  options.signal?.throwIfAborted();
115
- const hash = authored === undefined
116
- ? specHash(toKernelSpec(spec!))
117
- : createHash('sha256').update(canonicalize({
118
- authority: authored.authority,
119
- input: authoredInput,
120
- })).digest('hex');
121
- const result = await cloudRequest('/api/v1/workflows/run', options, {
175
+ if (authored === undefined) {
176
+ const kernel = toKernelSpec(spec!);
122
177
  // JSON is a YAML subset. Sending canonical data preserves the exact spec
123
178
  // while using the server's existing YAML-to-config admission path.
124
- workflow: authored?.source ?? canonicalize(spec),
125
- fileType: authored === undefined ? 'yaml' : 'ts',
126
- relayflowVersion: 'v2',
127
- ...(authored === undefined ? {} : { authoredAuthority: authored.authority }),
128
- ...(authored === undefined ? {} : { inputs: authoredInput }),
129
- ...(options.workspaceId === undefined ? {} : { workspaceId: options.workspaceId }),
130
- });
179
+ return { workflow: canonicalize(spec), fileType: 'yaml', inputPresent: false, specHash: specHash(kernel),
180
+ name: spec!.name ?? "flow", schedules: [] };
181
+ }
182
+ return {
183
+ workflow: authored.source, fileType: 'ts', authoredAuthority: authored.authority,
184
+ inputs: authoredInput, inputPresent: true, name: authored.name, schedules: authored.schedules,
185
+ specHash: createHash('sha256').update(canonicalize({ authority: authored.authority, input: authoredInput })).digest('hex'),
186
+ };
187
+ }
188
+
189
+ /**
190
+ * Submit a declarative flow to Cloud's pinned v2 runtime. Compilation only
191
+ * happens here; Cloud owns provisioning and the Rust engine owns execution.
192
+ * Returns acceptance, not completion. No local daemon, CLI probe, or node up.
193
+ */
194
+ export async function runInCloud(
195
+ flow: CloudFlowSource,
196
+ options: RunInCloudOptions = {},
197
+ ): Promise<CloudRunReceipt> {
198
+ const { baseUrl } = cloudConnection(options);
199
+ const submission = await prepareCloudSubmission(flow, options);
200
+ const hash = submission.specHash;
201
+ // Sync before submission: `prepare` reserves the run ID and the upload lands
202
+ // under it, so the run request below names code Cloud already holds. A
203
+ // refused backend or failed upload therefore never leaves a launched run
204
+ // pointing at a tree that is not there.
205
+ let synced: { runId: string; codeKey: string; files: number; bytes: number; skippedLinks: string[] } | undefined;
206
+ if (options.syncCode !== undefined) {
207
+ const prepared = await prepareCloudSync(options);
208
+ options.signal?.throwIfAborted();
209
+ const packed = await packWorkingTree(options.syncCode.root);
210
+ try {
211
+ options.signal?.throwIfAborted();
212
+ await uploadCloudCode(prepared, packed, options);
213
+ } finally {
214
+ packed.dispose();
215
+ }
216
+ synced = { runId: prepared.runId, codeKey: prepared.codeKey, files: packed.files.length, bytes: packed.bytes,
217
+ skippedLinks: packed.skippedLinks };
218
+ }
219
+ options.signal?.throwIfAborted();
220
+ options.onSubmit?.();
221
+ let result: unknown;
222
+ try {
223
+ result = await cloudFetch('/api/v1/workflows/run', options, { method: 'POST', detail: true, body: JSON.stringify({
224
+ ...cloudSubmissionBody(submission),
225
+ ...(options.workspaceId === undefined ? {} : { workspaceId: options.workspaceId }),
226
+ ...(synced === undefined ? {} : { runId: synced.runId, s3CodeKey: synced.codeKey }),
227
+ }) });
228
+ } catch (error) {
229
+ // Cloud accepts exactly one authored Surface (the one its sandbox runs).
230
+ // A CLI on another release is refused with this code; say which side is
231
+ // which instead of leaving the user with a bare 400 (flows#461).
232
+ if (error instanceof CloudFlowError && submission.authoredAuthority !== undefined
233
+ && error.refusal?.code === 'relayflow_v2_authored_authority_invalid') {
234
+ const expected = error.refusal.expected?.version;
235
+ throw new CloudFlowError('unsupported_source',
236
+ `Cloud refused this authored flow's Surface: it runs @relayflows/surface ${expected ?? '(version not reported)'} `
237
+ + `and this CLI authored against ${submission.authoredAuthority.surface.version}. `
238
+ + 'Install the matching relayflows release, or deploy the flow with `flows deploy`, which uses Cloud\'s own Surface.',
239
+ error.status, error.refusal);
240
+ }
241
+ throw error;
242
+ }
131
243
  if (!isCloudRecord(result) || (result.status !== 'pending' && result.status !== 'running')) {
132
244
  throw new CloudFlowError('invalid_response', 'Cloud did not return an accepted run.');
133
245
  }
134
246
  const runId = cloudRunId(result.runId);
135
- return { runId, status: result.status, specHash: hash, apiUrl: `${baseUrl}/api/v1/workflows/runs/${runId}` };
247
+ if (synced !== undefined && runId !== synced.runId) {
248
+ throw new CloudFlowError('invalid_response',
249
+ `Cloud accepted run ${runId} but the synced code was uploaded for ${synced.runId}.`);
250
+ }
251
+ return {
252
+ runId, status: result.status, specHash: hash, apiUrl: `${baseUrl}/api/v1/workflows/runs/${runId}`,
253
+ ...(synced === undefined ? {} : { synced: { files: synced.files, bytes: synced.bytes, skippedLinks: synced.skippedLinks } }),
254
+ };
136
255
  }
137
256
 
138
257
  export async function getCloudFlowRun(
@@ -0,0 +1,158 @@
1
+ import { cronGrid, everyToMs, parseCron, type ScheduleTriggerSource } from '@relayflows/surface';
2
+ import { CloudFlowError, cloudFetch, cloudRequest, isCloudRecord, type CloudConnectionOptions } from './cloud-http.js';
3
+ import { cloudSubmissionBody, prepareCloudSubmission, type CloudFlowSource } from './cloud-run.js';
4
+ import type { JsonValue } from './json-value.js';
5
+
6
+ /**
7
+ * Hosted schedules. `POST /api/v1/workflows/schedules` stores a workflow
8
+ * request and relaycron fires it on the cron; each fire replays the stored
9
+ * request through the same `/workflows/run` admission a `flows run --cloud`
10
+ * takes. So a schedule sends exactly what a run sends — `prepareCloudSubmission`
11
+ * — wrapped in the schedule envelope. Nothing runs at schedule time.
12
+ */
13
+
14
+ export interface ScheduleInCloudInput {
15
+ flow: CloudFlowSource;
16
+ /** Five-field cron. Exactly one of `cron` or `every`, or neither to use the flow's declared `schedule.*`. */
17
+ cron?: string;
18
+ /** Fixed interval such as `5m`; lowered to a cron the server accepts. */
19
+ every?: string;
20
+ /** IANA zone the cron is evaluated in; default UTC. */
21
+ tz?: string;
22
+ /** Authored input, as `flows run --cloud --input`. */
23
+ input?: JsonValue;
24
+ /** Defaults to the flow's declared name. */
25
+ name?: string;
26
+ }
27
+
28
+ export interface CloudSchedule {
29
+ id: string;
30
+ name: string;
31
+ cronExpression: string;
32
+ timezone: string;
33
+ status: string;
34
+ createdAt?: string;
35
+ lastTriggeredAt?: string;
36
+ lastTriggeredRunId?: string;
37
+ lastTriggerStatus?: string;
38
+ }
39
+
40
+ const SCHEDULE_ID = /^[A-Za-z0-9_-]{1,128}$/u;
41
+
42
+ /** `every("5m")` as a cron the server accepts; only intervals cron can express exactly. */
43
+ export function everyToCron(every: string): string {
44
+ const ms = everyToMs(every);
45
+ const minutes = ms / 60_000;
46
+ if (Number.isInteger(minutes) && minutes >= 1 && minutes < 60 && 60 % minutes === 0) return `*/${minutes} * * * *`;
47
+ if (minutes === 60) return '0 * * * *';
48
+ const hours = ms / 3_600_000;
49
+ if (Number.isInteger(hours) && hours > 1 && hours < 24 && 24 % hours === 0) return `0 */${hours} * * *`;
50
+ if (hours === 24) return '0 0 * * *';
51
+ throw new CloudFlowError('invalid_input',
52
+ `--every ${every} has no exact cron: use a divisor of an hour (1m-30m), 1h, a divisor of a day (2h-12h), or 1d; or give --cron.`);
53
+ }
54
+
55
+ /** The cron a declared `schedule.*` source means on Cloud. */
56
+ export function declaredScheduleCron(source: ScheduleTriggerSource): { cron: string; tz?: string } {
57
+ if (source.cron !== undefined) return { cron: source.cron, ...(source.tz === undefined ? {} : { tz: source.tz }) };
58
+ const minutes = (source.intervalMs ?? 0) / 60_000;
59
+ const every = Number.isInteger(minutes) ? `${minutes}m` : `${Math.round((source.intervalMs ?? 0) / 1000)}s`;
60
+ return { cron: everyToCron(every) };
61
+ }
62
+
63
+ function assertTimeZone(tz: string): string {
64
+ try {
65
+ new Intl.DateTimeFormat('en-US', { timeZone: tz });
66
+ } catch {
67
+ throw new CloudFlowError('invalid_input', `--tz ${JSON.stringify(tz)} is not a known IANA zone.`);
68
+ }
69
+ return tz;
70
+ }
71
+
72
+ export async function scheduleInCloud(
73
+ input: ScheduleInCloudInput, options: CloudConnectionOptions = {},
74
+ ): Promise<CloudSchedule> {
75
+ if (input.cron !== undefined && input.every !== undefined) {
76
+ throw new CloudFlowError('invalid_input', 'Give --cron or --every, not both.');
77
+ }
78
+ const submission = await prepareCloudSubmission(input.flow, {
79
+ ...(Object.prototype.hasOwnProperty.call(input, 'input') ? { input: input.input } : {}),
80
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
81
+ });
82
+ let cron: string;
83
+ let tz = input.tz;
84
+ if (input.cron !== undefined) {
85
+ try { parseCron(input.cron); } catch (error) {
86
+ throw new CloudFlowError('invalid_input', `--cron: ${error instanceof Error ? error.message : String(error)}`);
87
+ }
88
+ cron = input.cron.trim();
89
+ } else if (input.every !== undefined) {
90
+ cron = everyToCron(input.every);
91
+ } else {
92
+ if (submission.schedules.length !== 1) {
93
+ throw new CloudFlowError('invalid_input', submission.schedules.length === 0
94
+ ? 'The flow declares no schedule.* handler; give --cron or --every.'
95
+ : 'The flow declares several schedules; say which with --cron or --every.');
96
+ }
97
+ const declared = declaredScheduleCron(submission.schedules[0]!);
98
+ cron = declared.cron;
99
+ tz ??= declared.tz;
100
+ }
101
+ const timezone = tz === undefined ? 'UTC' : assertTimeZone(tz);
102
+ const name = (input.name ?? submission.name).trim();
103
+ if (!name) throw new CloudFlowError('invalid_input', 'Schedule name must not be empty.');
104
+ options.signal?.throwIfAborted();
105
+ const result = await cloudFetch('/api/v1/workflows/schedules', options, {
106
+ method: 'POST', detail: true,
107
+ body: JSON.stringify({
108
+ name,
109
+ schedule_type: 'cron',
110
+ cron_expression: cron,
111
+ timezone,
112
+ workflowRequest: cloudSubmissionBody(submission),
113
+ }),
114
+ });
115
+ const record = isCloudRecord(result) && isCloudRecord(result.schedule) ? result.schedule : undefined;
116
+ if (record === undefined) throw new CloudFlowError('invalid_response', 'Cloud did not return a schedule.');
117
+ return toCloudSchedule(record);
118
+ }
119
+
120
+ function toCloudSchedule(row: Record<string, unknown>): CloudSchedule {
121
+ if (typeof row.id !== 'string' || !SCHEDULE_ID.test(row.id) || typeof row.name !== 'string') {
122
+ throw new CloudFlowError('invalid_response', 'Cloud returned a malformed schedule.');
123
+ }
124
+ const optional = (key: string): Record<string, string> =>
125
+ typeof row[key] === 'string' ? { [key]: row[key] as string } : {};
126
+ return {
127
+ id: row.id, name: row.name,
128
+ cronExpression: typeof row.cronExpression === 'string' ? row.cronExpression : '',
129
+ timezone: typeof row.timezone === 'string' ? row.timezone : 'UTC',
130
+ status: typeof row.status === 'string' ? row.status : 'unknown',
131
+ ...optional('createdAt'), ...optional('lastTriggeredAt'), ...optional('lastTriggeredRunId'), ...optional('lastTriggerStatus'),
132
+ };
133
+ }
134
+
135
+ export async function listCloudSchedules(options: CloudConnectionOptions = {}): Promise<CloudSchedule[]> {
136
+ const payload = await cloudRequest('/api/v1/workflows/schedules', options);
137
+ if (!isCloudRecord(payload) || !Array.isArray(payload.schedules)) {
138
+ throw new CloudFlowError('invalid_response', 'Cloud did not return a schedules list.');
139
+ }
140
+ return payload.schedules.map(row => {
141
+ if (!isCloudRecord(row)) throw new CloudFlowError('invalid_response', 'Cloud returned a malformed schedule row.');
142
+ return toCloudSchedule(row);
143
+ });
144
+ }
145
+
146
+ export async function unscheduleInCloud(scheduleId: string, options: CloudConnectionOptions = {}): Promise<void> {
147
+ if (!SCHEDULE_ID.test(scheduleId)) throw new CloudFlowError('invalid_input', `"${scheduleId}" is not a schedule id.`);
148
+ const result = await cloudFetch(`/api/v1/workflows/schedules/${encodeURIComponent(scheduleId)}`, options,
149
+ { method: 'DELETE', detail: true });
150
+ if (!isCloudRecord(result) || result.deleted !== true) {
151
+ throw new CloudFlowError('invalid_response', 'Cloud did not confirm the deletion.');
152
+ }
153
+ }
154
+
155
+ /** Exposed for previews: the tick grid a UTC cron amounts to, if it is exactly one. */
156
+ export function cronIntervalMs(cron: string): number | undefined {
157
+ return cronGrid(parseCron(cron))?.intervalMs;
158
+ }