@upstash/workflow 0.2.12 → 0.2.13

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/express.js CHANGED
@@ -23710,11 +23710,12 @@ var WORKFLOW_PROTOCOL_VERSION_HEADER = "Upstash-Workflow-Sdk-Version";
23710
23710
  var DEFAULT_CONTENT_TYPE = "application/json";
23711
23711
  var NO_CONCURRENCY = 1;
23712
23712
  var DEFAULT_RETRIES = 3;
23713
- var VERSION = "v0.2.7";
23713
+ var VERSION = "v0.2.13";
23714
23714
  var SDK_TELEMETRY = `@upstash/workflow@${VERSION}`;
23715
23715
  var TELEMETRY_HEADER_SDK = "Upstash-Telemetry-Sdk";
23716
23716
  var TELEMETRY_HEADER_FRAMEWORK = "Upstash-Telemetry-Framework";
23717
23717
  var TELEMETRY_HEADER_RUNTIME = "Upstash-Telemetry-Runtime";
23718
+ var TELEMETRY_HEADER_AGENT = "Upstash-Telemetry-Agent";
23718
23719
 
23719
23720
  // src/client/utils.ts
23720
23721
  var import_qstash = require("@upstash/qstash");
@@ -23810,6 +23811,12 @@ var formatWorkflowError = (error) => {
23810
23811
  };
23811
23812
  };
23812
23813
 
23814
+ // src/context/auto-executor.ts
23815
+ var import_qstash5 = require("@upstash/qstash");
23816
+
23817
+ // src/qstash/headers.ts
23818
+ var import_qstash4 = require("@upstash/qstash");
23819
+
23813
23820
  // src/utils.ts
23814
23821
  var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
23815
23822
  var NANOID_LENGTH = 21;
@@ -23835,574 +23842,231 @@ function decodeBase64(base64) {
23835
23842
  }
23836
23843
  }
23837
23844
 
23838
- // src/context/steps.ts
23839
- var BaseLazyStep = class _BaseLazyStep {
23840
- stepName;
23841
- constructor(stepName) {
23842
- if (!stepName) {
23843
- throw new WorkflowError(
23844
- "A workflow step name cannot be undefined or an empty string. Please provide a name for your workflow step."
23845
- );
23846
- }
23847
- this.stepName = stepName;
23845
+ // node_modules/neverthrow/dist/index.es.js
23846
+ var defaultErrorConfig = {
23847
+ withStackTrace: false
23848
+ };
23849
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
23850
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
23851
+ const maybeStack = config.withStackTrace ? new Error().stack : void 0;
23852
+ return {
23853
+ data,
23854
+ message,
23855
+ stack: maybeStack
23856
+ };
23857
+ };
23858
+ function __awaiter(thisArg, _arguments, P, generator) {
23859
+ function adopt(value) {
23860
+ return value instanceof P ? value : new P(function(resolve) {
23861
+ resolve(value);
23862
+ });
23848
23863
  }
23849
- /**
23850
- * parse the out field of a step result.
23851
- *
23852
- * will be called when returning the steps to the context from auto executor
23853
- *
23854
- * @param out field of the step
23855
- * @returns parsed out field
23856
- */
23857
- parseOut(out) {
23858
- if (out === void 0) {
23859
- if (this.allowUndefinedOut) {
23860
- return void 0;
23861
- } else {
23862
- throw new WorkflowError(
23863
- `Error while parsing output of ${this.stepType} step. Expected a string, but got: undefined`
23864
- );
23864
+ return new (P || (P = Promise))(function(resolve, reject) {
23865
+ function fulfilled(value) {
23866
+ try {
23867
+ step(generator.next(value));
23868
+ } catch (e) {
23869
+ reject(e);
23865
23870
  }
23866
23871
  }
23867
- if (typeof out === "object") {
23868
- if (this.stepType !== "Wait") {
23869
- console.warn(
23870
- `Error while parsing ${this.stepType} step output. Expected a string, but got object. Please reach out to Upstash Support.`
23871
- );
23872
- return out;
23872
+ function rejected(value) {
23873
+ try {
23874
+ step(generator["throw"](value));
23875
+ } catch (e) {
23876
+ reject(e);
23873
23877
  }
23874
- return {
23875
- ...out,
23876
- eventData: _BaseLazyStep.tryParsing(out.eventData)
23877
- };
23878
23878
  }
23879
- if (typeof out !== "string") {
23880
- throw new WorkflowError(
23881
- `Error while parsing output of ${this.stepType} step. Expected a string or undefined, but got: ${typeof out}`
23882
- );
23879
+ function step(result) {
23880
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
23883
23881
  }
23884
- return this.safeParseOut(out);
23885
- }
23886
- safeParseOut(out) {
23887
- return _BaseLazyStep.tryParsing(out);
23882
+ step((generator = generator.apply(thisArg, [])).next());
23883
+ });
23884
+ }
23885
+ function __values(o) {
23886
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
23887
+ if (m) return m.call(o);
23888
+ if (o && typeof o.length === "number") return {
23889
+ next: function() {
23890
+ if (o && i >= o.length) o = void 0;
23891
+ return { value: o && o[i++], done: !o };
23892
+ }
23893
+ };
23894
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
23895
+ }
23896
+ function __await(v) {
23897
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
23898
+ }
23899
+ function __asyncGenerator(thisArg, _arguments, generator) {
23900
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
23901
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
23902
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
23903
+ return this;
23904
+ }, i;
23905
+ function verb(n) {
23906
+ if (g[n]) i[n] = function(v) {
23907
+ return new Promise(function(a, b) {
23908
+ q.push([n, v, a, b]) > 1 || resume(n, v);
23909
+ });
23910
+ };
23888
23911
  }
23889
- static tryParsing(stepOut) {
23912
+ function resume(n, v) {
23890
23913
  try {
23891
- return JSON.parse(stepOut);
23892
- } catch {
23893
- return stepOut;
23914
+ step(g[n](v));
23915
+ } catch (e) {
23916
+ settle(q[0][3], e);
23894
23917
  }
23895
23918
  }
23896
- };
23897
- var LazyFunctionStep = class extends BaseLazyStep {
23898
- stepFunction;
23899
- stepType = "Run";
23900
- allowUndefinedOut = true;
23901
- constructor(stepName, stepFunction) {
23902
- super(stepName);
23903
- this.stepFunction = stepFunction;
23919
+ function step(r) {
23920
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
23904
23921
  }
23905
- getPlanStep(concurrent, targetStep) {
23906
- return {
23907
- stepId: 0,
23908
- stepName: this.stepName,
23909
- stepType: this.stepType,
23910
- concurrent,
23911
- targetStep
23912
- };
23922
+ function fulfill(value) {
23923
+ resume("next", value);
23913
23924
  }
23914
- async getResultStep(concurrent, stepId) {
23915
- let result = this.stepFunction();
23916
- if (result instanceof Promise) {
23917
- result = await result;
23918
- }
23919
- return {
23920
- stepId,
23921
- stepName: this.stepName,
23922
- stepType: this.stepType,
23923
- out: result,
23924
- concurrent
23925
- };
23925
+ function reject(value) {
23926
+ resume("throw", value);
23926
23927
  }
23927
- };
23928
- var LazySleepStep = class extends BaseLazyStep {
23929
- sleep;
23930
- stepType = "SleepFor";
23931
- allowUndefinedOut = true;
23932
- constructor(stepName, sleep) {
23933
- super(stepName);
23934
- this.sleep = sleep;
23928
+ function settle(f, v) {
23929
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
23935
23930
  }
23936
- getPlanStep(concurrent, targetStep) {
23937
- return {
23938
- stepId: 0,
23939
- stepName: this.stepName,
23940
- stepType: this.stepType,
23941
- sleepFor: this.sleep,
23942
- concurrent,
23943
- targetStep
23931
+ }
23932
+ function __asyncDelegator(o) {
23933
+ var i, p;
23934
+ return i = {}, verb("next"), verb("throw", function(e) {
23935
+ throw e;
23936
+ }), verb("return"), i[Symbol.iterator] = function() {
23937
+ return this;
23938
+ }, i;
23939
+ function verb(n, f) {
23940
+ i[n] = o[n] ? function(v) {
23941
+ return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
23942
+ } : f;
23943
+ }
23944
+ }
23945
+ function __asyncValues(o) {
23946
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
23947
+ var m = o[Symbol.asyncIterator], i;
23948
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
23949
+ return this;
23950
+ }, i);
23951
+ function verb(n) {
23952
+ i[n] = o[n] && function(v) {
23953
+ return new Promise(function(resolve, reject) {
23954
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
23955
+ });
23944
23956
  };
23945
23957
  }
23946
- async getResultStep(concurrent, stepId) {
23947
- return await Promise.resolve({
23948
- stepId,
23949
- stepName: this.stepName,
23950
- stepType: this.stepType,
23951
- sleepFor: this.sleep,
23952
- concurrent
23953
- });
23958
+ function settle(resolve, reject, d, v) {
23959
+ Promise.resolve(v).then(function(v2) {
23960
+ resolve({ value: v2, done: d });
23961
+ }, reject);
23954
23962
  }
23955
- };
23956
- var LazySleepUntilStep = class extends BaseLazyStep {
23957
- sleepUntil;
23958
- stepType = "SleepUntil";
23959
- allowUndefinedOut = true;
23960
- constructor(stepName, sleepUntil) {
23961
- super(stepName);
23962
- this.sleepUntil = sleepUntil;
23963
+ }
23964
+ var ResultAsync = class _ResultAsync {
23965
+ constructor(res) {
23966
+ this._promise = res;
23963
23967
  }
23964
- getPlanStep(concurrent, targetStep) {
23965
- return {
23966
- stepId: 0,
23967
- stepName: this.stepName,
23968
- stepType: this.stepType,
23969
- sleepUntil: this.sleepUntil,
23970
- concurrent,
23971
- targetStep
23972
- };
23968
+ static fromSafePromise(promise) {
23969
+ const newPromise = promise.then((value) => new Ok(value));
23970
+ return new _ResultAsync(newPromise);
23973
23971
  }
23974
- async getResultStep(concurrent, stepId) {
23975
- return await Promise.resolve({
23976
- stepId,
23977
- stepName: this.stepName,
23978
- stepType: this.stepType,
23979
- sleepUntil: this.sleepUntil,
23980
- concurrent
23981
- });
23972
+ static fromPromise(promise, errorFn) {
23973
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
23974
+ return new _ResultAsync(newPromise);
23982
23975
  }
23983
- safeParseOut() {
23984
- return void 0;
23976
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
23977
+ static fromThrowable(fn, errorFn) {
23978
+ return (...args) => {
23979
+ return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
23980
+ try {
23981
+ return new Ok(yield fn(...args));
23982
+ } catch (error) {
23983
+ return new Err(errorFn ? errorFn(error) : error);
23984
+ }
23985
+ }))());
23986
+ };
23985
23987
  }
23986
- };
23987
- var LazyCallStep = class _LazyCallStep extends BaseLazyStep {
23988
- url;
23989
- method;
23990
- body;
23991
- headers;
23992
- retries;
23993
- timeout;
23994
- flowControl;
23995
- stepType = "Call";
23996
- allowUndefinedOut = false;
23997
- constructor(stepName, url, method, body, headers, retries, timeout, flowControl) {
23998
- super(stepName);
23999
- this.url = url;
24000
- this.method = method;
24001
- this.body = body;
24002
- this.headers = headers;
24003
- this.retries = retries;
24004
- this.timeout = timeout;
24005
- this.flowControl = flowControl;
24006
- }
24007
- getPlanStep(concurrent, targetStep) {
24008
- return {
24009
- stepId: 0,
24010
- stepName: this.stepName,
24011
- stepType: this.stepType,
24012
- concurrent,
24013
- targetStep
24014
- };
23988
+ static combine(asyncResultList) {
23989
+ return combineResultAsyncList(asyncResultList);
24015
23990
  }
24016
- async getResultStep(concurrent, stepId) {
24017
- return await Promise.resolve({
24018
- stepId,
24019
- stepName: this.stepName,
24020
- stepType: this.stepType,
24021
- concurrent,
24022
- callUrl: this.url,
24023
- callMethod: this.method,
24024
- callBody: this.body,
24025
- callHeaders: this.headers
24026
- });
23991
+ static combineWithAllErrors(asyncResultList) {
23992
+ return combineResultAsyncListWithAllErrors(asyncResultList);
24027
23993
  }
24028
- safeParseOut(out) {
24029
- const { header, status, body } = JSON.parse(out);
24030
- const responseHeaders = new Headers(header);
24031
- if (_LazyCallStep.isText(responseHeaders.get("content-type"))) {
24032
- const bytes = new Uint8Array(out.length);
24033
- for (let i = 0; i < out.length; i++) {
24034
- bytes[i] = out.charCodeAt(i);
23994
+ map(f) {
23995
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
23996
+ if (res.isErr()) {
23997
+ return new Err(res.error);
24035
23998
  }
24036
- const processedResult = new TextDecoder().decode(bytes);
24037
- const newBody = JSON.parse(processedResult).body;
24038
- return {
24039
- status,
24040
- header,
24041
- body: BaseLazyStep.tryParsing(newBody)
24042
- };
24043
- } else {
24044
- return { header, status, body };
24045
- }
24046
- }
24047
- static applicationHeaders = /* @__PURE__ */ new Set([
24048
- "application/json",
24049
- "application/xml",
24050
- "application/javascript",
24051
- "application/x-www-form-urlencoded",
24052
- "application/xhtml+xml",
24053
- "application/ld+json",
24054
- "application/rss+xml",
24055
- "application/atom+xml"
24056
- ]);
24057
- static isText = (contentTypeHeader) => {
24058
- if (!contentTypeHeader) {
24059
- return false;
24060
- }
24061
- if (_LazyCallStep.applicationHeaders.has(contentTypeHeader)) {
24062
- return true;
24063
- }
24064
- if (contentTypeHeader.startsWith("text/")) {
24065
- return true;
24066
- }
24067
- return false;
24068
- };
24069
- };
24070
- var LazyWaitForEventStep = class extends BaseLazyStep {
24071
- eventId;
24072
- timeout;
24073
- stepType = "Wait";
24074
- allowUndefinedOut = false;
24075
- constructor(stepName, eventId, timeout) {
24076
- super(stepName);
24077
- this.eventId = eventId;
24078
- this.timeout = timeout;
23999
+ return new Ok(yield f(res.value));
24000
+ })));
24079
24001
  }
24080
- getPlanStep(concurrent, targetStep) {
24081
- return {
24082
- stepId: 0,
24083
- stepName: this.stepName,
24084
- stepType: this.stepType,
24085
- waitEventId: this.eventId,
24086
- timeout: this.timeout,
24087
- concurrent,
24088
- targetStep
24089
- };
24002
+ andThrough(f) {
24003
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
24004
+ if (res.isErr()) {
24005
+ return new Err(res.error);
24006
+ }
24007
+ const newRes = yield f(res.value);
24008
+ if (newRes.isErr()) {
24009
+ return new Err(newRes.error);
24010
+ }
24011
+ return new Ok(res.value);
24012
+ })));
24090
24013
  }
24091
- async getResultStep(concurrent, stepId) {
24092
- return await Promise.resolve({
24093
- stepId,
24094
- stepName: this.stepName,
24095
- stepType: this.stepType,
24096
- waitEventId: this.eventId,
24097
- timeout: this.timeout,
24098
- concurrent
24099
- });
24014
+ andTee(f) {
24015
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
24016
+ if (res.isErr()) {
24017
+ return new Err(res.error);
24018
+ }
24019
+ try {
24020
+ yield f(res.value);
24021
+ } catch (e) {
24022
+ }
24023
+ return new Ok(res.value);
24024
+ })));
24100
24025
  }
24101
- safeParseOut(out) {
24102
- const result = JSON.parse(out);
24103
- return {
24104
- ...result,
24105
- eventData: BaseLazyStep.tryParsing(result.eventData)
24106
- };
24026
+ mapErr(f) {
24027
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
24028
+ if (res.isOk()) {
24029
+ return new Ok(res.value);
24030
+ }
24031
+ return new Err(yield f(res.error));
24032
+ })));
24107
24033
  }
24108
- };
24109
- var LazyNotifyStep = class extends LazyFunctionStep {
24110
- stepType = "Notify";
24111
- constructor(stepName, eventId, eventData, requester) {
24112
- super(stepName, async () => {
24113
- const notifyResponse = await makeNotifyRequest(requester, eventId, eventData);
24114
- return {
24115
- eventId,
24116
- eventData,
24117
- notifyResponse
24118
- };
24119
- });
24034
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
24035
+ andThen(f) {
24036
+ return new _ResultAsync(this._promise.then((res) => {
24037
+ if (res.isErr()) {
24038
+ return new Err(res.error);
24039
+ }
24040
+ const newValue = f(res.value);
24041
+ return newValue instanceof _ResultAsync ? newValue._promise : newValue;
24042
+ }));
24120
24043
  }
24121
- safeParseOut(out) {
24122
- const result = JSON.parse(out);
24123
- return {
24124
- ...result,
24125
- eventData: BaseLazyStep.tryParsing(result.eventData)
24126
- };
24044
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
24045
+ orElse(f) {
24046
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
24047
+ if (res.isErr()) {
24048
+ return f(res.error);
24049
+ }
24050
+ return new Ok(res.value);
24051
+ })));
24127
24052
  }
24128
- };
24129
- var LazyInvokeStep = class extends BaseLazyStep {
24130
- stepType = "Invoke";
24131
- params;
24132
- allowUndefinedOut = false;
24133
- constructor(stepName, {
24134
- workflow,
24135
- body,
24136
- headers = {},
24137
- workflowRunId,
24138
- retries,
24139
- flowControl
24140
- }) {
24141
- super(stepName);
24142
- this.params = {
24143
- workflow,
24144
- body,
24145
- headers,
24146
- workflowRunId: getWorkflowRunId(workflowRunId),
24147
- retries,
24148
- flowControl
24149
- };
24053
+ match(ok2, _err) {
24054
+ return this._promise.then((res) => res.match(ok2, _err));
24150
24055
  }
24151
- getPlanStep(concurrent, targetStep) {
24152
- return {
24153
- stepId: 0,
24154
- stepName: this.stepName,
24155
- stepType: this.stepType,
24156
- concurrent,
24157
- targetStep
24158
- };
24056
+ unwrapOr(t) {
24057
+ return this._promise.then((res) => res.unwrapOr(t));
24159
24058
  }
24160
24059
  /**
24161
- * won't be used as it's the server who will add the result step
24162
- * in Invoke step.
24060
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
24163
24061
  */
24164
- getResultStep(concurrent, stepId) {
24165
- return Promise.resolve({
24166
- stepId,
24167
- stepName: this.stepName,
24168
- stepType: this.stepType,
24169
- concurrent
24062
+ safeUnwrap() {
24063
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
24064
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
24170
24065
  });
24171
24066
  }
24172
- safeParseOut(out) {
24173
- const result = JSON.parse(out);
24174
- return {
24175
- ...result,
24176
- body: BaseLazyStep.tryParsing(result.body)
24177
- };
24178
- }
24179
- };
24180
-
24181
- // node_modules/neverthrow/dist/index.es.js
24182
- var defaultErrorConfig = {
24183
- withStackTrace: false
24184
- };
24185
- var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
24186
- const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
24187
- const maybeStack = config.withStackTrace ? new Error().stack : void 0;
24188
- return {
24189
- data,
24190
- message,
24191
- stack: maybeStack
24192
- };
24193
- };
24194
- function __awaiter(thisArg, _arguments, P, generator) {
24195
- function adopt(value) {
24196
- return value instanceof P ? value : new P(function(resolve) {
24197
- resolve(value);
24198
- });
24199
- }
24200
- return new (P || (P = Promise))(function(resolve, reject) {
24201
- function fulfilled(value) {
24202
- try {
24203
- step(generator.next(value));
24204
- } catch (e) {
24205
- reject(e);
24206
- }
24207
- }
24208
- function rejected(value) {
24209
- try {
24210
- step(generator["throw"](value));
24211
- } catch (e) {
24212
- reject(e);
24213
- }
24214
- }
24215
- function step(result) {
24216
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
24217
- }
24218
- step((generator = generator.apply(thisArg, [])).next());
24219
- });
24220
- }
24221
- function __values(o) {
24222
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
24223
- if (m) return m.call(o);
24224
- if (o && typeof o.length === "number") return {
24225
- next: function() {
24226
- if (o && i >= o.length) o = void 0;
24227
- return { value: o && o[i++], done: !o };
24228
- }
24229
- };
24230
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
24231
- }
24232
- function __await(v) {
24233
- return this instanceof __await ? (this.v = v, this) : new __await(v);
24234
- }
24235
- function __asyncGenerator(thisArg, _arguments, generator) {
24236
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
24237
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
24238
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
24239
- return this;
24240
- }, i;
24241
- function verb(n) {
24242
- if (g[n]) i[n] = function(v) {
24243
- return new Promise(function(a, b) {
24244
- q.push([n, v, a, b]) > 1 || resume(n, v);
24245
- });
24246
- };
24247
- }
24248
- function resume(n, v) {
24249
- try {
24250
- step(g[n](v));
24251
- } catch (e) {
24252
- settle(q[0][3], e);
24253
- }
24254
- }
24255
- function step(r) {
24256
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
24257
- }
24258
- function fulfill(value) {
24259
- resume("next", value);
24260
- }
24261
- function reject(value) {
24262
- resume("throw", value);
24263
- }
24264
- function settle(f, v) {
24265
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
24266
- }
24267
- }
24268
- function __asyncDelegator(o) {
24269
- var i, p;
24270
- return i = {}, verb("next"), verb("throw", function(e) {
24271
- throw e;
24272
- }), verb("return"), i[Symbol.iterator] = function() {
24273
- return this;
24274
- }, i;
24275
- function verb(n, f) {
24276
- i[n] = o[n] ? function(v) {
24277
- return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
24278
- } : f;
24279
- }
24280
- }
24281
- function __asyncValues(o) {
24282
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
24283
- var m = o[Symbol.asyncIterator], i;
24284
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
24285
- return this;
24286
- }, i);
24287
- function verb(n) {
24288
- i[n] = o[n] && function(v) {
24289
- return new Promise(function(resolve, reject) {
24290
- v = o[n](v), settle(resolve, reject, v.done, v.value);
24291
- });
24292
- };
24293
- }
24294
- function settle(resolve, reject, d, v) {
24295
- Promise.resolve(v).then(function(v2) {
24296
- resolve({ value: v2, done: d });
24297
- }, reject);
24298
- }
24299
- }
24300
- var ResultAsync = class _ResultAsync {
24301
- constructor(res) {
24302
- this._promise = res;
24303
- }
24304
- static fromSafePromise(promise) {
24305
- const newPromise = promise.then((value) => new Ok(value));
24306
- return new _ResultAsync(newPromise);
24307
- }
24308
- static fromPromise(promise, errorFn) {
24309
- const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
24310
- return new _ResultAsync(newPromise);
24311
- }
24312
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
24313
- static fromThrowable(fn, errorFn) {
24314
- return (...args) => {
24315
- return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
24316
- try {
24317
- return new Ok(yield fn(...args));
24318
- } catch (error) {
24319
- return new Err(errorFn ? errorFn(error) : error);
24320
- }
24321
- }))());
24322
- };
24323
- }
24324
- static combine(asyncResultList) {
24325
- return combineResultAsyncList(asyncResultList);
24326
- }
24327
- static combineWithAllErrors(asyncResultList) {
24328
- return combineResultAsyncListWithAllErrors(asyncResultList);
24329
- }
24330
- map(f) {
24331
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
24332
- if (res.isErr()) {
24333
- return new Err(res.error);
24334
- }
24335
- return new Ok(yield f(res.value));
24336
- })));
24337
- }
24338
- andThrough(f) {
24339
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
24340
- if (res.isErr()) {
24341
- return new Err(res.error);
24342
- }
24343
- const newRes = yield f(res.value);
24344
- if (newRes.isErr()) {
24345
- return new Err(newRes.error);
24346
- }
24347
- return new Ok(res.value);
24348
- })));
24349
- }
24350
- andTee(f) {
24351
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
24352
- if (res.isErr()) {
24353
- return new Err(res.error);
24354
- }
24355
- try {
24356
- yield f(res.value);
24357
- } catch (e) {
24358
- }
24359
- return new Ok(res.value);
24360
- })));
24361
- }
24362
- mapErr(f) {
24363
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
24364
- if (res.isOk()) {
24365
- return new Ok(res.value);
24366
- }
24367
- return new Err(yield f(res.error));
24368
- })));
24369
- }
24370
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
24371
- andThen(f) {
24372
- return new _ResultAsync(this._promise.then((res) => {
24373
- if (res.isErr()) {
24374
- return new Err(res.error);
24375
- }
24376
- const newValue = f(res.value);
24377
- return newValue instanceof _ResultAsync ? newValue._promise : newValue;
24378
- }));
24379
- }
24380
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
24381
- orElse(f) {
24382
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
24383
- if (res.isErr()) {
24384
- return f(res.error);
24385
- }
24386
- return new Ok(res.value);
24387
- })));
24388
- }
24389
- match(ok2, _err) {
24390
- return this._promise.then((res) => res.match(ok2, _err));
24391
- }
24392
- unwrapOr(t) {
24393
- return this._promise.then((res) => res.unwrapOr(t));
24394
- }
24395
- /**
24396
- * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
24397
- */
24398
- safeUnwrap() {
24399
- return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
24400
- return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
24401
- });
24402
- }
24403
- // Makes ResultAsync implement PromiseLike<Result>
24404
- then(successCallback, failureCallback) {
24405
- return this._promise.then(successCallback, failureCallback);
24067
+ // Makes ResultAsync implement PromiseLike<Result>
24068
+ then(successCallback, failureCallback) {
24069
+ return this._promise.then(successCallback, failureCallback);
24406
24070
  }
24407
24071
  };
24408
24072
  var errAsync = (err2) => new ResultAsync(Promise.resolve(new Err(err2)));
@@ -24612,18 +24276,22 @@ var triggerFirstInvocation = async ({
24612
24276
  useJSONContent,
24613
24277
  telemetry: telemetry2,
24614
24278
  debug,
24615
- invokeCount
24279
+ invokeCount,
24280
+ delay
24616
24281
  }) => {
24617
24282
  const { headers } = getHeaders({
24618
24283
  initHeaderValue: "true",
24619
- workflowRunId: workflowContext.workflowRunId,
24620
- workflowUrl: workflowContext.url,
24621
- userHeaders: workflowContext.headers,
24622
- failureUrl: workflowContext.failureUrl,
24623
- retries: workflowContext.retries,
24624
- telemetry: telemetry2,
24625
- invokeCount,
24626
- flowControl: workflowContext.flowControl
24284
+ workflowConfig: {
24285
+ workflowRunId: workflowContext.workflowRunId,
24286
+ workflowUrl: workflowContext.url,
24287
+ failureUrl: workflowContext.failureUrl,
24288
+ retries: workflowContext.retries,
24289
+ telemetry: telemetry2,
24290
+ flowControl: workflowContext.flowControl,
24291
+ useJSONContent: useJSONContent ?? false
24292
+ },
24293
+ invokeCount: invokeCount ?? 0,
24294
+ userHeaders: workflowContext.headers
24627
24295
  });
24628
24296
  if (workflowContext.headers.get("content-type")) {
24629
24297
  headers["content-type"] = workflowContext.headers.get("content-type");
@@ -24637,7 +24305,8 @@ var triggerFirstInvocation = async ({
24637
24305
  headers,
24638
24306
  method: "POST",
24639
24307
  body,
24640
- url: workflowContext.url
24308
+ url: workflowContext.url,
24309
+ delay
24641
24310
  });
24642
24311
  if (result.deduplicated) {
24643
24312
  await debug?.log("WARN", "SUBMIT_FIRST_INVOCATION", {
@@ -24793,14 +24462,16 @@ ${atob(callbackMessage.body ?? "")}`
24793
24462
  const userHeaders = recreateUserHeaders(request.headers);
24794
24463
  const { headers: requestHeaders } = getHeaders({
24795
24464
  initHeaderValue: "false",
24796
- workflowRunId,
24797
- workflowUrl,
24465
+ workflowConfig: {
24466
+ workflowRunId,
24467
+ workflowUrl,
24468
+ failureUrl,
24469
+ retries,
24470
+ telemetry: telemetry2,
24471
+ flowControl
24472
+ },
24798
24473
  userHeaders,
24799
- failureUrl,
24800
- retries,
24801
- telemetry: telemetry2,
24802
- invokeCount: Number(invokeCount),
24803
- flowControl
24474
+ invokeCount: Number(invokeCount)
24804
24475
  });
24805
24476
  const callResponse = {
24806
24477
  status: callbackMessage.status,
@@ -24832,343 +24503,913 @@ ${atob(callbackMessage.body ?? "")}`
24832
24503
  } else {
24833
24504
  return ok("continue-workflow");
24834
24505
  }
24835
- } catch (error) {
24836
- const isCallReturn = request.headers.get("Upstash-Workflow-Callback");
24837
- return err(
24838
- new WorkflowError(`Error when handling call return (isCallReturn=${isCallReturn}): ${error}`)
24839
- );
24840
- }
24841
- };
24842
- var getTelemetryHeaders = (telemetry2) => {
24843
- return {
24844
- [TELEMETRY_HEADER_SDK]: telemetry2.sdk,
24845
- [TELEMETRY_HEADER_FRAMEWORK]: telemetry2.framework,
24846
- [TELEMETRY_HEADER_RUNTIME]: telemetry2.runtime ?? "unknown"
24847
- };
24848
- };
24849
- var getHeaders = ({
24850
- initHeaderValue,
24851
- workflowRunId,
24852
- workflowUrl,
24853
- userHeaders,
24854
- failureUrl,
24855
- retries,
24856
- step,
24857
- callRetries,
24858
- callTimeout,
24859
- telemetry: telemetry2,
24860
- invokeCount,
24861
- flowControl,
24862
- callFlowControl
24863
- }) => {
24864
- const callHeaders = new Headers(step?.callHeaders);
24865
- const contentType = (callHeaders.get("content-type") ? callHeaders.get("content-type") : userHeaders?.get("Content-Type") ? userHeaders.get("Content-Type") : void 0) ?? DEFAULT_CONTENT_TYPE;
24866
- const baseHeaders = {
24867
- [WORKFLOW_INIT_HEADER]: initHeaderValue,
24868
- [WORKFLOW_ID_HEADER]: workflowRunId,
24869
- [WORKFLOW_URL_HEADER]: workflowUrl,
24870
- [WORKFLOW_FEATURE_HEADER]: "LazyFetch,InitialBody",
24871
- [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
24872
- "content-type": contentType,
24873
- ...telemetry2 ? getTelemetryHeaders(telemetry2) : {}
24874
- };
24875
- if (invokeCount !== void 0 && !step?.callUrl) {
24876
- baseHeaders[`Upstash-Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount.toString();
24877
- }
24878
- if (!step?.callUrl) {
24879
- baseHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] = WORKFLOW_PROTOCOL_VERSION;
24880
- }
24881
- if (callTimeout) {
24882
- baseHeaders[`Upstash-Timeout`] = callTimeout.toString();
24883
- }
24884
- if (failureUrl) {
24885
- baseHeaders[`Upstash-Failure-Callback-Forward-${WORKFLOW_FAILURE_HEADER}`] = "true";
24886
- baseHeaders[`Upstash-Failure-Callback-Forward-Upstash-Workflow-Failure-Callback`] = "true";
24887
- baseHeaders["Upstash-Failure-Callback-Workflow-Runid"] = workflowRunId;
24888
- baseHeaders["Upstash-Failure-Callback-Workflow-Init"] = "false";
24889
- baseHeaders["Upstash-Failure-Callback-Workflow-Url"] = workflowUrl;
24890
- baseHeaders["Upstash-Failure-Callback-Workflow-Calltype"] = "failureCall";
24891
- if (retries !== void 0) {
24892
- baseHeaders["Upstash-Failure-Callback-Retries"] = retries.toString();
24893
- }
24894
- if (flowControl) {
24895
- const { flowControlKey, flowControlValue } = prepareFlowControl(flowControl);
24896
- baseHeaders["Upstash-Failure-Callback-Flow-Control-Key"] = flowControlKey;
24897
- baseHeaders["Upstash-Failure-Callback-Flow-Control-Value"] = flowControlValue;
24898
- }
24899
- if (!step?.callUrl) {
24900
- baseHeaders["Upstash-Failure-Callback"] = failureUrl;
24901
- }
24902
- }
24903
- if (step?.callUrl) {
24904
- baseHeaders["Upstash-Retries"] = callRetries?.toString() ?? "0";
24905
- baseHeaders[WORKFLOW_FEATURE_HEADER] = "WF_NoDelete,InitialBody";
24906
- if (retries !== void 0) {
24907
- baseHeaders["Upstash-Callback-Retries"] = retries.toString();
24908
- baseHeaders["Upstash-Failure-Callback-Retries"] = retries.toString();
24909
- }
24910
- if (callFlowControl) {
24911
- const { flowControlKey, flowControlValue } = prepareFlowControl(callFlowControl);
24912
- baseHeaders["Upstash-Flow-Control-Key"] = flowControlKey;
24913
- baseHeaders["Upstash-Flow-Control-Value"] = flowControlValue;
24914
- }
24915
- if (flowControl) {
24916
- const { flowControlKey, flowControlValue } = prepareFlowControl(flowControl);
24917
- baseHeaders["Upstash-Callback-Flow-Control-Key"] = flowControlKey;
24918
- baseHeaders["Upstash-Callback-Flow-Control-Value"] = flowControlValue;
24506
+ } catch (error) {
24507
+ const isCallReturn = request.headers.get("Upstash-Workflow-Callback");
24508
+ return err(
24509
+ new WorkflowError(`Error when handling call return (isCallReturn=${isCallReturn}): ${error}`)
24510
+ );
24511
+ }
24512
+ };
24513
+ var getTelemetryHeaders = (telemetry2) => {
24514
+ return {
24515
+ [TELEMETRY_HEADER_SDK]: telemetry2.sdk,
24516
+ [TELEMETRY_HEADER_FRAMEWORK]: telemetry2.framework,
24517
+ [TELEMETRY_HEADER_RUNTIME]: telemetry2.runtime ?? "unknown"
24518
+ };
24519
+ };
24520
+ var verifyRequest = async (body, signature, verifier) => {
24521
+ if (!verifier) {
24522
+ return;
24523
+ }
24524
+ try {
24525
+ if (!signature) {
24526
+ throw new Error("`Upstash-Signature` header is not passed.");
24527
+ }
24528
+ const isValid = await verifier.verify({
24529
+ body,
24530
+ signature
24531
+ });
24532
+ if (!isValid) {
24533
+ throw new Error("Signature in `Upstash-Signature` header is not valid");
24534
+ }
24535
+ } catch (error) {
24536
+ throw new WorkflowError(
24537
+ `Failed to verify that the Workflow request comes from QStash: ${error}
24538
+
24539
+ If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
24540
+
24541
+ If you want to disable QStash Verification, you should clear env variables QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY`
24542
+ );
24543
+ }
24544
+ };
24545
+
24546
+ // src/context/steps.ts
24547
+ var BaseLazyStep = class _BaseLazyStep {
24548
+ stepName;
24549
+ constructor(stepName) {
24550
+ if (!stepName) {
24551
+ throw new WorkflowError(
24552
+ "A workflow step name cannot be undefined or an empty string. Please provide a name for your workflow step."
24553
+ );
24554
+ }
24555
+ if (typeof stepName !== "string") {
24556
+ console.warn(
24557
+ "Workflow Warning: A workflow step name must be a string. In a future release, this will throw an error."
24558
+ );
24559
+ }
24560
+ this.stepName = stepName;
24561
+ }
24562
+ /**
24563
+ * parse the out field of a step result.
24564
+ *
24565
+ * will be called when returning the steps to the context from auto executor
24566
+ *
24567
+ * @param out field of the step
24568
+ * @returns parsed out field
24569
+ */
24570
+ parseOut(out) {
24571
+ if (out === void 0) {
24572
+ if (this.allowUndefinedOut) {
24573
+ return void 0;
24574
+ } else {
24575
+ throw new WorkflowError(
24576
+ `Error while parsing output of ${this.stepType} step. Expected a string, but got: undefined`
24577
+ );
24578
+ }
24579
+ }
24580
+ if (typeof out === "object") {
24581
+ if (this.stepType !== "Wait") {
24582
+ console.warn(
24583
+ `Error while parsing ${this.stepType} step output. Expected a string, but got object. Please reach out to Upstash Support.`
24584
+ );
24585
+ return out;
24586
+ }
24587
+ return {
24588
+ ...out,
24589
+ eventData: _BaseLazyStep.tryParsing(out.eventData)
24590
+ };
24591
+ }
24592
+ if (typeof out !== "string") {
24593
+ throw new WorkflowError(
24594
+ `Error while parsing output of ${this.stepType} step. Expected a string or undefined, but got: ${typeof out}`
24595
+ );
24596
+ }
24597
+ return this.safeParseOut(out);
24598
+ }
24599
+ safeParseOut(out) {
24600
+ return _BaseLazyStep.tryParsing(out);
24601
+ }
24602
+ static tryParsing(stepOut) {
24603
+ try {
24604
+ return JSON.parse(stepOut);
24605
+ } catch {
24606
+ return stepOut;
24607
+ }
24608
+ }
24609
+ getBody({ step }) {
24610
+ step.out = JSON.stringify(step.out);
24611
+ return JSON.stringify(step);
24612
+ }
24613
+ getHeaders({ context, telemetry: telemetry2, invokeCount, step }) {
24614
+ return getHeaders({
24615
+ initHeaderValue: "false",
24616
+ workflowConfig: {
24617
+ workflowRunId: context.workflowRunId,
24618
+ workflowUrl: context.url,
24619
+ failureUrl: context.failureUrl,
24620
+ retries: context.retries,
24621
+ useJSONContent: false,
24622
+ telemetry: telemetry2,
24623
+ flowControl: context.flowControl
24624
+ },
24625
+ userHeaders: context.headers,
24626
+ invokeCount,
24627
+ stepInfo: {
24628
+ step,
24629
+ lazyStep: this
24630
+ }
24631
+ });
24632
+ }
24633
+ async submitStep({ context, body, headers }) {
24634
+ return await context.qstashClient.batch([
24635
+ {
24636
+ body,
24637
+ headers,
24638
+ method: "POST",
24639
+ url: context.url
24640
+ }
24641
+ ]);
24642
+ }
24643
+ };
24644
+ var LazyFunctionStep = class extends BaseLazyStep {
24645
+ stepFunction;
24646
+ stepType = "Run";
24647
+ allowUndefinedOut = true;
24648
+ constructor(stepName, stepFunction) {
24649
+ super(stepName);
24650
+ this.stepFunction = stepFunction;
24651
+ }
24652
+ getPlanStep(concurrent, targetStep) {
24653
+ return {
24654
+ stepId: 0,
24655
+ stepName: this.stepName,
24656
+ stepType: this.stepType,
24657
+ concurrent,
24658
+ targetStep
24659
+ };
24660
+ }
24661
+ async getResultStep(concurrent, stepId) {
24662
+ let result = this.stepFunction();
24663
+ if (result instanceof Promise) {
24664
+ result = await result;
24665
+ }
24666
+ return {
24667
+ stepId,
24668
+ stepName: this.stepName,
24669
+ stepType: this.stepType,
24670
+ out: result,
24671
+ concurrent
24672
+ };
24673
+ }
24674
+ };
24675
+ var LazySleepStep = class extends BaseLazyStep {
24676
+ sleep;
24677
+ stepType = "SleepFor";
24678
+ allowUndefinedOut = true;
24679
+ constructor(stepName, sleep) {
24680
+ super(stepName);
24681
+ this.sleep = sleep;
24682
+ }
24683
+ getPlanStep(concurrent, targetStep) {
24684
+ return {
24685
+ stepId: 0,
24686
+ stepName: this.stepName,
24687
+ stepType: this.stepType,
24688
+ sleepFor: this.sleep,
24689
+ concurrent,
24690
+ targetStep
24691
+ };
24692
+ }
24693
+ async getResultStep(concurrent, stepId) {
24694
+ return await Promise.resolve({
24695
+ stepId,
24696
+ stepName: this.stepName,
24697
+ stepType: this.stepType,
24698
+ sleepFor: this.sleep,
24699
+ concurrent
24700
+ });
24701
+ }
24702
+ async submitStep({ context, body, headers, isParallel }) {
24703
+ return await context.qstashClient.batch([
24704
+ {
24705
+ body,
24706
+ headers,
24707
+ method: "POST",
24708
+ url: context.url,
24709
+ delay: isParallel ? void 0 : this.sleep
24710
+ }
24711
+ ]);
24712
+ }
24713
+ };
24714
+ var LazySleepUntilStep = class extends BaseLazyStep {
24715
+ sleepUntil;
24716
+ stepType = "SleepUntil";
24717
+ allowUndefinedOut = true;
24718
+ constructor(stepName, sleepUntil) {
24719
+ super(stepName);
24720
+ this.sleepUntil = sleepUntil;
24721
+ }
24722
+ getPlanStep(concurrent, targetStep) {
24723
+ return {
24724
+ stepId: 0,
24725
+ stepName: this.stepName,
24726
+ stepType: this.stepType,
24727
+ sleepUntil: this.sleepUntil,
24728
+ concurrent,
24729
+ targetStep
24730
+ };
24731
+ }
24732
+ async getResultStep(concurrent, stepId) {
24733
+ return await Promise.resolve({
24734
+ stepId,
24735
+ stepName: this.stepName,
24736
+ stepType: this.stepType,
24737
+ sleepUntil: this.sleepUntil,
24738
+ concurrent
24739
+ });
24740
+ }
24741
+ safeParseOut() {
24742
+ return void 0;
24743
+ }
24744
+ async submitStep({ context, body, headers, isParallel }) {
24745
+ return await context.qstashClient.batch([
24746
+ {
24747
+ body,
24748
+ headers,
24749
+ method: "POST",
24750
+ url: context.url,
24751
+ notBefore: isParallel ? void 0 : this.sleepUntil
24752
+ }
24753
+ ]);
24754
+ }
24755
+ };
24756
+ var LazyCallStep = class _LazyCallStep extends BaseLazyStep {
24757
+ url;
24758
+ method;
24759
+ body;
24760
+ headers;
24761
+ retries;
24762
+ timeout;
24763
+ flowControl;
24764
+ stepType = "Call";
24765
+ allowUndefinedOut = false;
24766
+ constructor(stepName, url, method, body, headers, retries, timeout, flowControl) {
24767
+ super(stepName);
24768
+ this.url = url;
24769
+ this.method = method;
24770
+ this.body = body;
24771
+ this.headers = headers;
24772
+ this.retries = retries;
24773
+ this.timeout = timeout;
24774
+ this.flowControl = flowControl;
24775
+ }
24776
+ getPlanStep(concurrent, targetStep) {
24777
+ return {
24778
+ stepId: 0,
24779
+ stepName: this.stepName,
24780
+ stepType: this.stepType,
24781
+ concurrent,
24782
+ targetStep
24783
+ };
24784
+ }
24785
+ async getResultStep(concurrent, stepId) {
24786
+ return await Promise.resolve({
24787
+ stepId,
24788
+ stepName: this.stepName,
24789
+ stepType: this.stepType,
24790
+ concurrent,
24791
+ callUrl: this.url,
24792
+ callMethod: this.method,
24793
+ callBody: this.body,
24794
+ callHeaders: this.headers
24795
+ });
24796
+ }
24797
+ safeParseOut(out) {
24798
+ const { header, status, body } = JSON.parse(out);
24799
+ const responseHeaders = new Headers(header);
24800
+ if (_LazyCallStep.isText(responseHeaders.get("content-type"))) {
24801
+ const bytes = new Uint8Array(out.length);
24802
+ for (let i = 0; i < out.length; i++) {
24803
+ bytes[i] = out.charCodeAt(i);
24804
+ }
24805
+ const processedResult = new TextDecoder().decode(bytes);
24806
+ const newBody = JSON.parse(processedResult).body;
24807
+ return {
24808
+ status,
24809
+ header,
24810
+ body: BaseLazyStep.tryParsing(newBody)
24811
+ };
24812
+ } else {
24813
+ return { header, status, body };
24814
+ }
24815
+ }
24816
+ static applicationHeaders = /* @__PURE__ */ new Set([
24817
+ "application/json",
24818
+ "application/xml",
24819
+ "application/javascript",
24820
+ "application/x-www-form-urlencoded",
24821
+ "application/xhtml+xml",
24822
+ "application/ld+json",
24823
+ "application/rss+xml",
24824
+ "application/atom+xml"
24825
+ ]);
24826
+ static isText = (contentTypeHeader) => {
24827
+ if (!contentTypeHeader) {
24828
+ return false;
24829
+ }
24830
+ if (_LazyCallStep.applicationHeaders.has(contentTypeHeader)) {
24831
+ return true;
24919
24832
  }
24920
- } else {
24921
- if (flowControl) {
24922
- const { flowControlKey, flowControlValue } = prepareFlowControl(flowControl);
24923
- baseHeaders["Upstash-Flow-Control-Key"] = flowControlKey;
24924
- baseHeaders["Upstash-Flow-Control-Value"] = flowControlValue;
24833
+ if (contentTypeHeader.startsWith("text/")) {
24834
+ return true;
24925
24835
  }
24926
- if (retries !== void 0) {
24927
- baseHeaders["Upstash-Retries"] = retries.toString();
24928
- baseHeaders["Upstash-Failure-Callback-Retries"] = retries.toString();
24836
+ return false;
24837
+ };
24838
+ getBody({ step }) {
24839
+ if (!step.callUrl) {
24840
+ throw new WorkflowError("Incompatible step received in LazyCallStep.getBody");
24929
24841
  }
24842
+ return JSON.stringify(step.callBody);
24930
24843
  }
24931
- if (userHeaders) {
24932
- for (const header of userHeaders.keys()) {
24933
- if (step?.callHeaders) {
24934
- baseHeaders[`Upstash-Callback-Forward-${header}`] = userHeaders.get(header);
24935
- } else {
24936
- baseHeaders[`Upstash-Forward-${header}`] = userHeaders.get(header);
24937
- }
24938
- baseHeaders[`Upstash-Failure-Callback-Forward-${header}`] = userHeaders.get(header);
24844
+ getHeaders({ context, telemetry: telemetry2, invokeCount, step }) {
24845
+ const { headers, contentType } = super.getHeaders({ context, telemetry: telemetry2, invokeCount, step });
24846
+ headers["Upstash-Retries"] = this.retries.toString();
24847
+ headers[WORKFLOW_FEATURE_HEADER] = "WF_NoDelete,InitialBody";
24848
+ if (this.flowControl) {
24849
+ const { flowControlKey, flowControlValue } = prepareFlowControl(this.flowControl);
24850
+ headers["Upstash-Flow-Control-Key"] = flowControlKey;
24851
+ headers["Upstash-Flow-Control-Value"] = flowControlValue;
24852
+ }
24853
+ if (this.timeout) {
24854
+ headers["Upstash-Timeout"] = this.timeout.toString();
24939
24855
  }
24940
- }
24941
- if (step?.callHeaders) {
24942
24856
  const forwardedHeaders = Object.fromEntries(
24943
- Object.entries(step.callHeaders).map(([header, value]) => [
24944
- `Upstash-Forward-${header}`,
24945
- value
24946
- ])
24857
+ Object.entries(this.headers).map(([header, value]) => [`Upstash-Forward-${header}`, value])
24947
24858
  );
24948
24859
  return {
24949
24860
  headers: {
24950
- ...baseHeaders,
24861
+ ...headers,
24951
24862
  ...forwardedHeaders,
24952
- "Upstash-Callback": workflowUrl,
24953
- "Upstash-Callback-Workflow-RunId": workflowRunId,
24863
+ "Upstash-Callback": context.url,
24864
+ "Upstash-Callback-Workflow-RunId": context.workflowRunId,
24954
24865
  "Upstash-Callback-Workflow-CallType": "fromCallback",
24955
24866
  "Upstash-Callback-Workflow-Init": "false",
24956
- "Upstash-Callback-Workflow-Url": workflowUrl,
24867
+ "Upstash-Callback-Workflow-Url": context.url,
24957
24868
  "Upstash-Callback-Feature-Set": "LazyFetch,InitialBody",
24958
24869
  "Upstash-Callback-Forward-Upstash-Workflow-Callback": "true",
24959
24870
  "Upstash-Callback-Forward-Upstash-Workflow-StepId": step.stepId.toString(),
24960
- "Upstash-Callback-Forward-Upstash-Workflow-StepName": step.stepName,
24961
- "Upstash-Callback-Forward-Upstash-Workflow-StepType": step.stepType,
24871
+ "Upstash-Callback-Forward-Upstash-Workflow-StepName": this.stepName,
24872
+ "Upstash-Callback-Forward-Upstash-Workflow-StepType": this.stepType,
24962
24873
  "Upstash-Callback-Forward-Upstash-Workflow-Concurrent": step.concurrent.toString(),
24963
24874
  "Upstash-Callback-Forward-Upstash-Workflow-ContentType": contentType,
24964
- [`Upstash-Callback-Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`]: (invokeCount ?? 0).toString(),
24965
24875
  "Upstash-Workflow-CallType": "toCallback"
24876
+ },
24877
+ contentType
24878
+ };
24879
+ }
24880
+ async submitStep({ context, headers }) {
24881
+ return await context.qstashClient.batch([
24882
+ {
24883
+ headers,
24884
+ body: JSON.stringify(this.body),
24885
+ method: this.method,
24886
+ url: this.url
24966
24887
  }
24888
+ ]);
24889
+ }
24890
+ };
24891
+ var LazyWaitForEventStep = class extends BaseLazyStep {
24892
+ eventId;
24893
+ timeout;
24894
+ stepType = "Wait";
24895
+ allowUndefinedOut = false;
24896
+ constructor(stepName, eventId, timeout) {
24897
+ super(stepName);
24898
+ this.eventId = eventId;
24899
+ this.timeout = timeout;
24900
+ }
24901
+ getPlanStep(concurrent, targetStep) {
24902
+ return {
24903
+ stepId: 0,
24904
+ stepName: this.stepName,
24905
+ stepType: this.stepType,
24906
+ waitEventId: this.eventId,
24907
+ timeout: this.timeout,
24908
+ concurrent,
24909
+ targetStep
24967
24910
  };
24968
24911
  }
24969
- if (step?.waitEventId) {
24912
+ async getResultStep(concurrent, stepId) {
24913
+ return await Promise.resolve({
24914
+ stepId,
24915
+ stepName: this.stepName,
24916
+ stepType: this.stepType,
24917
+ waitEventId: this.eventId,
24918
+ timeout: this.timeout,
24919
+ concurrent
24920
+ });
24921
+ }
24922
+ safeParseOut(out) {
24923
+ const result = JSON.parse(out);
24970
24924
  return {
24971
- headers: {
24972
- ...baseHeaders,
24973
- "Upstash-Workflow-CallType": "step"
24974
- },
24975
- timeoutHeaders: {
24976
- // to include user headers:
24977
- ...Object.fromEntries(
24978
- Object.entries(baseHeaders).map(([header, value]) => [header, [value]])
24979
- ),
24980
- // to include telemetry headers:
24981
- ...telemetry2 ? Object.fromEntries(
24982
- Object.entries(getTelemetryHeaders(telemetry2)).map(([header, value]) => [
24983
- header,
24984
- [value]
24985
- ])
24986
- ) : {},
24987
- // note: using WORKFLOW_ID_HEADER doesn't work, because Runid -> RunId:
24988
- "Upstash-Workflow-Runid": [workflowRunId],
24989
- [WORKFLOW_INIT_HEADER]: ["false"],
24990
- [WORKFLOW_URL_HEADER]: [workflowUrl],
24991
- "Upstash-Workflow-CallType": ["step"]
24992
- }
24993
- };
24994
- }
24995
- return { headers: baseHeaders };
24925
+ ...result,
24926
+ eventData: BaseLazyStep.tryParsing(result.eventData)
24927
+ };
24928
+ }
24929
+ getHeaders({ context, telemetry: telemetry2, invokeCount, step }) {
24930
+ const headers = super.getHeaders({ context, telemetry: telemetry2, invokeCount, step });
24931
+ headers.headers["Upstash-Workflow-CallType"] = "step";
24932
+ return headers;
24933
+ }
24934
+ getBody({ context, step, headers, telemetry: telemetry2 }) {
24935
+ if (!step.waitEventId) {
24936
+ throw new WorkflowError("Incompatible step received in LazyWaitForEventStep.getBody");
24937
+ }
24938
+ const timeoutHeaders = {
24939
+ // to include user headers:
24940
+ ...Object.fromEntries(Object.entries(headers).map(([header, value]) => [header, [value]])),
24941
+ // to include telemetry headers:
24942
+ ...telemetry2 ? Object.fromEntries(
24943
+ Object.entries(getTelemetryHeaders(telemetry2)).map(([header, value]) => [
24944
+ header,
24945
+ [value]
24946
+ ])
24947
+ ) : {},
24948
+ // note: using WORKFLOW_ID_HEADER doesn't work, because Runid -> RunId:
24949
+ "Upstash-Workflow-Runid": [context.workflowRunId],
24950
+ [WORKFLOW_INIT_HEADER]: ["false"],
24951
+ [WORKFLOW_URL_HEADER]: [context.url],
24952
+ "Upstash-Workflow-CallType": ["step"]
24953
+ };
24954
+ const waitBody = {
24955
+ url: context.url,
24956
+ timeout: step.timeout,
24957
+ timeoutBody: void 0,
24958
+ timeoutUrl: context.url,
24959
+ timeoutHeaders,
24960
+ step: {
24961
+ stepId: step.stepId,
24962
+ stepType: "Wait",
24963
+ stepName: step.stepName,
24964
+ concurrent: step.concurrent,
24965
+ targetStep: step.targetStep
24966
+ }
24967
+ };
24968
+ return JSON.stringify(waitBody);
24969
+ }
24970
+ async submitStep({ context, body, headers }) {
24971
+ const result = await context.qstashClient.http.request({
24972
+ path: ["v2", "wait", this.eventId],
24973
+ body,
24974
+ headers,
24975
+ method: "POST",
24976
+ parseResponseAsJson: false
24977
+ });
24978
+ return [result];
24979
+ }
24996
24980
  };
24997
- var verifyRequest = async (body, signature, verifier) => {
24998
- if (!verifier) {
24999
- return;
24981
+ var LazyNotifyStep = class extends LazyFunctionStep {
24982
+ stepType = "Notify";
24983
+ constructor(stepName, eventId, eventData, requester) {
24984
+ super(stepName, async () => {
24985
+ const notifyResponse = await makeNotifyRequest(requester, eventId, eventData);
24986
+ return {
24987
+ eventId,
24988
+ eventData,
24989
+ notifyResponse
24990
+ };
24991
+ });
25000
24992
  }
25001
- try {
25002
- if (!signature) {
25003
- throw new Error("`Upstash-Signature` header is not passed.");
24993
+ safeParseOut(out) {
24994
+ const result = JSON.parse(out);
24995
+ return {
24996
+ ...result,
24997
+ eventData: BaseLazyStep.tryParsing(result.eventData)
24998
+ };
24999
+ }
25000
+ };
25001
+ var LazyInvokeStep = class extends BaseLazyStep {
25002
+ stepType = "Invoke";
25003
+ params;
25004
+ allowUndefinedOut = false;
25005
+ /**
25006
+ * workflow id of the invoked workflow
25007
+ */
25008
+ workflowId;
25009
+ constructor(stepName, {
25010
+ workflow,
25011
+ body,
25012
+ headers = {},
25013
+ workflowRunId,
25014
+ retries,
25015
+ flowControl
25016
+ }) {
25017
+ super(stepName);
25018
+ this.params = {
25019
+ workflow,
25020
+ body,
25021
+ headers,
25022
+ workflowRunId: getWorkflowRunId(workflowRunId),
25023
+ retries,
25024
+ flowControl
25025
+ };
25026
+ const { workflowId } = workflow;
25027
+ if (!workflowId) {
25028
+ throw new WorkflowError("You can only invoke workflow which has a workflowId");
25004
25029
  }
25005
- const isValid = await verifier.verify({
25030
+ this.workflowId = workflowId;
25031
+ }
25032
+ getPlanStep(concurrent, targetStep) {
25033
+ return {
25034
+ stepId: 0,
25035
+ stepName: this.stepName,
25036
+ stepType: this.stepType,
25037
+ concurrent,
25038
+ targetStep
25039
+ };
25040
+ }
25041
+ /**
25042
+ * won't be used as it's the server who will add the result step
25043
+ * in Invoke step.
25044
+ */
25045
+ getResultStep(concurrent, stepId) {
25046
+ return Promise.resolve({
25047
+ stepId,
25048
+ stepName: this.stepName,
25049
+ stepType: this.stepType,
25050
+ concurrent
25051
+ });
25052
+ }
25053
+ safeParseOut(out) {
25054
+ const result = JSON.parse(out);
25055
+ return {
25056
+ ...result,
25057
+ body: BaseLazyStep.tryParsing(result.body)
25058
+ };
25059
+ }
25060
+ getBody({ context, step, telemetry: telemetry2, invokeCount }) {
25061
+ const { headers: invokerHeaders } = getHeaders({
25062
+ initHeaderValue: "false",
25063
+ workflowConfig: {
25064
+ workflowRunId: context.workflowRunId,
25065
+ workflowUrl: context.url,
25066
+ failureUrl: context.failureUrl,
25067
+ retries: context.retries,
25068
+ telemetry: telemetry2,
25069
+ flowControl: context.flowControl,
25070
+ useJSONContent: false
25071
+ },
25072
+ userHeaders: context.headers,
25073
+ invokeCount
25074
+ });
25075
+ invokerHeaders["Upstash-Workflow-Runid"] = context.workflowRunId;
25076
+ const request = {
25077
+ body: JSON.stringify(this.params.body),
25078
+ headers: Object.fromEntries(
25079
+ Object.entries(invokerHeaders).map((pairs) => [pairs[0], [pairs[1]]])
25080
+ ),
25081
+ workflowRunId: context.workflowRunId,
25082
+ workflowUrl: context.url,
25083
+ step
25084
+ };
25085
+ return JSON.stringify(request);
25086
+ }
25087
+ getHeaders({ context, telemetry: telemetry2, invokeCount }) {
25088
+ const {
25089
+ workflow,
25090
+ headers = {},
25091
+ workflowRunId = getWorkflowRunId(),
25092
+ retries,
25093
+ flowControl
25094
+ } = this.params;
25095
+ const newUrl = context.url.replace(/[^/]+$/, this.workflowId);
25096
+ const {
25097
+ retries: workflowRetries,
25098
+ failureFunction,
25099
+ failureUrl,
25100
+ useJSONContent,
25101
+ flowControl: workflowFlowControl
25102
+ } = workflow.options;
25103
+ const { headers: triggerHeaders, contentType } = getHeaders({
25104
+ initHeaderValue: "true",
25105
+ workflowConfig: {
25106
+ workflowRunId,
25107
+ workflowUrl: newUrl,
25108
+ retries: retries ?? workflowRetries,
25109
+ telemetry: telemetry2,
25110
+ failureUrl: failureFunction ? newUrl : failureUrl,
25111
+ flowControl: flowControl ?? workflowFlowControl,
25112
+ useJSONContent: useJSONContent ?? false
25113
+ },
25114
+ invokeCount: invokeCount + 1,
25115
+ userHeaders: new Headers(headers)
25116
+ });
25117
+ triggerHeaders["Upstash-Workflow-Invoke"] = "true";
25118
+ return { headers: triggerHeaders, contentType };
25119
+ }
25120
+ async submitStep({ context, body, headers }) {
25121
+ const newUrl = context.url.replace(/[^/]+$/, this.workflowId);
25122
+ const result = await context.qstashClient.publish({
25123
+ headers,
25124
+ method: "POST",
25006
25125
  body,
25007
- signature
25126
+ url: newUrl
25008
25127
  });
25009
- if (!isValid) {
25010
- throw new Error("Signature in `Upstash-Signature` header is not valid");
25011
- }
25012
- } catch (error) {
25013
- throw new WorkflowError(
25014
- `Failed to verify that the Workflow request comes from QStash: ${error}
25128
+ return [result];
25129
+ }
25130
+ };
25015
25131
 
25016
- If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
25132
+ // src/agents/constants.ts
25133
+ var AGENT_NAME_HEADER = "upstash-agent-name";
25134
+ var MANAGER_AGENT_PROMPT = `You are an agent orchestrating other AI Agents.
25017
25135
 
25018
- If you want to disable QStash Verification, you should clear env variables QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY`
25136
+ These other agents have tools available to them.
25137
+
25138
+ Given a prompt, utilize these agents to address requests.
25139
+
25140
+ Don't always call all the agents provided to you at the same time. You can call one and use it's response to call another.
25141
+
25142
+ Avoid calling the same agent twice in one turn. Instead, prefer to call it once but provide everything
25143
+ you need from that agent.
25144
+ `;
25145
+
25146
+ // src/qstash/headers.ts
25147
+ var WorkflowHeaders = class {
25148
+ userHeaders;
25149
+ workflowConfig;
25150
+ invokeCount;
25151
+ initHeaderValue;
25152
+ stepInfo;
25153
+ headers;
25154
+ constructor({
25155
+ userHeaders,
25156
+ workflowConfig,
25157
+ invokeCount,
25158
+ initHeaderValue,
25159
+ stepInfo
25160
+ }) {
25161
+ this.userHeaders = userHeaders;
25162
+ this.workflowConfig = workflowConfig;
25163
+ this.invokeCount = invokeCount;
25164
+ this.initHeaderValue = initHeaderValue;
25165
+ this.stepInfo = stepInfo;
25166
+ this.headers = {
25167
+ rawHeaders: {},
25168
+ workflowHeaders: {},
25169
+ failureHeaders: {}
25170
+ };
25171
+ }
25172
+ getHeaders() {
25173
+ this.addBaseHeaders();
25174
+ this.addRetries();
25175
+ this.addFlowControl();
25176
+ this.addUserHeaders();
25177
+ this.addInvokeCount();
25178
+ this.addFailureUrl();
25179
+ const contentType = this.addContentType();
25180
+ return this.prefixHeaders(contentType);
25181
+ }
25182
+ addBaseHeaders() {
25183
+ this.headers.rawHeaders = {
25184
+ ...this.headers.rawHeaders,
25185
+ [WORKFLOW_INIT_HEADER]: this.initHeaderValue,
25186
+ [WORKFLOW_ID_HEADER]: this.workflowConfig.workflowRunId,
25187
+ [WORKFLOW_URL_HEADER]: this.workflowConfig.workflowUrl,
25188
+ [WORKFLOW_FEATURE_HEADER]: "LazyFetch,InitialBody",
25189
+ [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
25190
+ ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {},
25191
+ ...this.workflowConfig.telemetry && this.stepInfo?.lazyStep instanceof LazyCallStep && this.stepInfo.lazyStep.headers[AGENT_NAME_HEADER] ? { [TELEMETRY_HEADER_AGENT]: "true" } : {}
25192
+ };
25193
+ if (this.stepInfo?.lazyStep.stepType !== "Call") {
25194
+ this.headers.rawHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] = WORKFLOW_PROTOCOL_VERSION;
25195
+ }
25196
+ }
25197
+ addInvokeCount() {
25198
+ if (this.invokeCount === void 0 || this.invokeCount === 0) {
25199
+ return;
25200
+ }
25201
+ const invokeCount = this.invokeCount.toString();
25202
+ this.headers.workflowHeaders[`Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount;
25203
+ if (this.workflowConfig.failureUrl) {
25204
+ this.headers.failureHeaders[`Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount;
25205
+ }
25206
+ if (this.stepInfo?.lazyStep instanceof LazyCallStep) {
25207
+ this.headers.rawHeaders[`Upstash-Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount;
25208
+ }
25209
+ }
25210
+ addRetries() {
25211
+ if (this.workflowConfig.retries === void 0 || this.workflowConfig.retries === DEFAULT_RETRIES) {
25212
+ return;
25213
+ }
25214
+ const retries = this.workflowConfig.retries.toString();
25215
+ this.headers.workflowHeaders["Retries"] = retries;
25216
+ if (this.workflowConfig.failureUrl) {
25217
+ this.headers.failureHeaders["Retries"] = retries;
25218
+ }
25219
+ }
25220
+ addFlowControl() {
25221
+ if (!this.workflowConfig.flowControl) {
25222
+ return;
25223
+ }
25224
+ const { flowControlKey, flowControlValue } = prepareFlowControl(
25225
+ this.workflowConfig.flowControl
25226
+ );
25227
+ this.headers.workflowHeaders["Flow-Control-Key"] = flowControlKey;
25228
+ this.headers.workflowHeaders["Flow-Control-Value"] = flowControlValue;
25229
+ if (this.workflowConfig.failureUrl) {
25230
+ this.headers.failureHeaders["Flow-Control-Key"] = flowControlKey;
25231
+ this.headers.failureHeaders["Flow-Control-Value"] = flowControlValue;
25232
+ }
25233
+ }
25234
+ addUserHeaders() {
25235
+ for (const [key, value] of this.userHeaders.entries()) {
25236
+ const forwardKey = `Forward-${key}`;
25237
+ this.headers.workflowHeaders[forwardKey] = value;
25238
+ if (this.workflowConfig.failureUrl) {
25239
+ this.headers.failureHeaders[forwardKey] = value;
25240
+ }
25241
+ }
25242
+ }
25243
+ addFailureUrl() {
25244
+ if (!this.workflowConfig.failureUrl) {
25245
+ return;
25246
+ }
25247
+ this.headers.workflowHeaders["Failure-Callback"] = this.workflowConfig.failureUrl;
25248
+ this.headers.failureHeaders[`Forward-${WORKFLOW_FAILURE_HEADER}`] = "true";
25249
+ this.headers.failureHeaders[`Forward-Upstash-Workflow-Failure-Callback`] = "true";
25250
+ this.headers.failureHeaders["Workflow-Runid"] = this.workflowConfig.workflowRunId;
25251
+ this.headers.failureHeaders["Workflow-Init"] = "false";
25252
+ this.headers.failureHeaders["Workflow-Url"] = this.workflowConfig.workflowUrl;
25253
+ this.headers.failureHeaders["Workflow-Calltype"] = "failureCall";
25254
+ this.headers.failureHeaders["Feature-Set"] = "LazyFetch,InitialBody";
25255
+ if (this.workflowConfig.retries !== void 0 && this.workflowConfig.retries !== DEFAULT_RETRIES) {
25256
+ this.headers.failureHeaders["Retries"] = this.workflowConfig.retries.toString();
25257
+ }
25258
+ }
25259
+ addContentType() {
25260
+ if (this.workflowConfig.useJSONContent) {
25261
+ this.headers.rawHeaders["content-type"] = "application/json";
25262
+ return "application/json";
25263
+ }
25264
+ const callHeaders = new Headers(
25265
+ this.stepInfo?.lazyStep instanceof LazyCallStep ? this.stepInfo.lazyStep.headers : {}
25019
25266
  );
25267
+ const contentType = (callHeaders.get("content-type") ? callHeaders.get("content-type") : this.userHeaders?.get("Content-Type") ? this.userHeaders.get("Content-Type") : void 0) ?? DEFAULT_CONTENT_TYPE;
25268
+ this.headers.rawHeaders["content-type"] = contentType;
25269
+ return contentType;
25270
+ }
25271
+ prefixHeaders(contentType) {
25272
+ const { rawHeaders, workflowHeaders, failureHeaders } = this.headers;
25273
+ const isCall = this.stepInfo?.lazyStep.stepType === "Call";
25274
+ return {
25275
+ headers: {
25276
+ ...rawHeaders,
25277
+ ...addPrefixToHeaders(workflowHeaders, isCall ? "Upstash-Callback-" : "Upstash-"),
25278
+ ...addPrefixToHeaders(failureHeaders, "Upstash-Failure-Callback-"),
25279
+ ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {}
25280
+ },
25281
+ contentType
25282
+ };
25020
25283
  }
25021
25284
  };
25285
+ function addPrefixToHeaders(headers, prefix) {
25286
+ const prefixedHeaders = {};
25287
+ for (const [key, value] of Object.entries(headers)) {
25288
+ prefixedHeaders[`${prefix}${key}`] = value;
25289
+ }
25290
+ return prefixedHeaders;
25291
+ }
25022
25292
  var prepareFlowControl = (flowControl) => {
25023
25293
  const parallelism = flowControl.parallelism?.toString();
25024
- const rate = flowControl.ratePerSecond?.toString();
25294
+ const rate = (flowControl.rate ?? flowControl.ratePerSecond)?.toString();
25295
+ const period = typeof flowControl.period === "number" ? `${flowControl.period}s` : flowControl.period;
25025
25296
  const controlValue = [
25026
25297
  parallelism ? `parallelism=${parallelism}` : void 0,
25027
- rate ? `rate=${rate}` : void 0
25298
+ rate ? `rate=${rate}` : void 0,
25299
+ period ? `period=${period}` : void 0
25028
25300
  ].filter(Boolean);
25029
25301
  if (controlValue.length === 0) {
25030
- throw new import_qstash3.QstashError("Provide at least one of parallelism or ratePerSecond for flowControl");
25302
+ throw new import_qstash4.QstashError("Provide at least one of parallelism or ratePerSecond for flowControl");
25031
25303
  }
25032
25304
  return {
25033
25305
  flowControlKey: flowControl.key,
25034
25306
  flowControlValue: controlValue.join(", ")
25035
25307
  };
25036
25308
  };
25037
-
25038
- // src/context/auto-executor.ts
25039
- var import_qstash4 = require("@upstash/qstash");
25040
-
25041
- // src/serve/serve-many.ts
25042
- var getWorkflowId = (url) => {
25043
- const components = url.split("/");
25044
- const lastComponent = components[components.length - 1];
25045
- return lastComponent.split("?")[0];
25046
- };
25047
- var serveManyBase = ({
25048
- workflows,
25049
- getUrl,
25050
- serveMethod,
25051
- options
25309
+ var getHeaders = (params) => {
25310
+ const workflowHeaders = new WorkflowHeaders(params);
25311
+ return workflowHeaders.getHeaders();
25312
+ };
25313
+
25314
+ // src/qstash/submit-steps.ts
25315
+ var submitParallelSteps = async ({
25316
+ context,
25317
+ steps,
25318
+ initialStepCount,
25319
+ invokeCount,
25320
+ telemetry: telemetry2,
25321
+ debug
25052
25322
  }) => {
25053
- const workflowIds = [];
25054
- const workflowMap = Object.fromEntries(
25055
- Object.entries(workflows).map((workflow) => {
25056
- const workflowId = workflow[0];
25057
- if (workflowIds.includes(workflowId)) {
25058
- throw new WorkflowError(
25059
- `Duplicate workflow name found: '${workflowId}'. Please set different workflow names in serveMany.`
25060
- );
25061
- }
25062
- if (workflowId.includes("/")) {
25063
- throw new WorkflowError(
25064
- `Invalid workflow name found: '${workflowId}'. Workflow name cannot contain '/'.`
25065
- );
25066
- }
25067
- workflowIds.push(workflowId);
25068
- workflow[1].workflowId = workflowId;
25069
- workflow[1].options = {
25070
- ...options,
25071
- ...workflow[1].options
25323
+ const planSteps = steps.map(
25324
+ (step, index) => step.getPlanStep(steps.length, initialStepCount + index)
25325
+ );
25326
+ await debug?.log("SUBMIT", "SUBMIT_STEP", {
25327
+ length: planSteps.length,
25328
+ steps: planSteps
25329
+ });
25330
+ const result = await context.qstashClient.batch(
25331
+ planSteps.map((planStep) => {
25332
+ const { headers } = getHeaders({
25333
+ initHeaderValue: "false",
25334
+ workflowConfig: {
25335
+ workflowRunId: context.workflowRunId,
25336
+ workflowUrl: context.url,
25337
+ failureUrl: context.failureUrl,
25338
+ retries: context.retries,
25339
+ flowControl: context.flowControl,
25340
+ telemetry: telemetry2
25341
+ },
25342
+ userHeaders: context.headers,
25343
+ invokeCount
25344
+ });
25345
+ return {
25346
+ headers,
25347
+ method: "POST",
25348
+ url: context.url,
25349
+ body: JSON.stringify(planStep),
25350
+ notBefore: planStep.sleepUntil,
25351
+ delay: planStep.sleepFor
25072
25352
  };
25073
- const params = [workflow[1].routeFunction, workflow[1].options];
25074
- const handler = serveMethod(...params);
25075
- return [workflowId, handler];
25076
25353
  })
25077
25354
  );
25078
- return {
25079
- handler: async (...params) => {
25080
- const url = getUrl(...params);
25081
- const pickedWorkflowId = getWorkflowId(url);
25082
- if (!pickedWorkflowId) {
25083
- return new Response(
25084
- `Unexpected request in serveMany. workflowId not set. Please update the URL of your request.`,
25085
- {
25086
- status: 404
25087
- }
25088
- );
25089
- }
25090
- const workflow = workflowMap[pickedWorkflowId];
25091
- if (!workflow) {
25092
- return new Response(
25093
- `No workflows in serveMany found for '${pickedWorkflowId}'. Please update the URL of your request.`,
25094
- {
25095
- status: 404
25096
- }
25097
- );
25098
- }
25099
- return await workflow(...params);
25100
- }
25101
- };
25355
+ await debug?.log("INFO", "SUBMIT_STEP", {
25356
+ messageIds: result.map((message) => {
25357
+ return {
25358
+ message: message.messageId
25359
+ };
25360
+ })
25361
+ });
25362
+ throw new WorkflowAbort(planSteps[0].stepName, planSteps[0]);
25102
25363
  };
25103
- var invokeWorkflow = async ({
25104
- settings,
25105
- invokeStep,
25364
+ var submitSingleStep = async ({
25106
25365
  context,
25366
+ lazyStep,
25367
+ stepId,
25107
25368
  invokeCount,
25108
- telemetry: telemetry2
25369
+ concurrency,
25370
+ telemetry: telemetry2,
25371
+ debug
25109
25372
  }) => {
25110
- const {
25111
- body,
25112
- workflow,
25113
- headers = {},
25114
- workflowRunId = getWorkflowRunId(),
25115
- retries,
25116
- flowControl
25117
- } = settings;
25118
- const { workflowId } = workflow;
25119
- const {
25120
- retries: workflowRetries,
25121
- failureFunction,
25122
- failureUrl,
25123
- useJSONContent,
25124
- flowControl: workflowFlowControl
25125
- } = workflow.options;
25126
- if (!workflowId) {
25127
- throw new WorkflowError("You can only invoke workflow which has a workflowId");
25128
- }
25129
- const { headers: invokerHeaders } = getHeaders({
25130
- initHeaderValue: "false",
25131
- workflowRunId: context.workflowRunId,
25132
- workflowUrl: context.url,
25133
- userHeaders: context.headers,
25134
- failureUrl: context.failureUrl,
25135
- retries: context.retries,
25136
- telemetry: telemetry2,
25373
+ const resultStep = await lazyStep.getResultStep(concurrency, stepId);
25374
+ await debug?.log("INFO", "RUN_SINGLE", {
25375
+ fromRequest: false,
25376
+ step: resultStep,
25377
+ stepCount: stepId
25378
+ });
25379
+ const { headers } = lazyStep.getHeaders({
25380
+ context,
25381
+ step: resultStep,
25137
25382
  invokeCount,
25138
- flowControl: context.flowControl
25383
+ telemetry: telemetry2
25139
25384
  });
25140
- invokerHeaders["Upstash-Workflow-Runid"] = context.workflowRunId;
25141
- const newUrl = context.url.replace(/[^/]+$/, workflowId);
25142
- const { headers: triggerHeaders } = getHeaders({
25143
- initHeaderValue: "true",
25144
- workflowRunId,
25145
- workflowUrl: newUrl,
25146
- userHeaders: new Headers(headers),
25147
- retries: retries ?? workflowRetries,
25148
- telemetry: telemetry2,
25149
- failureUrl: failureFunction ? newUrl : failureUrl,
25150
- invokeCount: invokeCount + 1,
25151
- flowControl: flowControl ?? workflowFlowControl
25385
+ const body = lazyStep.getBody({
25386
+ context,
25387
+ step: resultStep,
25388
+ headers,
25389
+ invokeCount,
25390
+ telemetry: telemetry2
25152
25391
  });
25153
- triggerHeaders["Upstash-Workflow-Invoke"] = "true";
25154
- if (useJSONContent) {
25155
- triggerHeaders["content-type"] = "application/json";
25156
- }
25157
- const request = {
25158
- body: JSON.stringify(body),
25159
- headers: Object.fromEntries(
25160
- Object.entries(invokerHeaders).map((pairs) => [pairs[0], [pairs[1]]])
25161
- ),
25162
- workflowRunId: context.workflowRunId,
25163
- workflowUrl: context.url,
25164
- step: invokeStep
25165
- };
25166
- await context.qstashClient.publish({
25167
- headers: triggerHeaders,
25168
- method: "POST",
25169
- body: JSON.stringify(request),
25170
- url: newUrl
25392
+ await debug?.log("SUBMIT", "SUBMIT_STEP", {
25393
+ length: 1,
25394
+ steps: [resultStep]
25395
+ });
25396
+ const submitResult = await lazyStep.submitStep({
25397
+ context,
25398
+ body,
25399
+ headers,
25400
+ isParallel: concurrency !== NO_CONCURRENCY,
25401
+ invokeCount,
25402
+ step: resultStep,
25403
+ telemetry: telemetry2
25404
+ });
25405
+ await debug?.log("INFO", "SUBMIT_STEP", {
25406
+ messageIds: submitResult.map((message) => {
25407
+ return {
25408
+ message: message.messageId
25409
+ };
25410
+ })
25171
25411
  });
25412
+ return resultStep;
25172
25413
  };
25173
25414
 
25174
25415
  // src/context/auto-executor.ts
@@ -25275,14 +25516,16 @@ var AutoExecutor = class _AutoExecutor {
25275
25516
  });
25276
25517
  return lazyStep.parseOut(step.out);
25277
25518
  }
25278
- const resultStep = await lazyStep.getResultStep(NO_CONCURRENCY, this.stepCount);
25279
- await this.debug?.log("INFO", "RUN_SINGLE", {
25280
- fromRequest: false,
25281
- step: resultStep,
25282
- stepCount: this.stepCount
25519
+ const resultStep = await submitSingleStep({
25520
+ context: this.context,
25521
+ lazyStep,
25522
+ stepId: this.stepCount,
25523
+ invokeCount: this.invokeCount,
25524
+ concurrency: 1,
25525
+ telemetry: this.telemetry,
25526
+ debug: this.debug
25283
25527
  });
25284
- await this.submitStepsToQStash([resultStep], [lazyStep]);
25285
- return resultStep.out;
25528
+ throw new WorkflowAbort(lazyStep.stepName, resultStep);
25286
25529
  }
25287
25530
  /**
25288
25531
  * Runs steps in parallel.
@@ -25310,10 +25553,14 @@ var AutoExecutor = class _AutoExecutor {
25310
25553
  });
25311
25554
  switch (parallelCallState) {
25312
25555
  case "first": {
25313
- const planSteps = parallelSteps.map(
25314
- (parallelStep, index) => parallelStep.getPlanStep(parallelSteps.length, initialStepCount + index)
25315
- );
25316
- await this.submitStepsToQStash(planSteps, parallelSteps);
25556
+ await submitParallelSteps({
25557
+ context: this.context,
25558
+ steps: parallelSteps,
25559
+ initialStepCount,
25560
+ invokeCount: this.invokeCount,
25561
+ telemetry: this.telemetry,
25562
+ debug: this.debug
25563
+ });
25317
25564
  break;
25318
25565
  }
25319
25566
  case "partial": {
@@ -25327,13 +25574,18 @@ var AutoExecutor = class _AutoExecutor {
25327
25574
  validateStep(parallelSteps[stepIndex], planStep);
25328
25575
  try {
25329
25576
  const parallelStep = parallelSteps[stepIndex];
25330
- const resultStep = await parallelStep.getResultStep(
25331
- parallelSteps.length,
25332
- planStep.targetStep
25333
- );
25334
- await this.submitStepsToQStash([resultStep], [parallelStep]);
25577
+ const resultStep = await submitSingleStep({
25578
+ context: this.context,
25579
+ lazyStep: parallelStep,
25580
+ stepId: planStep.targetStep,
25581
+ invokeCount: this.invokeCount,
25582
+ concurrency: parallelSteps.length,
25583
+ telemetry: this.telemetry,
25584
+ debug: this.debug
25585
+ });
25586
+ throw new WorkflowAbort(parallelStep.stepName, resultStep);
25335
25587
  } catch (error) {
25336
- if (error instanceof WorkflowAbort || error instanceof import_qstash4.QstashError && error.status === 400) {
25588
+ if (error instanceof WorkflowAbort || error instanceof import_qstash5.QstashError && error.status === 400) {
25337
25589
  throw error;
25338
25590
  }
25339
25591
  throw new WorkflowError(
@@ -25389,128 +25641,6 @@ var AutoExecutor = class _AutoExecutor {
25389
25641
  return "discard";
25390
25642
  }
25391
25643
  }
25392
- /**
25393
- * sends the steps to QStash as batch
25394
- *
25395
- * @param steps steps to send
25396
- */
25397
- async submitStepsToQStash(steps, lazySteps) {
25398
- if (steps.length === 0) {
25399
- throw new WorkflowError(
25400
- `Unable to submit steps to QStash. Provided list is empty. Current step: ${this.stepCount}`
25401
- );
25402
- }
25403
- await this.debug?.log("SUBMIT", "SUBMIT_STEP", {
25404
- length: steps.length,
25405
- steps
25406
- });
25407
- if (steps[0].waitEventId && steps.length === 1) {
25408
- const waitStep = steps[0];
25409
- const { headers, timeoutHeaders } = getHeaders({
25410
- initHeaderValue: "false",
25411
- workflowRunId: this.context.workflowRunId,
25412
- workflowUrl: this.context.url,
25413
- userHeaders: this.context.headers,
25414
- step: waitStep,
25415
- failureUrl: this.context.failureUrl,
25416
- retries: this.context.retries,
25417
- telemetry: this.telemetry,
25418
- invokeCount: this.invokeCount,
25419
- flowControl: this.context.flowControl
25420
- });
25421
- const waitBody = {
25422
- url: this.context.url,
25423
- timeout: waitStep.timeout,
25424
- timeoutBody: void 0,
25425
- timeoutUrl: this.context.url,
25426
- timeoutHeaders,
25427
- step: {
25428
- stepId: waitStep.stepId,
25429
- stepType: "Wait",
25430
- stepName: waitStep.stepName,
25431
- concurrent: waitStep.concurrent,
25432
- targetStep: waitStep.targetStep
25433
- }
25434
- };
25435
- await this.context.qstashClient.http.request({
25436
- path: ["v2", "wait", waitStep.waitEventId],
25437
- body: JSON.stringify(waitBody),
25438
- headers,
25439
- method: "POST",
25440
- parseResponseAsJson: false
25441
- });
25442
- throw new WorkflowAbort(waitStep.stepName, waitStep);
25443
- }
25444
- if (steps.length === 1 && lazySteps[0] instanceof LazyInvokeStep) {
25445
- const invokeStep = steps[0];
25446
- const lazyInvokeStep = lazySteps[0];
25447
- await invokeWorkflow({
25448
- settings: lazyInvokeStep.params,
25449
- invokeStep,
25450
- context: this.context,
25451
- invokeCount: this.invokeCount,
25452
- telemetry: this.telemetry
25453
- });
25454
- throw new WorkflowAbort(invokeStep.stepName, invokeStep);
25455
- }
25456
- const result = await this.context.qstashClient.batch(
25457
- steps.map((singleStep, index) => {
25458
- const lazyStep = lazySteps[index];
25459
- const { headers } = getHeaders({
25460
- initHeaderValue: "false",
25461
- workflowRunId: this.context.workflowRunId,
25462
- workflowUrl: this.context.url,
25463
- userHeaders: this.context.headers,
25464
- step: singleStep,
25465
- failureUrl: this.context.failureUrl,
25466
- retries: this.context.retries,
25467
- callRetries: lazyStep instanceof LazyCallStep ? lazyStep.retries : void 0,
25468
- callTimeout: lazyStep instanceof LazyCallStep ? lazyStep.timeout : void 0,
25469
- telemetry: this.telemetry,
25470
- invokeCount: this.invokeCount,
25471
- flowControl: this.context.flowControl,
25472
- callFlowControl: lazyStep instanceof LazyCallStep ? lazyStep.flowControl : void 0
25473
- });
25474
- const willWait = singleStep.concurrent === NO_CONCURRENCY || singleStep.stepId === 0;
25475
- singleStep.out = JSON.stringify(singleStep.out);
25476
- return singleStep.callUrl && lazyStep instanceof LazyCallStep ? (
25477
- // if the step is a third party call, we call the third party
25478
- // url (singleStep.callUrl) and pass information about the workflow
25479
- // in the headers (handled in getHeaders). QStash makes the request
25480
- // to callUrl and returns the result to Workflow endpoint.
25481
- // handleThirdPartyCallResult method sends the result of the third
25482
- // party call to QStash.
25483
- {
25484
- headers,
25485
- method: singleStep.callMethod,
25486
- body: JSON.stringify(singleStep.callBody),
25487
- url: singleStep.callUrl
25488
- }
25489
- ) : (
25490
- // if the step is not a third party call, we use workflow
25491
- // endpoint (context.url) as URL when calling QStash. QStash
25492
- // calls us back with the updated steps list.
25493
- {
25494
- headers,
25495
- method: "POST",
25496
- body: JSON.stringify(singleStep),
25497
- url: this.context.url,
25498
- notBefore: willWait ? singleStep.sleepUntil : void 0,
25499
- delay: willWait ? singleStep.sleepFor : void 0
25500
- }
25501
- );
25502
- })
25503
- );
25504
- const _result = result;
25505
- await this.debug?.log("INFO", "SUBMIT_STEP", {
25506
- messageIds: _result.map((message) => {
25507
- return {
25508
- message: message.messageId
25509
- };
25510
- })
25511
- });
25512
- throw new WorkflowAbort(steps[0].stepName, steps[0]);
25513
- }
25514
25644
  /**
25515
25645
  * Get the promise by executing the lazt steps list. If there is a single
25516
25646
  * step, we call `runSingle`. Otherwise `runParallel` is called.
@@ -25584,7 +25714,7 @@ var sortSteps = (steps) => {
25584
25714
  };
25585
25715
 
25586
25716
  // src/context/api/anthropic.ts
25587
- var import_qstash5 = require("@upstash/qstash");
25717
+ var import_qstash6 = require("@upstash/qstash");
25588
25718
 
25589
25719
  // src/context/provider.ts
25590
25720
  var getProviderInfo = (api) => {
@@ -25648,7 +25778,7 @@ var AnthropicAPI = class extends BaseWorkflowApi {
25648
25778
  return await this.callApi(stepName, {
25649
25779
  api: {
25650
25780
  name: "llm",
25651
- provider: (0, import_qstash5.anthropic)({ token })
25781
+ provider: (0, import_qstash6.anthropic)({ token })
25652
25782
  },
25653
25783
  ...parameters
25654
25784
  });
@@ -25656,12 +25786,12 @@ var AnthropicAPI = class extends BaseWorkflowApi {
25656
25786
  };
25657
25787
 
25658
25788
  // src/context/api/openai.ts
25659
- var import_qstash6 = require("@upstash/qstash");
25789
+ var import_qstash7 = require("@upstash/qstash");
25660
25790
  var OpenAIAPI = class extends BaseWorkflowApi {
25661
25791
  async call(stepName, settings) {
25662
25792
  const { token, organization, operation, baseURL, ...parameters } = settings;
25663
25793
  const useOpenAI = baseURL === void 0;
25664
- const provider = useOpenAI ? (0, import_qstash6.openai)({ token, organization }) : (0, import_qstash6.custom)({ baseUrl: baseURL, token });
25794
+ const provider = useOpenAI ? (0, import_qstash7.openai)({ token, organization }) : (0, import_qstash7.custom)({ baseUrl: baseURL, token });
25665
25795
  return await this.callApi(stepName, {
25666
25796
  api: {
25667
25797
  name: "llm",
@@ -25673,14 +25803,14 @@ var OpenAIAPI = class extends BaseWorkflowApi {
25673
25803
  };
25674
25804
 
25675
25805
  // src/context/api/resend.ts
25676
- var import_qstash7 = require("@upstash/qstash");
25806
+ var import_qstash8 = require("@upstash/qstash");
25677
25807
  var ResendAPI = class extends BaseWorkflowApi {
25678
25808
  async call(stepName, settings) {
25679
25809
  const { token, batch = false, ...parameters } = settings;
25680
25810
  return await this.callApi(stepName, {
25681
25811
  api: {
25682
25812
  name: "email",
25683
- provider: (0, import_qstash7.resend)({ token, batch })
25813
+ provider: (0, import_qstash8.resend)({ token, batch })
25684
25814
  },
25685
25815
  ...parameters
25686
25816
  });
@@ -25707,28 +25837,11 @@ var WorkflowApi = class extends BaseWorkflowApi {
25707
25837
  };
25708
25838
 
25709
25839
  // src/agents/index.ts
25710
- var import_openai3 = require("@ai-sdk/openai");
25711
-
25712
- // src/agents/adapters.ts
25713
25840
  var import_openai2 = require("@ai-sdk/openai");
25714
- var import_ai = require("ai");
25715
-
25716
- // src/agents/constants.ts
25717
- var AGENT_NAME_HEADER = "upstash-agent-name";
25718
- var MANAGER_AGENT_PROMPT = `You are an agent orchestrating other AI Agents.
25719
-
25720
- These other agents have tools available to them.
25721
-
25722
- Given a prompt, utilize these agents to address requests.
25723
-
25724
- Don't always call all the agents provided to you at the same time. You can call one and use it's response to call another.
25725
-
25726
- Avoid calling the same agent twice in one turn. Instead, prefer to call it once but provide everything
25727
- you need from that agent.
25728
- `;
25729
25841
 
25730
25842
  // src/agents/adapters.ts
25731
- var fetchWithContextCall = async (context, ...params) => {
25843
+ var import_ai = require("ai");
25844
+ var fetchWithContextCall = async (context, agentCallParams, ...params) => {
25732
25845
  const [input, init] = params;
25733
25846
  try {
25734
25847
  const headers = init?.headers ? Object.fromEntries(new Headers(init.headers).entries()) : {};
@@ -25739,7 +25852,10 @@ var fetchWithContextCall = async (context, ...params) => {
25739
25852
  url: input.toString(),
25740
25853
  method: init?.method,
25741
25854
  headers,
25742
- body
25855
+ body,
25856
+ timeout: agentCallParams?.timeout,
25857
+ retries: agentCallParams?.retries,
25858
+ flowControl: agentCallParams?.flowControl
25743
25859
  });
25744
25860
  const responseHeaders = new Headers(
25745
25861
  Object.entries(responseInfo.header).reduce(
@@ -25766,10 +25882,11 @@ var fetchWithContextCall = async (context, ...params) => {
25766
25882
  var createWorkflowModel = ({
25767
25883
  context,
25768
25884
  provider,
25769
- providerParams
25885
+ providerParams,
25886
+ agentCallParams
25770
25887
  }) => {
25771
25888
  return provider({
25772
- fetch: (...params) => fetchWithContextCall(context, ...params),
25889
+ fetch: (...params) => fetchWithContextCall(context, agentCallParams, ...params),
25773
25890
  ...providerParams
25774
25891
  });
25775
25892
  };
@@ -26009,17 +26126,87 @@ var WorkflowAgents = class {
26009
26126
  */
26010
26127
  openai(...params) {
26011
26128
  const [model, settings] = params;
26012
- const { baseURL, apiKey, ...otherSettings } = settings ?? {};
26129
+ const { baseURL, apiKey, callSettings, ...otherSettings } = settings ?? {};
26013
26130
  const openaiModel = this.AISDKModel({
26014
26131
  context: this.context,
26015
- provider: import_openai3.createOpenAI,
26016
- providerParams: { baseURL, apiKey, compatibility: "strict" }
26132
+ provider: import_openai2.createOpenAI,
26133
+ providerParams: { baseURL, apiKey, compatibility: "strict" },
26134
+ agentCallParams: callSettings
26017
26135
  });
26018
26136
  return openaiModel(model, otherSettings);
26019
26137
  }
26020
26138
  AISDKModel = createWorkflowModel;
26021
26139
  };
26022
26140
 
26141
+ // src/serve/serve-many.ts
26142
+ var getWorkflowId = (url) => {
26143
+ const components = url.split("/");
26144
+ const lastComponent = components[components.length - 1];
26145
+ return lastComponent.split("?")[0];
26146
+ };
26147
+ var serveManyBase = ({
26148
+ workflows,
26149
+ getUrl,
26150
+ serveMethod,
26151
+ options
26152
+ }) => {
26153
+ const workflowIds = [];
26154
+ const workflowMap = Object.fromEntries(
26155
+ Object.entries(workflows).map((workflow) => {
26156
+ const workflowId = workflow[0];
26157
+ if (workflowIds.includes(workflowId)) {
26158
+ throw new WorkflowError(
26159
+ `Duplicate workflow name found: '${workflowId}'. Please set different workflow names in serveMany.`
26160
+ );
26161
+ }
26162
+ if (workflowId.includes("/")) {
26163
+ throw new WorkflowError(
26164
+ `Invalid workflow name found: '${workflowId}'. Workflow name cannot contain '/'.`
26165
+ );
26166
+ }
26167
+ workflowIds.push(workflowId);
26168
+ workflow[1].workflowId = workflowId;
26169
+ workflow[1].options = {
26170
+ ...options,
26171
+ ...workflow[1].options
26172
+ };
26173
+ const params = [workflow[1].routeFunction, workflow[1].options];
26174
+ const handler = serveMethod(...params);
26175
+ return [workflowId, handler];
26176
+ })
26177
+ );
26178
+ return {
26179
+ handler: async (...params) => {
26180
+ const url = getUrl(...params);
26181
+ const pickedWorkflowId = getWorkflowId(url);
26182
+ if (!pickedWorkflowId) {
26183
+ return new Response(
26184
+ `Unexpected request in serveMany. workflowId not set. Please update the URL of your request.`,
26185
+ {
26186
+ status: 404
26187
+ }
26188
+ );
26189
+ }
26190
+ const workflow = workflowMap[pickedWorkflowId];
26191
+ if (!workflow) {
26192
+ return new Response(
26193
+ `No workflows in serveMany found for '${pickedWorkflowId}'. Please update the URL of your request.`,
26194
+ {
26195
+ status: 404
26196
+ }
26197
+ );
26198
+ }
26199
+ return await workflow(...params);
26200
+ }
26201
+ };
26202
+ };
26203
+ var getNewUrlFromWorkflowId = (url, workflowId) => {
26204
+ if (!workflowId) {
26205
+ throw new WorkflowError("You can only call workflow which has a workflowId");
26206
+ }
26207
+ return url.replace(/[^/]+$/, workflowId);
26208
+ };
26209
+
26023
26210
  // src/context/context.ts
26024
26211
  var WorkflowContext = class {
26025
26212
  executor;
@@ -26241,60 +26428,42 @@ var WorkflowContext = class {
26241
26428
  }
26242
26429
  await this.addStep(new LazySleepUntilStep(stepName, time));
26243
26430
  }
26244
- /**
26245
- * Makes a third party call through QStash in order to make a
26246
- * network call without consuming any runtime.
26247
- *
26248
- * ```ts
26249
- * const { status, body } = await context.call<string>(
26250
- * "post call step",
26251
- * {
26252
- * url: "https://www.some-endpoint.com/api",
26253
- * method: "POST",
26254
- * body: "my-payload"
26255
- * }
26256
- * );
26257
- * ```
26258
- *
26259
- * tries to parse the result of the request as JSON. If it's
26260
- * not a JSON which can be parsed, simply returns the response
26261
- * body as it is.
26262
- *
26263
- * @param stepName
26264
- * @param url url to call
26265
- * @param method call method. "GET" by default.
26266
- * @param body call body
26267
- * @param headers call headers
26268
- * @param retries number of call retries. 0 by default
26269
- * @param timeout max duration to wait for the endpoint to respond. in seconds.
26270
- * @returns call result as {
26271
- * status: number;
26272
- * body: unknown;
26273
- * header: Record<string, string[]>
26274
- * }
26275
- */
26276
26431
  async call(stepName, settings) {
26277
- const {
26278
- url,
26279
- method = "GET",
26280
- body: requestBody,
26281
- headers = {},
26282
- retries = 0,
26283
- timeout,
26284
- flowControl
26285
- } = settings;
26286
- return await this.addStep(
26287
- new LazyCallStep(
26432
+ let callStep;
26433
+ if ("workflow" in settings) {
26434
+ const url = getNewUrlFromWorkflowId(this.url, settings.workflow.workflowId);
26435
+ callStep = new LazyCallStep(
26436
+ stepName,
26437
+ url,
26438
+ "POST",
26439
+ settings.body,
26440
+ settings.headers || {},
26441
+ settings.retries || 0,
26442
+ settings.timeout,
26443
+ settings.flowControl ?? settings.workflow.options.flowControl
26444
+ );
26445
+ } else {
26446
+ const {
26447
+ url,
26448
+ method = "GET",
26449
+ body,
26450
+ headers = {},
26451
+ retries = 0,
26452
+ timeout,
26453
+ flowControl
26454
+ } = settings;
26455
+ callStep = new LazyCallStep(
26288
26456
  stepName,
26289
26457
  url,
26290
26458
  method,
26291
- requestBody,
26459
+ body,
26292
26460
  headers,
26293
26461
  retries,
26294
26462
  timeout,
26295
26463
  flowControl
26296
- )
26297
- );
26464
+ );
26465
+ }
26466
+ return await this.addStep(callStep);
26298
26467
  }
26299
26468
  /**
26300
26469
  * Pauses workflow execution until a specific event occurs or a timeout is reached.
@@ -26442,7 +26611,7 @@ var WorkflowLogger = class _WorkflowLogger {
26442
26611
  };
26443
26612
 
26444
26613
  // src/serve/authorization.ts
26445
- var import_qstash8 = require("@upstash/qstash");
26614
+ var import_qstash9 = require("@upstash/qstash");
26446
26615
  var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowContext {
26447
26616
  static disabledMessage = "disabled-qstash-worklfow-run";
26448
26617
  disabled = true;
@@ -26474,7 +26643,7 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
26474
26643
  */
26475
26644
  static async tryAuthentication(routeFunction, context) {
26476
26645
  const disabledContext = new _DisabledWorkflowContext({
26477
- qstashClient: new import_qstash8.Client({
26646
+ qstashClient: new import_qstash9.Client({
26478
26647
  baseUrl: "disabled-client",
26479
26648
  token: "disabled-client"
26480
26649
  }),
@@ -26688,15 +26857,15 @@ var handleFailure = async (request, requestPayload, qstashClient, initialPayload
26688
26857
  };
26689
26858
 
26690
26859
  // src/serve/options.ts
26691
- var import_qstash9 = require("@upstash/qstash");
26692
26860
  var import_qstash10 = require("@upstash/qstash");
26861
+ var import_qstash11 = require("@upstash/qstash");
26693
26862
  var processOptions = (options) => {
26694
26863
  const environment = options?.env ?? (typeof process === "undefined" ? {} : process.env);
26695
26864
  const receiverEnvironmentVariablesSet = Boolean(
26696
26865
  environment.QSTASH_CURRENT_SIGNING_KEY && environment.QSTASH_NEXT_SIGNING_KEY
26697
26866
  );
26698
26867
  return {
26699
- qstashClient: new import_qstash10.Client({
26868
+ qstashClient: new import_qstash11.Client({
26700
26869
  baseUrl: environment.QSTASH_URL,
26701
26870
  token: environment.QSTASH_TOKEN
26702
26871
  }),
@@ -26731,7 +26900,7 @@ var processOptions = (options) => {
26731
26900
  throw error;
26732
26901
  }
26733
26902
  },
26734
- receiver: receiverEnvironmentVariablesSet ? new import_qstash9.Receiver({
26903
+ receiver: receiverEnvironmentVariablesSet ? new import_qstash10.Receiver({
26735
26904
  currentSigningKey: environment.QSTASH_CURRENT_SIGNING_KEY,
26736
26905
  nextSigningKey: environment.QSTASH_NEXT_SIGNING_KEY
26737
26906
  }) : void 0,