@lovable.dev/workflows-sdk 0.0.0-dev.7 → 0.0.0-dev.9
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/README.md +209 -20
- package/dist/index.d.ts +112 -2
- package/dist/index.js +630 -1
- package/dist/vite.js +142 -16
- package/package.json +2 -5
- package/dist/stacks/tanstack/index.d.ts +0 -31
- package/dist/stacks/tanstack/index.js +0 -99
package/dist/index.js
CHANGED
|
@@ -1,2 +1,631 @@
|
|
|
1
1
|
import { a as defineSchedule, c as weekly, i as registerWorkflows, n as createMiddleware, o as daily, r as createWorkflow, s as hourly, t as generateManifests } from "./generate-DyUHbtre.js";
|
|
2
|
-
|
|
2
|
+
import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
|
|
3
|
+
//#region src/stacks/tanstack/sse.ts
|
|
4
|
+
const HEADERS = {
|
|
5
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
6
|
+
"cache-control": "no-cache, no-transform",
|
|
7
|
+
connection: "keep-alive",
|
|
8
|
+
"x-accel-buffering": "no"
|
|
9
|
+
};
|
|
10
|
+
function describe$1(error) {
|
|
11
|
+
return error instanceof Error ? error.message : String(error);
|
|
12
|
+
}
|
|
13
|
+
function frame(name, data) {
|
|
14
|
+
return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Encode a workflow event stream as `text/event-stream`. Each event keeps its
|
|
18
|
+
* engine `type` as the SSE event name and its whole JSON as the data line.
|
|
19
|
+
*/
|
|
20
|
+
function toServerSentEventsResponse(events) {
|
|
21
|
+
const encoder = new TextEncoder();
|
|
22
|
+
const body = new ReadableStream({ async start(controller) {
|
|
23
|
+
let connected = true;
|
|
24
|
+
const write = (text) => {
|
|
25
|
+
if (!connected) return;
|
|
26
|
+
try {
|
|
27
|
+
controller.enqueue(encoder.encode(text));
|
|
28
|
+
} catch {
|
|
29
|
+
connected = false;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
const send = (name, data) => {
|
|
33
|
+
try {
|
|
34
|
+
write(frame(name, data));
|
|
35
|
+
} catch (error) {
|
|
36
|
+
write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe$1(error)}` }));
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
try {
|
|
40
|
+
for await (const event of events) send(event.type, event);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
send("STREAM_ERRORED", { message: describe$1(error) });
|
|
43
|
+
} finally {
|
|
44
|
+
try {
|
|
45
|
+
controller.close();
|
|
46
|
+
} catch {
|
|
47
|
+
connected = false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
} });
|
|
51
|
+
return new Response(body, { headers: HEADERS });
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
//#region src/stacks/tanstack/handlers.ts
|
|
55
|
+
function json$1(status, body) {
|
|
56
|
+
return new Response(JSON.stringify(body), {
|
|
57
|
+
status,
|
|
58
|
+
headers: { "content-type": "application/json; charset=utf-8" }
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
function resolveWorkflowId$1(ctx, param) {
|
|
62
|
+
const fromParams = ctx.params?.[param];
|
|
63
|
+
if (fromParams) return fromParams;
|
|
64
|
+
return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
|
|
65
|
+
}
|
|
66
|
+
/** Build a TanStack Start `POST` handler serving every workflow in the collection. */
|
|
67
|
+
function createTanStackWorkflowHandler(collection, options = {}) {
|
|
68
|
+
const runStore = options.runStore ?? inMemoryRunStore();
|
|
69
|
+
const param = options.workflowIdParam ?? "workflowId";
|
|
70
|
+
const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
|
|
71
|
+
return async (ctx) => {
|
|
72
|
+
const workflowId = resolveWorkflowId$1(ctx, param);
|
|
73
|
+
const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
|
|
74
|
+
if (!workflow) return json$1(404, {
|
|
75
|
+
error: "unknown_workflow",
|
|
76
|
+
workflowId: workflowId ?? ""
|
|
77
|
+
});
|
|
78
|
+
let params;
|
|
79
|
+
try {
|
|
80
|
+
params = await parseWorkflowRequest(ctx.request);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error instanceof WorkflowRequestParseError) return json$1(400, {
|
|
83
|
+
error: "invalid_request",
|
|
84
|
+
message: error.message
|
|
85
|
+
});
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
if (params.abort) return json$1(501, {
|
|
89
|
+
error: "abort_unsupported",
|
|
90
|
+
message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
|
|
91
|
+
});
|
|
92
|
+
return toServerSentEventsResponse(runWorkflow({
|
|
93
|
+
workflow,
|
|
94
|
+
runStore,
|
|
95
|
+
...params
|
|
96
|
+
}));
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/runtime/input-hash.ts
|
|
101
|
+
/** Key order must not change the hash, so objects are serialized sorted. */
|
|
102
|
+
function canonical(value) {
|
|
103
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
104
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
105
|
+
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(",")}}`;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Identifies the input a run started with. A resume carries it back so replay
|
|
109
|
+
* cannot be pointed at a different record than the one its memo came from.
|
|
110
|
+
*/
|
|
111
|
+
async function hashInput(input) {
|
|
112
|
+
const bytes = new TextEncoder().encode(canonical(input));
|
|
113
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
114
|
+
return [...new Uint8Array(digest)].slice(0, 16).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/runtime/replay.ts
|
|
118
|
+
/** How long a pass waits for handler work that is not a durable operation. */
|
|
119
|
+
const DEFAULT_SETTLE_MS = 5e3;
|
|
120
|
+
function memoKey(stepId, occurrence) {
|
|
121
|
+
return `${stepId}#${occurrence}`;
|
|
122
|
+
}
|
|
123
|
+
const EXECUTABLE = /* @__PURE__ */ new Set([
|
|
124
|
+
"step",
|
|
125
|
+
"now",
|
|
126
|
+
"uuid"
|
|
127
|
+
]);
|
|
128
|
+
function describe(error) {
|
|
129
|
+
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
130
|
+
}
|
|
131
|
+
function runtimeContext() {
|
|
132
|
+
return {
|
|
133
|
+
timeRemaining: () => Number.POSITIVE_INFINITY,
|
|
134
|
+
shouldYield: () => false,
|
|
135
|
+
yield: async () => {}
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/** Thread the handler through `.middleware([...])`, merging each extension into ctx. */
|
|
139
|
+
async function throughMiddleware(middlewares, ctx, handler) {
|
|
140
|
+
let index = 0;
|
|
141
|
+
const dispatch = async () => {
|
|
142
|
+
const middleware = middlewares[index++];
|
|
143
|
+
if (!middleware) return handler(ctx);
|
|
144
|
+
return middleware.server({
|
|
145
|
+
ctx,
|
|
146
|
+
next: async ({ context }) => {
|
|
147
|
+
Object.assign(ctx, context);
|
|
148
|
+
return dispatch();
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
};
|
|
152
|
+
return dispatch();
|
|
153
|
+
}
|
|
154
|
+
async function replay(options) {
|
|
155
|
+
const { workflow, input, runId } = options;
|
|
156
|
+
const byKey = new Map(options.memo.map((entry) => [memoKey(entry.stepId, entry.occurrence ?? 0), entry]));
|
|
157
|
+
const allow = options.shouldExecute ?? (() => true);
|
|
158
|
+
const never = new Promise(() => {});
|
|
159
|
+
const pending = [];
|
|
160
|
+
const settled = /* @__PURE__ */ new Map();
|
|
161
|
+
const pass = { stepsSettled: 0 };
|
|
162
|
+
const occurrences = /* @__PURE__ */ new Map();
|
|
163
|
+
const consumed = /* @__PURE__ */ new Set();
|
|
164
|
+
let lastProgress = Date.now();
|
|
165
|
+
const results = [];
|
|
166
|
+
const emitted = [];
|
|
167
|
+
const inflight = [];
|
|
168
|
+
let seq = 0;
|
|
169
|
+
let nonDeterminism;
|
|
170
|
+
function record(entry) {
|
|
171
|
+
settled.set(memoKey(entry.stepId, entry.occurrence), entry);
|
|
172
|
+
lastProgress = Date.now();
|
|
173
|
+
if (entry.kind === "step") pass.stepsSettled += 1;
|
|
174
|
+
const result = {
|
|
175
|
+
seq: entry.seq,
|
|
176
|
+
stepId: entry.stepId,
|
|
177
|
+
occurrence: entry.occurrence,
|
|
178
|
+
kind: entry.kind,
|
|
179
|
+
status: entry.status,
|
|
180
|
+
result: entry.result,
|
|
181
|
+
error: entry.error
|
|
182
|
+
};
|
|
183
|
+
results.push(result);
|
|
184
|
+
options.onStepSettle?.(result);
|
|
185
|
+
}
|
|
186
|
+
function durable(kind, stepId, run, config, defaulted = false) {
|
|
187
|
+
const index = seq++;
|
|
188
|
+
const occurrence = occurrences.get(stepId) ?? 0;
|
|
189
|
+
occurrences.set(stepId, occurrence + 1);
|
|
190
|
+
if (defaulted && occurrence > 0) {
|
|
191
|
+
nonDeterminism = `ctx.${kind}() was reached more than once with the default id "${stepId}"; pass an explicit { id } per call site`;
|
|
192
|
+
return never;
|
|
193
|
+
}
|
|
194
|
+
const key = memoKey(stepId, occurrence);
|
|
195
|
+
consumed.add(key);
|
|
196
|
+
const answered = byKey.get(key) ?? settled.get(key);
|
|
197
|
+
if (answered) {
|
|
198
|
+
if (answered.kind !== kind) {
|
|
199
|
+
nonDeterminism = `memo has ${answered.kind} "${stepId}" (#${occurrence}), replay produced ${kind}`;
|
|
200
|
+
return never;
|
|
201
|
+
}
|
|
202
|
+
if (answered.status === "completed") return Promise.resolve(answered.result);
|
|
203
|
+
return Promise.reject(new Error(answered.error ?? `step "${stepId}" failed`));
|
|
204
|
+
}
|
|
205
|
+
const intent = {
|
|
206
|
+
seq: index,
|
|
207
|
+
stepId,
|
|
208
|
+
occurrence,
|
|
209
|
+
kind,
|
|
210
|
+
...config ? { config } : {}
|
|
211
|
+
};
|
|
212
|
+
if (!run || !EXECUTABLE.has(kind) || !allow(intent, pass)) {
|
|
213
|
+
pending.push(intent);
|
|
214
|
+
return never;
|
|
215
|
+
}
|
|
216
|
+
options.onStepStart?.(intent);
|
|
217
|
+
const running = run().then((result) => {
|
|
218
|
+
record({
|
|
219
|
+
seq: index,
|
|
220
|
+
stepId,
|
|
221
|
+
occurrence,
|
|
222
|
+
kind,
|
|
223
|
+
status: "completed",
|
|
224
|
+
result
|
|
225
|
+
});
|
|
226
|
+
return result;
|
|
227
|
+
}, (error) => {
|
|
228
|
+
record({
|
|
229
|
+
seq: index,
|
|
230
|
+
stepId,
|
|
231
|
+
occurrence,
|
|
232
|
+
kind,
|
|
233
|
+
status: "failed",
|
|
234
|
+
error: describe(error)
|
|
235
|
+
});
|
|
236
|
+
throw error;
|
|
237
|
+
});
|
|
238
|
+
inflight.push(running.then(noop, noop));
|
|
239
|
+
return running;
|
|
240
|
+
}
|
|
241
|
+
const state = { ...workflow.initialize?.({ input }) };
|
|
242
|
+
const runtime = runtimeContext();
|
|
243
|
+
const controller = new AbortController();
|
|
244
|
+
const ctx = {
|
|
245
|
+
runId,
|
|
246
|
+
input,
|
|
247
|
+
state,
|
|
248
|
+
signal: controller.signal,
|
|
249
|
+
runtime,
|
|
250
|
+
step: (id, fn, _options) => durable("step", id, async () => fn({
|
|
251
|
+
id,
|
|
252
|
+
attempt: 1,
|
|
253
|
+
runtime,
|
|
254
|
+
signal: controller.signal
|
|
255
|
+
})),
|
|
256
|
+
sleep: (ms, opts) => durable("sleep", opts?.id ?? `sleep:${ms}`, void 0, { ms }, opts?.id === void 0),
|
|
257
|
+
sleepUntil: (timestamp, opts) => durable("sleep", opts?.id ?? `sleepUntil:${timestamp}`, void 0, { timestamp }, opts?.id === void 0),
|
|
258
|
+
waitForEvent: (name, opts) => durable("waitForEvent", opts?.id ?? `event:${name}`, void 0, { name }, opts?.id === void 0),
|
|
259
|
+
approve: (opts) => durable("approve", opts.id ?? `approve:${opts.title}`, void 0, {
|
|
260
|
+
title: opts.title,
|
|
261
|
+
...opts.description === void 0 ? {} : { description: opts.description }
|
|
262
|
+
}, opts.id === void 0),
|
|
263
|
+
now: (opts) => durable("now", opts?.id ?? "now", async () => Date.now(), void 0, opts?.id === void 0),
|
|
264
|
+
uuid: (opts) => durable("uuid", opts?.id ?? "uuid", async () => crypto.randomUUID(), void 0, opts?.id === void 0),
|
|
265
|
+
emit: (name, value) => {
|
|
266
|
+
emitted.push({
|
|
267
|
+
name,
|
|
268
|
+
value
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
let outcome;
|
|
273
|
+
throughMiddleware(workflow.middlewares ?? [], ctx, workflow.handler).then((output) => {
|
|
274
|
+
outcome = {
|
|
275
|
+
status: "completed",
|
|
276
|
+
output: output ?? null
|
|
277
|
+
};
|
|
278
|
+
}, (error) => {
|
|
279
|
+
outcome = {
|
|
280
|
+
status: "failed",
|
|
281
|
+
error: describe(error)
|
|
282
|
+
};
|
|
283
|
+
});
|
|
284
|
+
const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
|
|
285
|
+
for (;;) {
|
|
286
|
+
for (let tick = 0; tick < 20; tick++) await new Promise((resolve) => setTimeout(resolve, 0));
|
|
287
|
+
if (outcome || nonDeterminism) break;
|
|
288
|
+
if (inflight.length > 0) {
|
|
289
|
+
await Promise.all(inflight.splice(0));
|
|
290
|
+
lastProgress = Date.now();
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (pending.length > 0 || Date.now() - lastProgress >= settleMs) break;
|
|
294
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
295
|
+
}
|
|
296
|
+
while (inflight.length > 0) await Promise.all(inflight.splice(0));
|
|
297
|
+
const memo = [...byKey.values(), ...settled.values()];
|
|
298
|
+
const orphan = [...byKey.keys()].find((key) => !consumed.has(key));
|
|
299
|
+
pending.sort((a, b) => a.seq - b.seq);
|
|
300
|
+
results.sort((a, b) => a.seq - b.seq);
|
|
301
|
+
const base = {
|
|
302
|
+
memo,
|
|
303
|
+
results,
|
|
304
|
+
emitted
|
|
305
|
+
};
|
|
306
|
+
if (nonDeterminism) return {
|
|
307
|
+
...base,
|
|
308
|
+
status: "failed",
|
|
309
|
+
steps: [],
|
|
310
|
+
error: `non-deterministic replay: ${nonDeterminism}`
|
|
311
|
+
};
|
|
312
|
+
if (orphan !== void 0) return {
|
|
313
|
+
...base,
|
|
314
|
+
status: "failed",
|
|
315
|
+
steps: [],
|
|
316
|
+
error: `stale memo: no operation matched "${orphan}"`
|
|
317
|
+
};
|
|
318
|
+
if (outcome?.status === "completed") return {
|
|
319
|
+
...base,
|
|
320
|
+
status: "completed",
|
|
321
|
+
steps: [],
|
|
322
|
+
output: outcome.output
|
|
323
|
+
};
|
|
324
|
+
if (outcome?.status === "failed") return {
|
|
325
|
+
...base,
|
|
326
|
+
status: "failed",
|
|
327
|
+
steps: [],
|
|
328
|
+
error: outcome.error
|
|
329
|
+
};
|
|
330
|
+
if (pending.length > 0) return {
|
|
331
|
+
...base,
|
|
332
|
+
status: "pending",
|
|
333
|
+
steps: pending
|
|
334
|
+
};
|
|
335
|
+
return {
|
|
336
|
+
...base,
|
|
337
|
+
status: "failed",
|
|
338
|
+
steps: [],
|
|
339
|
+
error: `workflow stalled: no durable operation and nothing settled for ${settleMs}ms`
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function noop() {}
|
|
343
|
+
//#endregion
|
|
344
|
+
//#region src/stacks/tanstack/steps.ts
|
|
345
|
+
function json(status, body) {
|
|
346
|
+
return new Response(JSON.stringify(body), {
|
|
347
|
+
status,
|
|
348
|
+
headers: { "content-type": "application/json; charset=utf-8" }
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
function resolveWorkflowId(ctx, param) {
|
|
352
|
+
const fromParams = ctx.params?.[param];
|
|
353
|
+
if (fromParams) return fromParams;
|
|
354
|
+
return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-2);
|
|
355
|
+
}
|
|
356
|
+
function isMemoEntry(value) {
|
|
357
|
+
const entry = value;
|
|
358
|
+
return typeof entry === "object" && entry !== null && Number.isInteger(entry.seq) && entry.seq >= 0 && typeof entry.stepId === "string" && Number.isInteger(entry.occurrence) && entry.occurrence >= 0 && (entry.status === "completed" || entry.status === "failed");
|
|
359
|
+
}
|
|
360
|
+
function parseBody(value) {
|
|
361
|
+
if (value === null || typeof value !== "object") return "body must be a JSON object";
|
|
362
|
+
const body = value;
|
|
363
|
+
if (body.memo !== void 0) {
|
|
364
|
+
if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
|
|
365
|
+
if (new Set(body.memo.map((entry) => memoKey(entry.stepId, entry.occurrence))).size !== body.memo.length) return "memo entries must be unique per stepId and occurrence";
|
|
366
|
+
}
|
|
367
|
+
if (body.steps !== void 0 && (!Array.isArray(body.steps) || !body.steps.every(isSelector))) return "steps must be an array of { stepId, occurrence? } selectors";
|
|
368
|
+
if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
|
|
369
|
+
return body;
|
|
370
|
+
}
|
|
371
|
+
async function readBody(request) {
|
|
372
|
+
const text = await request.text();
|
|
373
|
+
if (!text.trim()) return {};
|
|
374
|
+
return JSON.parse(text);
|
|
375
|
+
}
|
|
376
|
+
function selectorKey(selector) {
|
|
377
|
+
return memoKey(selector.stepId, selector.occurrence ?? 0);
|
|
378
|
+
}
|
|
379
|
+
function isSelector(value) {
|
|
380
|
+
const selector = value;
|
|
381
|
+
return typeof selector === "object" && selector !== null && typeof selector.stepId === "string" && (selector.occurrence === void 0 || Number.isInteger(selector.occurrence) && selector.occurrence >= 0);
|
|
382
|
+
}
|
|
383
|
+
function respond(runId, inputHash, outcome) {
|
|
384
|
+
const { status, memo, steps, results, emitted, output, error } = outcome;
|
|
385
|
+
return json(200, {
|
|
386
|
+
runId,
|
|
387
|
+
inputHash,
|
|
388
|
+
status,
|
|
389
|
+
memo,
|
|
390
|
+
steps,
|
|
391
|
+
results,
|
|
392
|
+
...emitted.length > 0 ? { emitted } : {},
|
|
393
|
+
...output === void 0 ? {} : { output },
|
|
394
|
+
...error === void 0 ? {} : { error }
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
function prepare(collection, options) {
|
|
398
|
+
return {
|
|
399
|
+
param: options.workflowIdParam ?? "workflowId",
|
|
400
|
+
byId: new Map(collection.workflows.map((workflow) => [workflow.id, workflow]))
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
async function resolve(ctx, param, byId) {
|
|
404
|
+
const workflowId = resolveWorkflowId(ctx, param);
|
|
405
|
+
const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
|
|
406
|
+
if (!workflow) return json(404, {
|
|
407
|
+
error: "unknown_workflow",
|
|
408
|
+
workflowId: workflowId ?? ""
|
|
409
|
+
});
|
|
410
|
+
let raw;
|
|
411
|
+
try {
|
|
412
|
+
raw = await readBody(ctx.request);
|
|
413
|
+
} catch (error) {
|
|
414
|
+
return json(400, {
|
|
415
|
+
error: "invalid_request",
|
|
416
|
+
message: `body is not valid JSON: ${String(error)}`
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
const body = parseBody(raw);
|
|
420
|
+
if (typeof body === "string") return json(400, {
|
|
421
|
+
error: "invalid_request",
|
|
422
|
+
message: body
|
|
423
|
+
});
|
|
424
|
+
const inputHash = await hashInput(body.input ?? null);
|
|
425
|
+
if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) return json(400, {
|
|
426
|
+
error: "invalid_request",
|
|
427
|
+
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"
|
|
428
|
+
});
|
|
429
|
+
return {
|
|
430
|
+
workflow,
|
|
431
|
+
body,
|
|
432
|
+
runId: body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
|
|
433
|
+
inputHash
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
/** Report what a run is waiting on, running nothing. Pins ctx.now/ctx.uuid into
|
|
437
|
+
* `memo` so a later executeSteps replays the same values. */
|
|
438
|
+
function createNextStepsHandler(collection, options = {}) {
|
|
439
|
+
const { param, byId } = prepare(collection, options);
|
|
440
|
+
return async (ctx) => {
|
|
441
|
+
const resolved = await resolve(ctx, param, byId);
|
|
442
|
+
if (resolved instanceof Response) return resolved;
|
|
443
|
+
const { workflow, body, runId, inputHash } = resolved;
|
|
444
|
+
return respond(runId, inputHash, await replay({
|
|
445
|
+
workflow,
|
|
446
|
+
input: body.input ?? null,
|
|
447
|
+
memo: body.memo ?? [],
|
|
448
|
+
runId,
|
|
449
|
+
shouldExecute: (intent) => intent.kind !== "step"
|
|
450
|
+
}));
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
/** Run the requested steps; omitting `steps` runs whatever `nextSteps` would
|
|
454
|
+
* report, advancing the run one wave per call. */
|
|
455
|
+
function createExecuteStepsHandler(collection, options = {}) {
|
|
456
|
+
const { param, byId } = prepare(collection, options);
|
|
457
|
+
return async (ctx) => {
|
|
458
|
+
const resolved = await resolve(ctx, param, byId);
|
|
459
|
+
if (resolved instanceof Response) return resolved;
|
|
460
|
+
const { workflow, body, runId, inputHash } = resolved;
|
|
461
|
+
const input = body.input ?? null;
|
|
462
|
+
const memo = body.memo ?? [];
|
|
463
|
+
const wanted = body.steps && new Set(body.steps.map(selectorKey));
|
|
464
|
+
return respond(runId, inputHash, await replay({
|
|
465
|
+
workflow,
|
|
466
|
+
input,
|
|
467
|
+
memo,
|
|
468
|
+
runId,
|
|
469
|
+
shouldExecute: (intent, pass) => intent.kind !== "step" || (wanted ? wanted.has(selectorKey(intent)) : pass.stepsSettled === 0)
|
|
470
|
+
}));
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
//#endregion
|
|
474
|
+
//#region src/stacks/tanstack/run.ts
|
|
475
|
+
function event(type, fields) {
|
|
476
|
+
return {
|
|
477
|
+
type,
|
|
478
|
+
ts: Date.now(),
|
|
479
|
+
...fields
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
async function* drive(workflow, input, runId, initialMemo, inputHash) {
|
|
483
|
+
let memo = [...initialMemo];
|
|
484
|
+
yield event("RUN_STARTED", {
|
|
485
|
+
runId,
|
|
486
|
+
inputHash
|
|
487
|
+
});
|
|
488
|
+
for (;;) {
|
|
489
|
+
const queue = [];
|
|
490
|
+
let wake;
|
|
491
|
+
const emit = (next) => {
|
|
492
|
+
queue.push(next);
|
|
493
|
+
wake?.();
|
|
494
|
+
wake = void 0;
|
|
495
|
+
};
|
|
496
|
+
let settledPass;
|
|
497
|
+
let passError;
|
|
498
|
+
let finished = false;
|
|
499
|
+
const running = replay({
|
|
500
|
+
workflow,
|
|
501
|
+
input,
|
|
502
|
+
memo,
|
|
503
|
+
runId,
|
|
504
|
+
shouldExecute: (intent, state) => intent.kind !== "step" || state.stepsSettled === 0,
|
|
505
|
+
onStepStart: (intent) => {
|
|
506
|
+
if (intent.kind === "step") emit(event("STEP_STARTED", { stepId: intent.stepId }));
|
|
507
|
+
},
|
|
508
|
+
onStepSettle: (result) => {
|
|
509
|
+
if (result.kind !== "step") return;
|
|
510
|
+
emit(result.status === "completed" ? event("STEP_FINISHED", {
|
|
511
|
+
stepId: result.stepId,
|
|
512
|
+
result: result.result
|
|
513
|
+
}) : event("STEP_FAILED", {
|
|
514
|
+
stepId: result.stepId,
|
|
515
|
+
error: result.error
|
|
516
|
+
}));
|
|
517
|
+
}
|
|
518
|
+
}).then((value) => {
|
|
519
|
+
settledPass = value;
|
|
520
|
+
finished = true;
|
|
521
|
+
wake?.();
|
|
522
|
+
wake = void 0;
|
|
523
|
+
}, (error) => {
|
|
524
|
+
passError = error;
|
|
525
|
+
finished = true;
|
|
526
|
+
wake?.();
|
|
527
|
+
wake = void 0;
|
|
528
|
+
});
|
|
529
|
+
for (;;) {
|
|
530
|
+
if (queue.length > 0) {
|
|
531
|
+
yield queue.shift();
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
if (finished) break;
|
|
535
|
+
await new Promise((resolve) => {
|
|
536
|
+
wake = resolve;
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
await running;
|
|
540
|
+
if (!settledPass) {
|
|
541
|
+
yield event("RUN_ERRORED", {
|
|
542
|
+
runId,
|
|
543
|
+
inputHash,
|
|
544
|
+
error: `replay threw: ${passError instanceof Error ? passError.message : String(passError)}`,
|
|
545
|
+
memo
|
|
546
|
+
});
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
const pass = settledPass;
|
|
550
|
+
memo = pass.memo;
|
|
551
|
+
if (pass.status === "completed") {
|
|
552
|
+
yield event("RUN_FINISHED", {
|
|
553
|
+
runId,
|
|
554
|
+
inputHash,
|
|
555
|
+
output: pass.output,
|
|
556
|
+
memo
|
|
557
|
+
});
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
if (pass.status === "failed") {
|
|
561
|
+
yield event("RUN_ERRORED", {
|
|
562
|
+
runId,
|
|
563
|
+
inputHash,
|
|
564
|
+
error: pass.error,
|
|
565
|
+
memo
|
|
566
|
+
});
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
if (pass.steps.every((intent) => intent.kind !== "step")) {
|
|
570
|
+
yield event("RUN_PAUSED", {
|
|
571
|
+
runId,
|
|
572
|
+
inputHash,
|
|
573
|
+
waitingOn: pass.steps,
|
|
574
|
+
memo
|
|
575
|
+
});
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
if (pass.results.length === 0) {
|
|
579
|
+
yield event("RUN_ERRORED", {
|
|
580
|
+
runId,
|
|
581
|
+
inputHash,
|
|
582
|
+
error: "run made no progress",
|
|
583
|
+
memo
|
|
584
|
+
});
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
function createRunHandler(collection, options = {}) {
|
|
590
|
+
const param = options.workflowIdParam ?? "workflowId";
|
|
591
|
+
const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
|
|
592
|
+
return async (ctx) => {
|
|
593
|
+
const workflowId = ctx.params?.[param] ?? new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
|
|
594
|
+
const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
|
|
595
|
+
if (!workflow) return new Response(JSON.stringify({
|
|
596
|
+
error: "unknown_workflow",
|
|
597
|
+
workflowId: workflowId ?? ""
|
|
598
|
+
}), {
|
|
599
|
+
status: 404,
|
|
600
|
+
headers: { "content-type": "application/json; charset=utf-8" }
|
|
601
|
+
});
|
|
602
|
+
let body = {};
|
|
603
|
+
try {
|
|
604
|
+
const text = await ctx.request.text();
|
|
605
|
+
if (text.trim()) body = JSON.parse(text);
|
|
606
|
+
} catch (error) {
|
|
607
|
+
return new Response(JSON.stringify({
|
|
608
|
+
error: "invalid_request",
|
|
609
|
+
message: String(error)
|
|
610
|
+
}), {
|
|
611
|
+
status: 400,
|
|
612
|
+
headers: { "content-type": "application/json; charset=utf-8" }
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
const inputHash = await hashInput(body.input ?? null);
|
|
616
|
+
if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) {
|
|
617
|
+
const 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";
|
|
618
|
+
return new Response(JSON.stringify({
|
|
619
|
+
error: "invalid_request",
|
|
620
|
+
message
|
|
621
|
+
}), {
|
|
622
|
+
status: 400,
|
|
623
|
+
headers: { "content-type": "application/json; charset=utf-8" }
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
const runId = body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
|
627
|
+
return toServerSentEventsResponse(drive(workflow, body.input ?? null, runId, body.memo ?? [], inputHash));
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
//#endregion
|
|
631
|
+
export { createExecuteStepsHandler, createMiddleware, createNextStepsHandler, createRunHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
|