@contractspec/integration.workflow-devkit 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,480 @@
1
+ // @bun
2
+ // src/agent-adapter.ts
3
+ class InMemoryWorkflowDevkitCheckpointStore {
4
+ envelopes = new Map;
5
+ async delete(sessionId) {
6
+ this.envelopes.delete(sessionId);
7
+ }
8
+ async load(sessionId) {
9
+ return this.envelopes.get(sessionId) ?? null;
10
+ }
11
+ async save(envelope) {
12
+ this.envelopes.set(envelope.sessionId, envelope);
13
+ }
14
+ }
15
+
16
+ class InMemoryWorkflowDevkitSuspensionStore {
17
+ states = new Map;
18
+ async clear(sessionId) {
19
+ this.states.delete(sessionId);
20
+ }
21
+ async get(sessionId) {
22
+ return this.states.get(sessionId) ?? null;
23
+ }
24
+ async set(sessionId, state) {
25
+ this.states.set(sessionId, state);
26
+ }
27
+ }
28
+ function createWorkflowDevkitAgentRuntimeAdapterBundle(options = {}) {
29
+ const checkpointStore = options.checkpointStore ?? new InMemoryWorkflowDevkitCheckpointStore;
30
+ const suspensionStore = options.suspensionStore ?? new InMemoryWorkflowDevkitSuspensionStore;
31
+ const resolveSessionToken = options.resolveSessionToken ?? defaultWorkflowDevkitAgentToken;
32
+ return {
33
+ key: "workflow-devkit",
34
+ checkpoint: {
35
+ delete(sessionId) {
36
+ return checkpointStore.delete(sessionId);
37
+ },
38
+ load(sessionId) {
39
+ return checkpointStore.load(sessionId);
40
+ },
41
+ save(envelope) {
42
+ return checkpointStore.save(envelope);
43
+ }
44
+ },
45
+ suspendResume: {
46
+ async resume(params) {
47
+ await suspensionStore.set(params.sessionId, {
48
+ input: params.input,
49
+ metadata: params.metadata,
50
+ reason: "resumed",
51
+ resumedAt: new Date,
52
+ suspendedAt: new Date
53
+ });
54
+ if (options.workflowApi) {
55
+ await options.workflowApi.resumeHook(resolveSessionToken(params.sessionId), {
56
+ input: params.input,
57
+ metadata: params.metadata,
58
+ sessionId: params.sessionId
59
+ });
60
+ }
61
+ },
62
+ async suspend(params) {
63
+ await suspensionStore.set(params.sessionId, {
64
+ metadata: params.metadata,
65
+ reason: params.reason,
66
+ suspendedAt: new Date
67
+ });
68
+ }
69
+ }
70
+ };
71
+ }
72
+ function defaultWorkflowDevkitAgentToken(sessionId) {
73
+ return `agent-session:${sessionId}`;
74
+ }
75
+
76
+ // src/chat-routes.ts
77
+ import { createUIMessageStreamResponse } from "ai";
78
+ import { getRun, resumeHook, start } from "workflow/api";
79
+ var WORKFLOW_RUN_ID_HEADER = "x-workflow-run-id";
80
+ var WORKFLOW_STREAM_TAIL_INDEX_HEADER = "x-workflow-stream-tail-index";
81
+ function createWorkflowDevkitStartRoute(options) {
82
+ const workflowApi = options.workflowApi ?? { start };
83
+ return async (request) => {
84
+ const body = await request.json();
85
+ const args = await options.buildArgs(body, request);
86
+ const run = await workflowApi.start(options.workflow, args);
87
+ if (options.createResponse) {
88
+ return options.createResponse({ body, run });
89
+ }
90
+ if (!run.readable) {
91
+ return new Response(JSON.stringify({ runId: run.runId }), {
92
+ headers: {
93
+ "Content-Type": "application/json",
94
+ [WORKFLOW_RUN_ID_HEADER]: run.runId
95
+ }
96
+ });
97
+ }
98
+ return createUIMessageStreamResponse({
99
+ headers: {
100
+ [WORKFLOW_RUN_ID_HEADER]: run.runId
101
+ },
102
+ stream: run.readable
103
+ });
104
+ };
105
+ }
106
+ function createWorkflowDevkitFollowUpRoute(options) {
107
+ const workflowApi = options.workflowApi ?? { resumeHook };
108
+ return async (request, context) => {
109
+ const runId = context.params.runId ?? context.params.id;
110
+ if (!runId) {
111
+ return new Response(JSON.stringify({ error: "Missing run id" }), {
112
+ status: 400
113
+ });
114
+ }
115
+ const body = await request.json();
116
+ const token = options.resolveToken({ body, request, runId });
117
+ const payload = options.buildPayload ? await options.buildPayload(body, request) : body;
118
+ await workflowApi.resumeHook(token, payload);
119
+ return new Response(JSON.stringify({ ok: true }), {
120
+ headers: {
121
+ "Content-Type": "application/json",
122
+ [WORKFLOW_RUN_ID_HEADER]: runId
123
+ }
124
+ });
125
+ };
126
+ }
127
+ function createWorkflowDevkitStreamRoute(options = {}) {
128
+ const workflowApi = options.workflowApi ?? { getRun };
129
+ return async (request, context) => {
130
+ const runId = context.params.runId ?? context.params.id;
131
+ if (!runId) {
132
+ return new Response(JSON.stringify({ error: "Missing run id" }), {
133
+ status: 400
134
+ });
135
+ }
136
+ const run = workflowApi.getRun(runId);
137
+ if (!run) {
138
+ return new Response(JSON.stringify({ error: "Workflow run not found" }), {
139
+ status: 404
140
+ });
141
+ }
142
+ const startIndex = readStartIndex(request.url);
143
+ const readable = run.getReadable ? run.getReadable({ startIndex }) : run.readable;
144
+ if (!readable) {
145
+ return new Response(JSON.stringify({ error: "Run has no readable stream" }), {
146
+ status: 404
147
+ });
148
+ }
149
+ const tailIndex = await readable.getTailIndex?.();
150
+ return createUIMessageStreamResponse({
151
+ headers: {
152
+ ...tailIndex !== undefined ? {
153
+ [WORKFLOW_STREAM_TAIL_INDEX_HEADER]: String(tailIndex)
154
+ } : {}
155
+ },
156
+ stream: readable
157
+ });
158
+ };
159
+ }
160
+ function readStartIndex(url) {
161
+ const parsed = new URL(url);
162
+ const rawStartIndex = parsed.searchParams.get("startIndex");
163
+ if (!rawStartIndex) {
164
+ return;
165
+ }
166
+ const parsedStartIndex = Number(rawStartIndex);
167
+ return Number.isFinite(parsedStartIndex) ? parsedStartIndex : undefined;
168
+ }
169
+
170
+ // src/helpers.ts
171
+ import { evaluateExpression } from "@contractspec/lib.contracts-spec/workflow";
172
+ function inferWorkflowDevkitBehavior(step) {
173
+ return step.runtime?.workflowDevkit?.behavior ?? step.type;
174
+ }
175
+ function resolveWorkflowDevkitEntryStepId(spec) {
176
+ const entryStepId = spec.definition.entryStepId ?? spec.definition.steps[0]?.id;
177
+ if (!entryStepId) {
178
+ throw new Error(`Workflow ${spec.meta.key}.v${spec.meta.version} does not define an entry step.`);
179
+ }
180
+ return entryStepId;
181
+ }
182
+ function resolveWorkflowDevkitRunIdentity(spec, runIdentity) {
183
+ if (runIdentity) {
184
+ return runIdentity;
185
+ }
186
+ const strategy = spec.runtime?.workflowDevkit?.runIdentity?.strategy ?? "meta-key-version";
187
+ const prefix = spec.runtime?.workflowDevkit?.runIdentity?.prefix;
188
+ const baseIdentity = strategy === "meta-key-version" ? `${spec.meta.key}.v${spec.meta.version}` : `${spec.meta.key}.v${spec.meta.version}`;
189
+ return prefix ? `${prefix}:${baseIdentity}` : baseIdentity;
190
+ }
191
+ function resolveWorkflowDevkitWaitToken(spec, step, runIdentity) {
192
+ const runtime = step.runtime?.workflowDevkit;
193
+ if (!runtime) {
194
+ return;
195
+ }
196
+ const explicitToken = runtime.hookWait?.token ?? runtime.webhookWait?.token ?? runtime.approvalWait?.token ?? runtime.streamSession?.followUpToken;
197
+ if (explicitToken) {
198
+ return explicitToken;
199
+ }
200
+ const tokenStrategy = spec.runtime?.workflowDevkit?.hookTokens?.strategy ?? "deterministic";
201
+ const prefix = spec.runtime?.workflowDevkit?.hookTokens?.prefix ?? spec.meta.key;
202
+ const stableStepId = sanitizeIdentifier(step.id);
203
+ if (tokenStrategy === "session-scoped") {
204
+ const resolvedRunIdentity = sanitizeIdentifier(resolveWorkflowDevkitRunIdentity(spec, runIdentity));
205
+ return `${prefix}:${resolvedRunIdentity}:${stableStepId}`;
206
+ }
207
+ if (tokenStrategy === "step-scoped") {
208
+ return `${prefix}:v${spec.meta.version}:${stableStepId}`;
209
+ }
210
+ return `${prefix}:${stableStepId}`;
211
+ }
212
+ function resolveWorkflowDevkitNextStepId(spec, step, data, input, output) {
213
+ const transitions = spec.definition.transitions.filter((transition) => transition.from === step.id);
214
+ for (const transition of transitions) {
215
+ if (evaluateExpression(transition.condition, {
216
+ data,
217
+ input,
218
+ output
219
+ })) {
220
+ return transition.to;
221
+ }
222
+ }
223
+ return null;
224
+ }
225
+ function mergeWorkflowDevkitData(current, input, output) {
226
+ const next = { ...current };
227
+ if (isRecord(input)) {
228
+ Object.assign(next, input);
229
+ }
230
+ if (isRecord(output)) {
231
+ Object.assign(next, output);
232
+ }
233
+ return next;
234
+ }
235
+ function sanitizeIdentifier(value) {
236
+ return value.replace(/[^a-zA-Z0-9_-]+/g, "-");
237
+ }
238
+ function isRecord(value) {
239
+ return value != null && typeof value === "object" && !Array.isArray(value);
240
+ }
241
+
242
+ // src/compiler.ts
243
+ function compileWorkflowSpecToWorkflowDevkit(spec) {
244
+ return {
245
+ entryStepId: resolveWorkflowDevkitEntryStepId(spec),
246
+ hostTarget: spec.runtime?.workflowDevkit?.hostTarget ?? "generic",
247
+ hookTokenStrategy: spec.runtime?.workflowDevkit?.hookTokens?.strategy ?? "deterministic",
248
+ integrationMode: spec.runtime?.workflowDevkit?.integrationMode ?? "manual",
249
+ runIdentityStrategy: spec.runtime?.workflowDevkit?.runIdentity?.strategy ?? "meta-key-version",
250
+ specKey: spec.meta.key,
251
+ specVersion: spec.meta.version,
252
+ steps: spec.definition.steps.map((step) => ({
253
+ behavior: inferWorkflowDevkitBehavior(step),
254
+ id: step.id,
255
+ label: step.label,
256
+ operationRef: step.action?.operation ? `${step.action.operation.key}.v${step.action.operation.version}` : undefined,
257
+ runtime: step.runtime?.workflowDevkit,
258
+ transitions: spec.definition.transitions.filter((transition) => transition.from === step.id).map((transition) => ({
259
+ condition: transition.condition,
260
+ to: transition.to
261
+ })),
262
+ type: step.type,
263
+ waitToken: resolveWorkflowDevkitWaitToken(spec, step)
264
+ }))
265
+ };
266
+ }
267
+ function generateWorkflowDevkitArtifacts(spec, options) {
268
+ const compilation = compileWorkflowSpecToWorkflowDevkit(spec);
269
+ const workflowFunctionName = options.workflowFunctionName ?? `${sanitizeIdentifier(options.exportName)}WorkflowDevkit`;
270
+ return {
271
+ genericBootstrap: createGenericBootstrapTemplate(options.exportName, workflowFunctionName),
272
+ manifest: JSON.stringify(compilation, null, 2),
273
+ nextFollowUpRoute: createFollowUpRouteTemplate(workflowFunctionName),
274
+ nextStartRoute: createStartRouteTemplate(workflowFunctionName),
275
+ nextStreamRoute: createStreamRouteTemplate(),
276
+ workflowModule: createWorkflowModuleTemplate(options.exportName, options.specImportPath, workflowFunctionName)
277
+ };
278
+ }
279
+ function createGenericBootstrapTemplate(exportName, workflowFunctionName) {
280
+ return `import { ${workflowFunctionName} } from "./${sanitizeIdentifier(exportName)}.workflow-devkit";
281
+
282
+ export const ${sanitizeIdentifier(exportName)}WorkflowDevkitBootstrap = {
283
+ workflow: ${workflowFunctionName},
284
+ createBridge() {
285
+ return {
286
+ executeAutomationStep: async () => {
287
+ throw new Error("Provide executeAutomationStep in your generic host bridge.");
288
+ },
289
+ };
290
+ },
291
+ };
292
+ `;
293
+ }
294
+ function createStartRouteTemplate(workflowFunctionName) {
295
+ return `import { createWorkflowDevkitStartRoute } from "@contractspec/integration.workflow-devkit";
296
+ import { ${workflowFunctionName} } from "./workflow";
297
+
298
+ export const POST = createWorkflowDevkitStartRoute({
299
+ workflow: ${workflowFunctionName},
300
+ async buildArgs(body) {
301
+ return [body];
302
+ },
303
+ });
304
+ `;
305
+ }
306
+ function createFollowUpRouteTemplate(workflowFunctionName) {
307
+ return `import { createWorkflowDevkitFollowUpRoute } from "@contractspec/integration.workflow-devkit";
308
+
309
+ export const POST = createWorkflowDevkitFollowUpRoute({
310
+ resolveToken({ runId }) {
311
+ return \`${workflowFunctionName}:\${runId}\`;
312
+ },
313
+ });
314
+ `;
315
+ }
316
+ function createStreamRouteTemplate() {
317
+ return `import { createWorkflowDevkitStreamRoute } from "@contractspec/integration.workflow-devkit";
318
+
319
+ export const GET = createWorkflowDevkitStreamRoute();
320
+ `;
321
+ }
322
+ function createWorkflowModuleTemplate(exportName, specImportPath, workflowFunctionName) {
323
+ return `import { createHook, createWebhook, sleep } from "workflow";
324
+ import { runWorkflowSpecWithWorkflowDevkit } from "@contractspec/integration.workflow-devkit";
325
+ import { ${exportName} } from "${specImportPath}";
326
+
327
+ export async function ${workflowFunctionName}(input = {}, bridge = {}) {
328
+ "use workflow";
329
+
330
+ return runWorkflowSpecWithWorkflowDevkit({
331
+ spec: ${exportName},
332
+ initialData: input,
333
+ bridge,
334
+ primitives: {
335
+ sleep,
336
+ createHook,
337
+ createWebhook,
338
+ },
339
+ });
340
+ }
341
+ `;
342
+ }
343
+
344
+ // src/next.ts
345
+ import { withWorkflow } from "workflow/next";
346
+ function withContractSpecWorkflow(nextConfig) {
347
+ return withWorkflow(nextConfig);
348
+ }
349
+
350
+ // src/runtime.ts
351
+ async function runWorkflowSpecWithWorkflowDevkit(options) {
352
+ const history = [];
353
+ let currentStepId = resolveWorkflowDevkitEntryStepId(options.spec);
354
+ let data = { ...options.initialData ?? {} };
355
+ let input = options.initialData;
356
+ while (currentStepId) {
357
+ const step = lookupStep(options.spec, currentStepId);
358
+ const runtime = step.runtime?.workflowDevkit;
359
+ const context = {
360
+ data,
361
+ input,
362
+ runIdentity: options.runIdentity,
363
+ runtime,
364
+ spec: options.spec,
365
+ step
366
+ };
367
+ const behavior = inferWorkflowDevkitBehavior(step);
368
+ const token = resolveWorkflowDevkitWaitToken(options.spec, step, options.runIdentity);
369
+ const output = await executeWorkflowDevkitBehavior(behavior, context, token, options.bridge, options.primitives);
370
+ history.push({
371
+ behavior,
372
+ input,
373
+ output,
374
+ stepId: step.id,
375
+ token
376
+ });
377
+ data = mergeWorkflowDevkitData(data, input, output);
378
+ const nextStepId = resolveWorkflowDevkitNextStepId(options.spec, step, data, input, output);
379
+ if (!nextStepId) {
380
+ return {
381
+ currentStep: null,
382
+ data,
383
+ history,
384
+ status: "completed"
385
+ };
386
+ }
387
+ currentStepId = nextStepId;
388
+ input = output;
389
+ }
390
+ return {
391
+ currentStep: null,
392
+ data,
393
+ history,
394
+ status: "completed"
395
+ };
396
+ }
397
+ async function executeWorkflowDevkitBehavior(behavior, context, token, bridge, primitives) {
398
+ switch (behavior) {
399
+ case "sleep":
400
+ if (!context.runtime?.sleep?.duration) {
401
+ throw new Error(`Step "${context.step.id}" is missing sleep.duration.`);
402
+ }
403
+ await primitives.sleep(context.runtime.sleep.duration);
404
+ return { sleptFor: context.runtime.sleep.duration };
405
+ case "hookWait":
406
+ return awaitExternalWait(context, token, bridge?.onExternalWait, primitives.createHook);
407
+ case "webhookWait":
408
+ return awaitExternalWait(context, token, bridge?.onExternalWait, primitives.createWebhook ?? primitives.createHook, context.runtime?.webhookWait?.path, context.runtime?.webhookWait?.method);
409
+ case "approvalWait":
410
+ return awaitExternalWait(context, token, bridge?.onApprovalRequested, primitives.createHook);
411
+ case "streamSession":
412
+ return awaitExternalWait(context, token, bridge?.onStreamSession, primitives.createHook);
413
+ case "automation":
414
+ if (!bridge?.executeAutomationStep) {
415
+ throw new Error("Workflow DevKit bridge requires executeAutomationStep for automation steps.");
416
+ }
417
+ return bridge.executeAutomationStep(context);
418
+ case "human":
419
+ if (!bridge?.awaitHumanInput) {
420
+ throw new Error("Workflow DevKit bridge requires awaitHumanInput for human steps without explicit wait behavior.");
421
+ }
422
+ return bridge.awaitHumanInput(context);
423
+ case "decision":
424
+ return bridge?.executeDecisionStep ? bridge.executeDecisionStep(context) : context.input;
425
+ }
426
+ }
427
+ async function awaitExternalWait(context, token, notifier, factory, path, method) {
428
+ if (!token) {
429
+ throw new Error(`Step "${context.step.id}" requires a Workflow DevKit wait token.`);
430
+ }
431
+ const behavior = context.runtime?.behavior;
432
+ if (behavior !== "approvalWait" && behavior !== "hookWait" && behavior !== "streamSession" && behavior !== "webhookWait") {
433
+ throw new Error(`Step "${context.step.id}" is not configured with an external wait behavior.`);
434
+ }
435
+ const waitContext = {
436
+ ...context,
437
+ behavior,
438
+ token
439
+ };
440
+ await notifier?.(waitContext);
441
+ const hook = factory({ method, path, token });
442
+ try {
443
+ return await hook;
444
+ } finally {
445
+ await hook.dispose?.();
446
+ }
447
+ }
448
+ function lookupStep(spec, stepId) {
449
+ const step = spec.definition.steps.find((candidate) => candidate.id === stepId);
450
+ if (!step) {
451
+ throw new Error(`Step "${stepId}" not found in workflow ${spec.meta.key}.v${spec.meta.version}.`);
452
+ }
453
+ return step;
454
+ }
455
+
456
+ // src/index.ts
457
+ import { WorkflowChatTransport } from "@workflow/ai";
458
+ export {
459
+ withContractSpecWorkflow,
460
+ sanitizeIdentifier,
461
+ runWorkflowSpecWithWorkflowDevkit,
462
+ resolveWorkflowDevkitWaitToken,
463
+ resolveWorkflowDevkitRunIdentity,
464
+ resolveWorkflowDevkitNextStepId,
465
+ resolveWorkflowDevkitEntryStepId,
466
+ mergeWorkflowDevkitData,
467
+ inferWorkflowDevkitBehavior,
468
+ generateWorkflowDevkitArtifacts,
469
+ defaultWorkflowDevkitAgentToken,
470
+ createWorkflowDevkitStreamRoute,
471
+ createWorkflowDevkitStartRoute,
472
+ createWorkflowDevkitFollowUpRoute,
473
+ createWorkflowDevkitAgentRuntimeAdapterBundle,
474
+ compileWorkflowSpecToWorkflowDevkit,
475
+ WorkflowChatTransport,
476
+ WORKFLOW_STREAM_TAIL_INDEX_HEADER,
477
+ WORKFLOW_RUN_ID_HEADER,
478
+ InMemoryWorkflowDevkitSuspensionStore,
479
+ InMemoryWorkflowDevkitCheckpointStore
480
+ };
package/dist/next.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function withContractSpecWorkflow<TNextConfig>(nextConfig: TNextConfig): TNextConfig;
package/dist/next.js ADDED
@@ -0,0 +1,9 @@
1
+ // @bun
2
+ // src/next.ts
3
+ import { withWorkflow } from "workflow/next";
4
+ function withContractSpecWorkflow(nextConfig) {
5
+ return withWorkflow(nextConfig);
6
+ }
7
+ export {
8
+ withContractSpecWorkflow
9
+ };
@@ -0,0 +1,79 @@
1
+ // src/agent-adapter.ts
2
+ class InMemoryWorkflowDevkitCheckpointStore {
3
+ envelopes = new Map;
4
+ async delete(sessionId) {
5
+ this.envelopes.delete(sessionId);
6
+ }
7
+ async load(sessionId) {
8
+ return this.envelopes.get(sessionId) ?? null;
9
+ }
10
+ async save(envelope) {
11
+ this.envelopes.set(envelope.sessionId, envelope);
12
+ }
13
+ }
14
+
15
+ class InMemoryWorkflowDevkitSuspensionStore {
16
+ states = new Map;
17
+ async clear(sessionId) {
18
+ this.states.delete(sessionId);
19
+ }
20
+ async get(sessionId) {
21
+ return this.states.get(sessionId) ?? null;
22
+ }
23
+ async set(sessionId, state) {
24
+ this.states.set(sessionId, state);
25
+ }
26
+ }
27
+ function createWorkflowDevkitAgentRuntimeAdapterBundle(options = {}) {
28
+ const checkpointStore = options.checkpointStore ?? new InMemoryWorkflowDevkitCheckpointStore;
29
+ const suspensionStore = options.suspensionStore ?? new InMemoryWorkflowDevkitSuspensionStore;
30
+ const resolveSessionToken = options.resolveSessionToken ?? defaultWorkflowDevkitAgentToken;
31
+ return {
32
+ key: "workflow-devkit",
33
+ checkpoint: {
34
+ delete(sessionId) {
35
+ return checkpointStore.delete(sessionId);
36
+ },
37
+ load(sessionId) {
38
+ return checkpointStore.load(sessionId);
39
+ },
40
+ save(envelope) {
41
+ return checkpointStore.save(envelope);
42
+ }
43
+ },
44
+ suspendResume: {
45
+ async resume(params) {
46
+ await suspensionStore.set(params.sessionId, {
47
+ input: params.input,
48
+ metadata: params.metadata,
49
+ reason: "resumed",
50
+ resumedAt: new Date,
51
+ suspendedAt: new Date
52
+ });
53
+ if (options.workflowApi) {
54
+ await options.workflowApi.resumeHook(resolveSessionToken(params.sessionId), {
55
+ input: params.input,
56
+ metadata: params.metadata,
57
+ sessionId: params.sessionId
58
+ });
59
+ }
60
+ },
61
+ async suspend(params) {
62
+ await suspensionStore.set(params.sessionId, {
63
+ metadata: params.metadata,
64
+ reason: params.reason,
65
+ suspendedAt: new Date
66
+ });
67
+ }
68
+ }
69
+ };
70
+ }
71
+ function defaultWorkflowDevkitAgentToken(sessionId) {
72
+ return `agent-session:${sessionId}`;
73
+ }
74
+ export {
75
+ defaultWorkflowDevkitAgentToken,
76
+ createWorkflowDevkitAgentRuntimeAdapterBundle,
77
+ InMemoryWorkflowDevkitSuspensionStore,
78
+ InMemoryWorkflowDevkitCheckpointStore
79
+ };
@@ -0,0 +1,100 @@
1
+ // src/chat-routes.ts
2
+ import { createUIMessageStreamResponse } from "ai";
3
+ import { getRun, resumeHook, start } from "workflow/api";
4
+ var WORKFLOW_RUN_ID_HEADER = "x-workflow-run-id";
5
+ var WORKFLOW_STREAM_TAIL_INDEX_HEADER = "x-workflow-stream-tail-index";
6
+ function createWorkflowDevkitStartRoute(options) {
7
+ const workflowApi = options.workflowApi ?? { start };
8
+ return async (request) => {
9
+ const body = await request.json();
10
+ const args = await options.buildArgs(body, request);
11
+ const run = await workflowApi.start(options.workflow, args);
12
+ if (options.createResponse) {
13
+ return options.createResponse({ body, run });
14
+ }
15
+ if (!run.readable) {
16
+ return new Response(JSON.stringify({ runId: run.runId }), {
17
+ headers: {
18
+ "Content-Type": "application/json",
19
+ [WORKFLOW_RUN_ID_HEADER]: run.runId
20
+ }
21
+ });
22
+ }
23
+ return createUIMessageStreamResponse({
24
+ headers: {
25
+ [WORKFLOW_RUN_ID_HEADER]: run.runId
26
+ },
27
+ stream: run.readable
28
+ });
29
+ };
30
+ }
31
+ function createWorkflowDevkitFollowUpRoute(options) {
32
+ const workflowApi = options.workflowApi ?? { resumeHook };
33
+ return async (request, context) => {
34
+ const runId = context.params.runId ?? context.params.id;
35
+ if (!runId) {
36
+ return new Response(JSON.stringify({ error: "Missing run id" }), {
37
+ status: 400
38
+ });
39
+ }
40
+ const body = await request.json();
41
+ const token = options.resolveToken({ body, request, runId });
42
+ const payload = options.buildPayload ? await options.buildPayload(body, request) : body;
43
+ await workflowApi.resumeHook(token, payload);
44
+ return new Response(JSON.stringify({ ok: true }), {
45
+ headers: {
46
+ "Content-Type": "application/json",
47
+ [WORKFLOW_RUN_ID_HEADER]: runId
48
+ }
49
+ });
50
+ };
51
+ }
52
+ function createWorkflowDevkitStreamRoute(options = {}) {
53
+ const workflowApi = options.workflowApi ?? { getRun };
54
+ return async (request, context) => {
55
+ const runId = context.params.runId ?? context.params.id;
56
+ if (!runId) {
57
+ return new Response(JSON.stringify({ error: "Missing run id" }), {
58
+ status: 400
59
+ });
60
+ }
61
+ const run = workflowApi.getRun(runId);
62
+ if (!run) {
63
+ return new Response(JSON.stringify({ error: "Workflow run not found" }), {
64
+ status: 404
65
+ });
66
+ }
67
+ const startIndex = readStartIndex(request.url);
68
+ const readable = run.getReadable ? run.getReadable({ startIndex }) : run.readable;
69
+ if (!readable) {
70
+ return new Response(JSON.stringify({ error: "Run has no readable stream" }), {
71
+ status: 404
72
+ });
73
+ }
74
+ const tailIndex = await readable.getTailIndex?.();
75
+ return createUIMessageStreamResponse({
76
+ headers: {
77
+ ...tailIndex !== undefined ? {
78
+ [WORKFLOW_STREAM_TAIL_INDEX_HEADER]: String(tailIndex)
79
+ } : {}
80
+ },
81
+ stream: readable
82
+ });
83
+ };
84
+ }
85
+ function readStartIndex(url) {
86
+ const parsed = new URL(url);
87
+ const rawStartIndex = parsed.searchParams.get("startIndex");
88
+ if (!rawStartIndex) {
89
+ return;
90
+ }
91
+ const parsedStartIndex = Number(rawStartIndex);
92
+ return Number.isFinite(parsedStartIndex) ? parsedStartIndex : undefined;
93
+ }
94
+ export {
95
+ createWorkflowDevkitStreamRoute,
96
+ createWorkflowDevkitStartRoute,
97
+ createWorkflowDevkitFollowUpRoute,
98
+ WORKFLOW_STREAM_TAIL_INDEX_HEADER,
99
+ WORKFLOW_RUN_ID_HEADER
100
+ };