@lovable.dev/workflows-sdk 0.0.0-dev.5 → 0.0.0-dev.52

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/index.js CHANGED
@@ -1,16 +1,802 @@
1
- import { a as defineSchedule, c as hourly, i as registerWorkflows, l as weekly, n as createMiddleware, o as daily, r as createWorkflow, s as every, t as generateManifests } from "./generate-IXn3QGVb.js";
2
- //#region src/core/smear.ts
3
- const FNV_OFFSET = 14695981039346656037n;
4
- const FNV_PRIME = 1099511628211n;
5
- const MASK = (1n << 64n) - 1n;
6
- function fnv1a64(value) {
7
- let hash = FNV_OFFSET;
8
- for (const byte of new TextEncoder().encode(value)) hash = (hash ^ BigInt(byte)) * FNV_PRIME & MASK;
9
- return hash;
10
- }
11
- function smearOffsetSeconds(projectId, scheduleId, windowSeconds) {
12
- if (!Number.isSafeInteger(windowSeconds) || windowSeconds <= 0) throw new Error("@lovable.dev/workflows-sdk: smear window must be a positive whole number of seconds");
13
- return Number(fnv1a64(`${projectId}\u0000${scheduleId}`) % BigInt(windowSeconds));
14
- }
15
- //#endregion
16
- export { createMiddleware, createWorkflow, daily, defineSchedule, every, generateManifests, hourly, registerWorkflows, smearOffsetSeconds, weekly };
1
+ import { t as DURABLE_ID_REQUIRED } from "./durable-ids-Cx341nJQ.js";
2
+ import { A as daily, D as registerWorkflows, E as createWorkflow, M as weekly, O as workflowVersions, T as createMiddleware, j as hourly, k as defineSchedule, t as generateManifests } from "./generate-C9MJlJBn.js";
3
+ import { n as assertLlmOptions, r as assertLlmRequest } from "./llm-validation-DdDO6csU.js";
4
+ import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
5
+ import { generateChatCompletion } from "@lovable.dev/ai-gateway";
6
+ //#region src/stacks/tanstack/sse.ts
7
+ const HEADERS = {
8
+ "content-type": "text/event-stream; charset=utf-8",
9
+ "cache-control": "no-cache, no-transform",
10
+ connection: "keep-alive",
11
+ "x-accel-buffering": "no"
12
+ };
13
+ function describe$1(error) {
14
+ return error instanceof Error ? error.message : String(error);
15
+ }
16
+ function frame(name, data) {
17
+ return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
18
+ }
19
+ /**
20
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
21
+ * engine `type` as the SSE event name and its whole JSON as the data line.
22
+ */
23
+ function toServerSentEventsResponse(events) {
24
+ const encoder = new TextEncoder();
25
+ const body = new ReadableStream({ async start(controller) {
26
+ let connected = true;
27
+ const write = (text) => {
28
+ if (!connected) return;
29
+ try {
30
+ controller.enqueue(encoder.encode(text));
31
+ } catch {
32
+ connected = false;
33
+ }
34
+ };
35
+ const send = (name, data) => {
36
+ try {
37
+ write(frame(name, data));
38
+ } catch (error) {
39
+ write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe$1(error)}` }));
40
+ }
41
+ };
42
+ try {
43
+ for await (const event of events) send(event.type, event);
44
+ } catch (error) {
45
+ send("STREAM_ERRORED", { message: describe$1(error) });
46
+ } finally {
47
+ try {
48
+ controller.close();
49
+ } catch {
50
+ connected = false;
51
+ }
52
+ }
53
+ } });
54
+ return new Response(body, { headers: HEADERS });
55
+ }
56
+ //#endregion
57
+ //#region src/stacks/tanstack/handlers.ts
58
+ function json$1(status, body) {
59
+ return new Response(JSON.stringify(body), {
60
+ status,
61
+ headers: { "content-type": "application/json; charset=utf-8" }
62
+ });
63
+ }
64
+ function resolveWorkflowId$1(ctx, param) {
65
+ const fromParams = ctx.params?.[param];
66
+ if (fromParams) return fromParams;
67
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
68
+ }
69
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
70
+ function createTanStackWorkflowHandler(collection, options = {}) {
71
+ const runStore = options.runStore ?? inMemoryRunStore();
72
+ const param = options.workflowIdParam ?? "workflowId";
73
+ const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
74
+ return async (ctx) => {
75
+ const workflowId = resolveWorkflowId$1(ctx, param);
76
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
77
+ if (!workflow) return json$1(404, {
78
+ error: "unknown_workflow",
79
+ workflowId: workflowId ?? ""
80
+ });
81
+ let params;
82
+ try {
83
+ params = await parseWorkflowRequest(ctx.request);
84
+ } catch (error) {
85
+ if (error instanceof WorkflowRequestParseError) return json$1(400, {
86
+ error: "invalid_request",
87
+ message: error.message
88
+ });
89
+ throw error;
90
+ }
91
+ if (params.abort) return json$1(501, {
92
+ error: "abort_unsupported",
93
+ message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
94
+ });
95
+ const state = params.runId ? await runStore.getRunState(params.runId) : void 0;
96
+ if (state && state.workflowId !== workflow.id) return json$1(409, { error: "workflow_version_unavailable" });
97
+ const readOnly = state && [
98
+ "finished",
99
+ "errored",
100
+ "aborted"
101
+ ].includes(state.status);
102
+ const selected = state && !readOnly ? workflowVersions(workflow).find((candidate) => candidate.version === state.workflowVersion) : workflow;
103
+ if (!selected) return json$1(409, { error: "workflow_version_unavailable" });
104
+ return toServerSentEventsResponse(runWorkflow({
105
+ workflow: selected,
106
+ runStore,
107
+ ...params
108
+ }));
109
+ };
110
+ }
111
+ //#endregion
112
+ //#region src/runtime/input-hash.ts
113
+ /** Key order must not change the hash, so objects are serialized sorted. */
114
+ function canonical(value) {
115
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
116
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
117
+ return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
118
+ }
119
+ /**
120
+ * Identifies the input a run started with. A resume carries it back so replay
121
+ * cannot be pointed at a different record than the one its memo came from.
122
+ */
123
+ async function hashInput(input) {
124
+ const bytes = new TextEncoder().encode(canonical(input));
125
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
126
+ return [...new Uint8Array(digest)].slice(0, 16).map((byte) => byte.toString(16).padStart(2, "0")).join("");
127
+ }
128
+ //#endregion
129
+ //#region src/runtime/operations.ts
130
+ var ReplayOperations = class {
131
+ memo;
132
+ settled;
133
+ pending = [];
134
+ consumed = /* @__PURE__ */ new Set();
135
+ never = new Promise(() => {});
136
+ error;
137
+ seq = 0;
138
+ constructor(memo, settled) {
139
+ this.memo = memo;
140
+ this.settled = settled;
141
+ }
142
+ reach(kind, stepId, meta) {
143
+ if (!stepId) {
144
+ this.error = `ctx.${kind}() was called without an id; ${DURABLE_ID_REQUIRED}`;
145
+ return;
146
+ }
147
+ const seq = this.seq++;
148
+ if (this.consumed.has(stepId)) {
149
+ this.error = `id "${stepId}" was reached more than once; every durable operation id must be unique within a workflow`;
150
+ return;
151
+ }
152
+ this.consumed.add(stepId);
153
+ const answered = this.memo.get(stepId) ?? this.settled.get(stepId);
154
+ if (!answered) return { seq };
155
+ if (answered.kind !== kind) {
156
+ this.error = `memo has ${answered.kind} "${stepId}", replay produced ${kind}`;
157
+ return;
158
+ }
159
+ if (kind === "connector" && (answered.meta?.connectorId !== meta?.connectorId || answered.meta?.connectionId !== meta?.connectionId)) {
160
+ this.error = `memo has a different connectorId or connectionId for connector "${stepId}"`;
161
+ return;
162
+ }
163
+ const recordedGroupId = groupId(answered.meta);
164
+ if (recordedGroupId !== void 0 && recordedGroupId !== groupId(meta)) {
165
+ this.error = `memo has group "${recordedGroupId}" for step "${stepId}", replay produced a different group`;
166
+ return;
167
+ }
168
+ if (answered.status === "completed") {
169
+ if (kind === "llm" && typeof answered.result !== "string") {
170
+ this.error = `memo has a non-string result for llm "${stepId}"`;
171
+ return;
172
+ }
173
+ return {
174
+ seq,
175
+ answer: Promise.resolve(answered.result)
176
+ };
177
+ }
178
+ return {
179
+ seq,
180
+ answer: Promise.reject(new Error(answered.error ?? `step "${stepId}" failed`))
181
+ };
182
+ }
183
+ };
184
+ function isRunnableKind(kind) {
185
+ return kind === "step" || kind === "llm" || kind === "connector";
186
+ }
187
+ function groupId(meta) {
188
+ const group = meta?.group;
189
+ if (group === null || typeof group !== "object") return void 0;
190
+ const id = group.id;
191
+ return typeof id === "string" ? id : void 0;
192
+ }
193
+ //#endregion
194
+ //#region src/core/connector.ts
195
+ function assertConnectorOptions(options) {
196
+ if (options === null || typeof options !== "object") throw new Error("@lovable.dev/workflows-sdk: ctx.connector() requires an options object");
197
+ const fields = options;
198
+ for (const field of ["connectorId", "connectionId"]) {
199
+ const value = fields[field];
200
+ if (typeof value !== "string" || !value.trim()) throw new Error(`@lovable.dev/workflows-sdk: ctx.connector() requires a nonempty ${field}`);
201
+ }
202
+ }
203
+ //#endregion
204
+ //#region src/runtime/llm.ts
205
+ const completeChat = generateChatCompletion;
206
+ function chatRequest(request) {
207
+ const messages = request.prompt !== void 0 ? [{
208
+ role: "user",
209
+ content: request.prompt
210
+ }] : request.messages;
211
+ const conversation = [...request.system === void 0 ? [] : [{
212
+ role: "system",
213
+ content: request.system
214
+ }], ...messages];
215
+ const maxTokens = request.maxTokens ?? 4096;
216
+ if (request.model.startsWith("openai/")) return {
217
+ model: request.model,
218
+ messages: conversation,
219
+ max_completion_tokens: maxTokens
220
+ };
221
+ if (request.model.startsWith("google/gemini-")) return {
222
+ model: request.model,
223
+ messages: conversation,
224
+ max_tokens: maxTokens,
225
+ modalities: ["text"]
226
+ };
227
+ throw new Error("ctx.llm requires an OpenAI or Gemini model with Chat Completions text support");
228
+ }
229
+ async function generateLlmText(request, options) {
230
+ assertLlmRequest(request);
231
+ const message = (await completeChat(chatRequest(request), {
232
+ ...options,
233
+ maxRetries: 0
234
+ }))?.choices?.[0]?.message;
235
+ if (message?.refusal || typeof message?.content !== "string" || message.content.trim() === "") throw new Error("AI Gateway returned no assistant text");
236
+ return message.content;
237
+ }
238
+ //#endregion
239
+ //#region src/runtime/replay.ts
240
+ /** How long a pass waits for handler work that is not a durable operation. */
241
+ const DEFAULT_SETTLE_MS = 5e3;
242
+ const EXECUTABLE = /* @__PURE__ */ new Set([
243
+ "step",
244
+ "llm",
245
+ "connector",
246
+ "now",
247
+ "uuid"
248
+ ]);
249
+ function describe(error) {
250
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
251
+ }
252
+ function runtimeContext() {
253
+ return {
254
+ timeRemaining: () => Number.POSITIVE_INFINITY,
255
+ shouldYield: () => false,
256
+ yield: async () => {}
257
+ };
258
+ }
259
+ /** Thread the handler through `.middleware([...])`, merging each extension into ctx. */
260
+ async function throughMiddleware(middlewares, ctx, handler) {
261
+ let index = 0;
262
+ const dispatch = async () => {
263
+ const middleware = middlewares[index++];
264
+ if (!middleware) return handler(ctx);
265
+ return middleware.server({
266
+ ctx,
267
+ next: async ({ context }) => {
268
+ Object.assign(ctx, context);
269
+ return dispatch();
270
+ }
271
+ });
272
+ };
273
+ return dispatch();
274
+ }
275
+ async function replay(options) {
276
+ const { workflow, input, runId } = options;
277
+ const byKey = new Map(options.memo.map((entry) => [entry.stepId, entry]));
278
+ const allow = options.shouldExecute ?? (() => true);
279
+ const settled = /* @__PURE__ */ new Map();
280
+ const operations = new ReplayOperations(byKey, settled);
281
+ const { pending, consumed, never } = operations;
282
+ const pass = { stepsSettled: 0 };
283
+ let lastProgress = Date.now();
284
+ let currentParent;
285
+ const results = [];
286
+ const emitted = [];
287
+ const inflight = [];
288
+ function record(entry) {
289
+ settled.set(entry.stepId, entry);
290
+ lastProgress = Date.now();
291
+ if (isRunnableKind(entry.kind)) pass.stepsSettled += 1;
292
+ const result = {
293
+ seq: entry.seq,
294
+ stepId: entry.stepId,
295
+ kind: entry.kind,
296
+ ...entry.meta ? { meta: entry.meta } : {},
297
+ status: entry.status,
298
+ result: entry.result,
299
+ error: entry.error
300
+ };
301
+ results.push(result);
302
+ options.onStepSettle?.(result);
303
+ }
304
+ function durable(kind, stepId, run, config, meta) {
305
+ const operation = operations.reach(kind, stepId, meta);
306
+ if (!operation || !stepId) return never;
307
+ if (operation.answer) return operation.answer;
308
+ const index = operation.seq;
309
+ const parent = currentParent;
310
+ const intent = {
311
+ seq: index,
312
+ stepId,
313
+ kind,
314
+ ...config ? { config } : {},
315
+ ...meta ? { meta } : {}
316
+ };
317
+ if (!run || !EXECUTABLE.has(kind) || !allow(intent, pass)) {
318
+ pending.push(intent);
319
+ return never;
320
+ }
321
+ options.onStepStart?.(intent);
322
+ const enclosing = currentParent;
323
+ currentParent = stepId;
324
+ let body;
325
+ try {
326
+ body = run();
327
+ } finally {
328
+ currentParent = enclosing;
329
+ }
330
+ const running = body.then((result) => {
331
+ record({
332
+ seq: index,
333
+ stepId,
334
+ kind,
335
+ status: "completed",
336
+ result,
337
+ ...parent ? { parent } : {},
338
+ ...meta ? { meta } : {}
339
+ });
340
+ return result;
341
+ }, (error) => {
342
+ record({
343
+ seq: index,
344
+ stepId,
345
+ kind,
346
+ status: "failed",
347
+ error: describe(error),
348
+ ...parent ? { parent } : {},
349
+ ...meta ? { meta } : {}
350
+ });
351
+ throw error;
352
+ });
353
+ inflight.push(running.then(noop, noop));
354
+ return running;
355
+ }
356
+ const state = { ...workflow.initialize?.({ input }) };
357
+ const runtime = runtimeContext();
358
+ const signal = options.signal ?? new AbortController().signal;
359
+ function connector(id, callback, stepOptions) {
360
+ assertConnectorOptions(stepOptions);
361
+ return durable("connector", id, async () => {
362
+ const result = await callback({
363
+ id,
364
+ attempt: 1,
365
+ runtime,
366
+ signal
367
+ });
368
+ return result === void 0 ? null : result;
369
+ }, void 0, {
370
+ ...stepOptions.meta,
371
+ connectorId: stepOptions.connectorId,
372
+ connectionId: stepOptions.connectionId
373
+ });
374
+ }
375
+ const llm = (request, stepOptions) => {
376
+ assertLlmOptions(stepOptions);
377
+ return durable("llm", stepOptions.id, () => generateLlmText(request, {
378
+ signal,
379
+ runId,
380
+ metadata: {
381
+ workflow_id: workflow.id,
382
+ workflow_step_id: stepOptions.id
383
+ }
384
+ }), void 0, stepOptions.meta);
385
+ };
386
+ const ctx = {
387
+ runId,
388
+ input,
389
+ state,
390
+ signal,
391
+ runtime,
392
+ connector,
393
+ llm,
394
+ step: (id, fn, stepOptions) => durable("step", id, async () => fn({
395
+ id,
396
+ attempt: 1,
397
+ runtime,
398
+ signal
399
+ }), void 0, stepOptions?.meta),
400
+ sleep: (ms, opts) => durable("sleep", opts?.id, void 0, { ms }, opts?.meta),
401
+ sleepUntil: (timestamp, opts) => durable("sleep", opts?.id, void 0, { timestamp }, opts?.meta),
402
+ waitForEvent: (name, opts) => durable("waitForEvent", opts?.id, void 0, { name }, opts?.meta),
403
+ approve: (opts) => durable("approve", opts.id, void 0, {
404
+ title: opts.title,
405
+ ...opts.description === void 0 ? {} : { description: opts.description }
406
+ }, {
407
+ ...opts.meta,
408
+ ...opts.description === void 0 ? {} : { description: opts.description }
409
+ }),
410
+ now: (opts) => durable("now", opts?.id, async () => Date.now(), void 0, opts?.meta),
411
+ uuid: (opts) => durable("uuid", opts?.id, async () => crypto.randomUUID(), void 0, opts?.meta),
412
+ emit: (name, value) => {
413
+ emitted.push({
414
+ name,
415
+ value
416
+ });
417
+ }
418
+ };
419
+ let outcome;
420
+ throughMiddleware(workflow.middlewares ?? [], ctx, workflow.handler).then((output) => {
421
+ outcome = {
422
+ status: "completed",
423
+ output: output ?? null
424
+ };
425
+ }, (error) => {
426
+ outcome = {
427
+ status: "failed",
428
+ error: describe(error)
429
+ };
430
+ });
431
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
432
+ for (;;) {
433
+ for (let tick = 0; tick < 20; tick++) await new Promise((resolve) => setTimeout(resolve, 0));
434
+ if (outcome || operations.error) break;
435
+ if (inflight.length > 0) {
436
+ await Promise.all(inflight.splice(0));
437
+ lastProgress = Date.now();
438
+ continue;
439
+ }
440
+ if (pending.length > 0 || Date.now() - lastProgress >= settleMs) break;
441
+ await new Promise((resolve) => setTimeout(resolve, 5));
442
+ }
443
+ while (inflight.length > 0) await Promise.all(inflight.splice(0));
444
+ const memo = [...byKey.values(), ...settled.values()];
445
+ const hidden = (start) => {
446
+ const seen = /* @__PURE__ */ new Set([start]);
447
+ let key = start;
448
+ for (;;) {
449
+ const parent = byKey.get(key)?.parent;
450
+ if (parent === void 0 || seen.has(parent)) return false;
451
+ if (consumed.has(parent)) return true;
452
+ seen.add(parent);
453
+ key = parent;
454
+ }
455
+ };
456
+ const orphan = [...byKey.keys()].find((key) => !consumed.has(key) && !hidden(key));
457
+ pending.sort((a, b) => a.seq - b.seq);
458
+ results.sort((a, b) => a.seq - b.seq);
459
+ const base = {
460
+ memo,
461
+ results,
462
+ emitted
463
+ };
464
+ if (operations.error) return {
465
+ ...base,
466
+ status: "failed",
467
+ steps: [],
468
+ error: `non-deterministic replay: ${operations.error}`
469
+ };
470
+ if (orphan !== void 0) return {
471
+ ...base,
472
+ status: "failed",
473
+ steps: [],
474
+ error: `stale memo: no operation matched "${orphan}"`
475
+ };
476
+ if (outcome?.status === "completed") return {
477
+ ...base,
478
+ status: "completed",
479
+ steps: [],
480
+ output: outcome.output
481
+ };
482
+ if (outcome?.status === "failed") return {
483
+ ...base,
484
+ status: "failed",
485
+ steps: [],
486
+ error: outcome.error
487
+ };
488
+ if (pending.length > 0) return {
489
+ ...base,
490
+ status: "pending",
491
+ steps: pending
492
+ };
493
+ return {
494
+ ...base,
495
+ status: "failed",
496
+ steps: [],
497
+ error: `workflow stalled: no durable operation and nothing settled for ${settleMs}ms`
498
+ };
499
+ }
500
+ function noop() {}
501
+ //#endregion
502
+ //#region src/stacks/tanstack/project-auth.ts
503
+ const PROJECT_SECRET_ENV_VAR = "LOVABLE_WORKFLOWS_KEY";
504
+ let cloudflareEnvPromise;
505
+ function readProcessSecret() {
506
+ const value = (globalThis.process?.env)?.[PROJECT_SECRET_ENV_VAR];
507
+ return typeof value === "string" && value ? value : void 0;
508
+ }
509
+ async function readCloudflareSecret() {
510
+ cloudflareEnvPromise ??= import(
511
+ /* @vite-ignore */
512
+ "cloudflare:workers"
513
+ ).then((module) => module.env).catch(() => void 0);
514
+ const value = (await cloudflareEnvPromise)?.[PROJECT_SECRET_ENV_VAR];
515
+ return typeof value === "string" && value ? value : void 0;
516
+ }
517
+ async function resolveProjectSecret() {
518
+ return readProcessSecret() ?? await readCloudflareSecret();
519
+ }
520
+ function bearerToken(request) {
521
+ const header = request.headers.get("authorization");
522
+ if (!header) return void 0;
523
+ const parts = header.trim().split(/\s+/);
524
+ if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") return void 0;
525
+ return parts[1] || void 0;
526
+ }
527
+ async function equalSecrets(left, right) {
528
+ const encoder = new TextEncoder();
529
+ const [leftHash, rightHash] = await Promise.all([crypto.subtle.digest("SHA-256", encoder.encode(left)), crypto.subtle.digest("SHA-256", encoder.encode(right))]);
530
+ const leftBytes = new Uint8Array(leftHash);
531
+ const rightBytes = new Uint8Array(rightHash);
532
+ let difference = 0;
533
+ for (let index = 0; index < leftBytes.length; index += 1) difference |= leftBytes[index] ^ rightBytes[index];
534
+ return difference === 0;
535
+ }
536
+ async function authorizeProjectRequest(request, getProjectSecret) {
537
+ let projectSecret;
538
+ try {
539
+ projectSecret = await getProjectSecret();
540
+ } catch {
541
+ return "unavailable";
542
+ }
543
+ if (!projectSecret) return "unavailable";
544
+ const token = bearerToken(request);
545
+ if (!token) return "unauthorized";
546
+ try {
547
+ return await equalSecrets(token, projectSecret) ? "authorized" : "unauthorized";
548
+ } catch {
549
+ return "unavailable";
550
+ }
551
+ }
552
+ //#endregion
553
+ //#region src/stacks/tanstack/steps-response.ts
554
+ function disposition(outcome) {
555
+ if (outcome.status === "completed") return "completed";
556
+ if (outcome.status === "failed") return "failed";
557
+ if (!outcome.steps.some((step) => isRunnableKind(step.kind))) return "waiting";
558
+ return outcome.steps.length > 1 ? "fork" : "advanced";
559
+ }
560
+ function memoDelta(before, after) {
561
+ const existing = new Set(before.map((entry) => entry.stepId));
562
+ return after.filter((entry) => !existing.has(entry.stepId));
563
+ }
564
+ function stepsResponse(runId, inputHash, workflowVersion, before, outcome, executed) {
565
+ const { steps, emitted, output, error } = outcome;
566
+ const base = {
567
+ runId,
568
+ inputHash,
569
+ workflowVersion,
570
+ memoDelta: memoDelta(before, outcome.memo),
571
+ next: steps,
572
+ ...emitted.length > 0 ? { emitted } : {}
573
+ };
574
+ const nextDisposition = disposition(outcome);
575
+ const deferred = executed?.status === "completed" && nextDisposition !== "fork";
576
+ return {
577
+ ...base,
578
+ disposition: deferred ? "advanced" : nextDisposition,
579
+ next: deferred && nextDisposition === "waiting" ? [] : steps,
580
+ ...executed === void 0 ? {} : { executed },
581
+ ...deferred || output === void 0 ? {} : { output },
582
+ ...deferred || error === void 0 ? {} : { error }
583
+ };
584
+ }
585
+ //#endregion
586
+ //#region src/stacks/tanstack/steps.ts
587
+ function json(status, body) {
588
+ return new Response(JSON.stringify(body), {
589
+ status,
590
+ headers: { "content-type": "application/json; charset=utf-8" }
591
+ });
592
+ }
593
+ function unauthorized() {
594
+ const response = json(401, { error: "unauthorized" });
595
+ response.headers.set("www-authenticate", "Bearer");
596
+ return response;
597
+ }
598
+ function authUnavailable() {
599
+ return json(503, {
600
+ error: "workflow_auth_unavailable",
601
+ message: "LOVABLE_WORKFLOWS_KEY is not configured in this app runtime"
602
+ });
603
+ }
604
+ function resolveWorkflowId(ctx, param) {
605
+ const fromParams = ctx.params?.[param];
606
+ if (fromParams) return fromParams;
607
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-2);
608
+ }
609
+ function isMemoEntry(value) {
610
+ const entry = value;
611
+ return typeof entry === "object" && entry !== null && Number.isInteger(entry.seq) && entry.seq >= 0 && typeof entry.stepId === "string" && Number.isInteger(entry.seq) && (entry.status === "completed" || entry.status === "failed");
612
+ }
613
+ function parseBody(value) {
614
+ if (value === null || typeof value !== "object") return "body must be a JSON object";
615
+ const body = value;
616
+ if (body.workflowVersion !== void 0 && typeof body.workflowVersion !== "string") return "workflowVersion must be a string";
617
+ if (body.memo !== void 0) {
618
+ if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
619
+ if (new Set(body.memo.map((entry) => entry.stepId)).size !== body.memo.length) return "memo entries must be unique per stepId";
620
+ }
621
+ if (body.action !== void 0 && body.action !== "advance" && body.action !== "execute") return "action must be \"advance\" or \"execute\"";
622
+ if (body.action === "execute" && !isStepReference(body.step)) return "step must be a { kind: \"step\" | \"llm\" | \"connector\", stepId } reference when action is \"execute\"";
623
+ if (body.action !== "execute" && body.step !== void 0) return "step is only valid when action is \"execute\"";
624
+ if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
625
+ return body;
626
+ }
627
+ async function readBody(request) {
628
+ const text = await request.text();
629
+ if (!text.trim()) return {};
630
+ return JSON.parse(text);
631
+ }
632
+ function isStepReference(value) {
633
+ const step = value;
634
+ return typeof step === "object" && step !== null && isRunnableKind(step.kind) && typeof step.stepId === "string";
635
+ }
636
+ function prepare(collection, options) {
637
+ return {
638
+ param: options.workflowIdParam ?? "workflowId",
639
+ byId: new Map(collection.workflows.map((workflow) => [workflow.id, workflow])),
640
+ getProjectSecret: options.getProjectSecret ?? resolveProjectSecret
641
+ };
642
+ }
643
+ async function validateSchema(schema, value) {
644
+ return schema["~standard"].validate(value);
645
+ }
646
+ function validationError(label, issues) {
647
+ const detail = issues.map((issue) => issue.message).join("; ");
648
+ return `workflow ${label} failed validation${detail ? `: ${detail}` : ""}`;
649
+ }
650
+ async function validateInput(workflow, input) {
651
+ if (!workflow.inputSchema) return { input };
652
+ let result;
653
+ try {
654
+ result = await validateSchema(workflow.inputSchema, input);
655
+ } catch {
656
+ return json(500, {
657
+ error: "input_validation_failed",
658
+ message: "workflow input schema could not be evaluated"
659
+ });
660
+ }
661
+ if (result.issues) return json(400, {
662
+ error: "invalid_input",
663
+ message: validationError("input", result.issues)
664
+ });
665
+ return { input: result.value };
666
+ }
667
+ async function validateOutput(workflow, outcome) {
668
+ if (outcome.status !== "completed" || !workflow.outputSchema || outcome.results.some((result) => isRunnableKind(result.kind) && result.status === "completed")) return outcome;
669
+ let result;
670
+ try {
671
+ result = await validateSchema(workflow.outputSchema, outcome.output);
672
+ } catch {
673
+ return {
674
+ status: "failed",
675
+ memo: outcome.memo,
676
+ steps: [],
677
+ results: outcome.results,
678
+ emitted: outcome.emitted,
679
+ error: "workflow output schema could not be evaluated"
680
+ };
681
+ }
682
+ if (result.issues) return {
683
+ status: "failed",
684
+ memo: outcome.memo,
685
+ steps: [],
686
+ results: outcome.results,
687
+ emitted: outcome.emitted,
688
+ error: validationError("output", result.issues)
689
+ };
690
+ return {
691
+ ...outcome,
692
+ output: result.value
693
+ };
694
+ }
695
+ async function resolve(ctx, param, byId) {
696
+ const workflowId = resolveWorkflowId(ctx, param);
697
+ const current = workflowId === void 0 ? void 0 : byId.get(workflowId);
698
+ if (!current) return json(404, {
699
+ error: "unknown_workflow",
700
+ workflowId: workflowId ?? ""
701
+ });
702
+ let raw;
703
+ try {
704
+ raw = await readBody(ctx.request);
705
+ } catch (error) {
706
+ return json(400, {
707
+ error: "invalid_request",
708
+ message: `body is not valid JSON: ${String(error)}`
709
+ });
710
+ }
711
+ const body = parseBody(raw);
712
+ if (typeof body === "string") return json(400, {
713
+ error: "invalid_request",
714
+ message: body
715
+ });
716
+ const versions = workflowVersions(current);
717
+ if (body.workflowVersion === void 0 && (body.runId !== void 0 || body.memo !== void 0 || body.action === "execute")) return json(400, {
718
+ error: "workflow_version_required",
719
+ message: "Resuming a run requires its pinned workflowVersion"
720
+ });
721
+ const workflow = body.workflowVersion === void 0 ? versions[0] : versions.find((candidate) => candidate.version === body.workflowVersion);
722
+ if (!workflow) return json(409, {
723
+ error: "workflow_version_unavailable",
724
+ workflowId,
725
+ workflowVersion: body.workflowVersion
726
+ });
727
+ if (workflow !== current && !body.runId) return json(400, {
728
+ error: "retained_version_requires_run",
729
+ message: "Retained versions can only resume an existing run"
730
+ });
731
+ const wireInput = body.input ?? null;
732
+ const validated = await validateInput(workflow, wireInput);
733
+ if (validated instanceof Response) return validated;
734
+ const { input } = validated;
735
+ const inputHash = await hashInput(wireInput);
736
+ if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) return json(400, {
737
+ error: "invalid_request",
738
+ message: body.inputHash === void 0 ? "inputHash must be sent with a memo; echo the value from the previous response" : "input does not match the run this memo came from"
739
+ });
740
+ return {
741
+ workflow,
742
+ body,
743
+ input,
744
+ runId: body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
745
+ inputHash
746
+ };
747
+ }
748
+ function createStepsHandler(collection, options = {}) {
749
+ const { param, byId, getProjectSecret } = prepare(collection, options);
750
+ return async (ctx) => {
751
+ const auth = await authorizeProjectRequest(ctx.request, getProjectSecret);
752
+ if (auth === "unauthorized") return unauthorized();
753
+ if (auth === "unavailable") return authUnavailable();
754
+ const resolved = await resolve(ctx, param, byId);
755
+ if (resolved instanceof Response) return resolved;
756
+ const { workflow, body, input, runId, inputHash } = resolved;
757
+ const before = body.memo ?? [];
758
+ if (body.action === "execute") {
759
+ const selected = body.step;
760
+ const outcome = await validateOutput(workflow, await replay({
761
+ workflow,
762
+ input,
763
+ memo: before,
764
+ runId,
765
+ signal: ctx.request.signal,
766
+ shouldExecute: (intent) => !isRunnableKind(intent.kind) || intent.kind === selected.kind && intent.stepId === selected.stepId
767
+ }));
768
+ const executed = outcome.results.find((result) => result.kind === selected.kind && result.stepId === selected.stepId);
769
+ if (executed === void 0 && outcome.status !== "failed") return json(409, {
770
+ error: "stale_step",
771
+ message: `step "${selected.stepId}" is not executable from this memo`
772
+ });
773
+ return json(200, stepsResponse(runId, inputHash, workflow.version, before, outcome, executed));
774
+ }
775
+ const described = await validateOutput(workflow, await replay({
776
+ workflow,
777
+ input,
778
+ memo: before,
779
+ runId,
780
+ signal: ctx.request.signal,
781
+ shouldExecute: (intent) => !isRunnableKind(intent.kind)
782
+ }));
783
+ const only = described.steps.length === 1 ? described.steps[0] : void 0;
784
+ if (described.status !== "pending" || !only || !isRunnableKind(only.kind)) return json(200, stepsResponse(runId, inputHash, workflow.version, before, described));
785
+ const outcome = await validateOutput(workflow, await replay({
786
+ workflow,
787
+ input,
788
+ memo: described.memo,
789
+ runId,
790
+ signal: ctx.request.signal,
791
+ shouldExecute: (intent) => !isRunnableKind(intent.kind) || intent.kind === only.kind && intent.stepId === only.stepId
792
+ }));
793
+ const executed = outcome.results.find((result) => result.kind === only.kind && result.stepId === only.stepId);
794
+ if (executed === void 0 && outcome.status !== "failed") return json(409, {
795
+ error: "stale_step",
796
+ message: `step "${only.stepId}" is not executable from this memo`
797
+ });
798
+ return json(200, stepsResponse(runId, inputHash, workflow.version, before, outcome, executed));
799
+ };
800
+ }
801
+ //#endregion
802
+ export { createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };