@sinestack/workflow-sdk 0.0.0-stage → 0.1.1-oidc.0

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ <http://www.apache.org/licenses/>
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Vercel Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,68 @@
1
- # Temporary Holding Version
1
+ # @sinestack/workflow-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One fixed `runWorkflow(ticket)` calls the product's trusted `advanceWorkflow(ticket)` step, then sleeps durably until `wakeAt`. Node and Cloudflare use the same compiled orchestration. Domain state, permissions, credentials, provider submission safety, results and billing remain in the consuming product.
4
+
5
+ After this version is published to npm:
6
+
7
+ ```sh
8
+ pnpm add --save-exact @sinestack/workflow-core@0.1.1-oidc.0 @sinestack/workflow-sdk@0.1.1-oidc.0 workflow@5.2.3
9
+ ```
10
+
11
+ Use Node **24.19+** for the builder and Node executor. Install `workflow@5.2.3`
12
+ directly in the build host: the upstream compiler resolves its built-in steps
13
+ from the generated output directory. The SDK installs the exact matching core
14
+ and Cloudflare World versions. Add `@sinestack/workflow-world-cloudflare@0.1.1-oidc.0`
15
+ directly only if your application imports it. The SDK exposes `/build`, `/node`
16
+ and `/runtime`; there is no root import.
17
+
18
+ Keep all three Sine Workflow packages at the same release and commit the
19
+ consumer lockfile. Registry installations need no overrides. For local tarball
20
+ installation, use package-manager overrides to direct transitive
21
+ `@sinestack/workflow-core` and `@sinestack/workflow-world-cloudflare` to the same local
22
+ artifacts. When moving an existing consumer to the registry, remove those old
23
+ tarball overrides and regenerate the lockfile. See the repository's
24
+ [publishing guide](https://github.com/fei-bai-inc/workflow/blob/main/PUBLISHING.md)
25
+ for registry access and upgrade instructions.
26
+
27
+ ```ts
28
+ import { buildWorkflow } from '@sinestack/workflow-sdk/build';
29
+ await buildWorkflow({
30
+ root: process.cwd(), target: 'cloudflare', deploymentPrefix: 'myappwf',
31
+ identityInputs: ['src/task-effects', 'package.json', 'pnpm-lock.yaml'],
32
+ runtimeService: { service: 'my-app', entrypoint: 'WorkflowRuntime' },
33
+ });
34
+ ```
35
+
36
+ The builder writes `.generated/workflow/flow.mjs`, `node-identity.mjs`, and `.output/workflow/{index.mjs,*.wasm,wrangler.json,manifest.json}` for Cloudflare. Optional `generatedDir` and `outputDir` override these paths. Consumer identity inputs must include all effect/state-machine code, schema contracts and dependency locks. Both infrastructure source and consumer inputs participate in immutable deployment identity.
37
+
38
+ Cloudflare exports `WorkflowService` with private `enqueue(ticket)` and `wake(ticket)`, plus `RunObject`, `TokenObject`, `StreamObject`, `StepRunner`. The executor's private `SINE_WORKFLOW_RUNTIME` service binding calls the consumer's `advanceWorkflow(ticket)`. Public fetch always returns 404. Retain each old immutable Worker, namespaces and encryption secret until its tasks drain; no in-flight migration is promised.
39
+
40
+ For each new immutable Cloudflare Worker, deploy the generated configuration,
41
+ then provision `WORKFLOW_ENCRYPTION_SECRET` before directing tasks to it:
42
+
43
+ ```sh
44
+ pnpm exec wrangler deploy --config .output/workflow/wrangler.json
45
+ pnpm exec wrangler secret put WORKFLOW_ENCRYPTION_SECRET --config .output/workflow/wrangler.json
46
+ ```
47
+
48
+ Supply base64 encoding of exactly 32 random bytes from your secret manager at
49
+ the secret prompt. Missing or malformed secrets fail closed before a run can
50
+ be accepted. Keep that key stable for the release's full retention period;
51
+ changing it makes prior payloads and snapshots unreadable. Local workerd
52
+ fixtures must supply the same binding explicitly. Executor service bindings
53
+ should be enabled only after this provisioning succeeds.
54
+
55
+ For Node, import `createNodeWorkflow` from `@sinestack/workflow-sdk/node` and pass `{dataDir,advance,workflowId,deploymentId,createFlowRoute}` using the generated modules. Call `start()` after configuring the durable product runtime, and `close()` before shutting that runtime down. Preserve both product data and the `workflow/` directory. Local World has one exclusive owner, not a distributed multi-host queue.
56
+
57
+ The pinned Node Local World does not require `WORKFLOW_ENCRYPTION_SECRET` and
58
+ does not encrypt its journal using the Cloudflare secret. Protect its data
59
+ directory with host storage controls. Shared tickets carry identifiers only;
60
+ product payloads and credentials stay in the product's encrypted task storage.
61
+
62
+ The Node owner database permanently pins its immutable deployment before delivery. A different build cannot adopt the same directory or replay old work with new code, even after process restart. Legacy unpinned Local World directories also require explicit migration after draining; preserve the old executor directory and use a fresh executor directory for the new release. Product databases can remain separate from executor state.
63
+
64
+ Retaining a Cloudflare executor alone is insufficient if its runtime service is replaced by incompatible effect code or schema. The callback host must continue to support that ticket's original driver/schema version or reject it before provider I/O. Retain a matching callback host when compatibility cannot be maintained; no adapter performs an implicit in-flight migration.
65
+
66
+ The SDK can replay steps. Product state must atomically persist tasks/outbox, fence leases, checkpoint results, and mark uncertain external side effects without resubmitting them. Cancel/timeout does not prove that an external request was undone.
67
+
68
+ `advanceRun` disables SDK-level step retries. A thrown host/storage/network error is caught by the fixed workflow, which durably sleeps for 30 seconds and tries the same fenced task again. A temporary host outage therefore does not leave the SDK run permanently failed after a finite retry budget. The product owner must return `completed` for absent/terminal tasks and apply its own bounded task deadline; restoring an incompatible driver/schema remains an explicit host responsibility.
@@ -0,0 +1,15 @@
1
+ # Third-party notices
2
+
3
+ This package adapts selected source from [vercel/workflow PR #4682](https://github.com/vercel/workflow/pull/4682), exact commit [`a555966986af83b94cb77d1d427dfdb18a2732cc`](https://github.com/vercel/workflow/tree/a555966986af83b94cb77d1d427dfdb18a2732cc).
4
+
5
+ Upstream project: Workflow Development Kit, Vercel, Inc. Licensed under Apache License 2.0. The complete upstream license is preserved in `LICENSE.workflow.txt`. `SOURCE_ORIGINS.json` identifies every imported source file, its exact source URL, and the SHA-256 of the unmodified fetched source.
6
+
7
+ Imported scope is `packages/world-cloudflare/src` and only `packages/world-sim/src/store.ts` plus its `ids.ts` dependency. The monorepo and simulator runtime were not imported. The former simulator store is maintained here as the production journal projection, `createJournalStore`; Durable Objects own its serialized write boundary, transactional journal, cold reconstruction, token registry, and durable alarms.
8
+
9
+ Local modifications include strict SDK/Workers typing; real required World listing methods; required environment-bound encryption; bounded delivery with durable restart; explicit deployment mismatch errors; terminal queue deduplication; transactional streams and snapshots; removal of simulator fault injection and fake Workers ambient declarations; and behavior-test sources. `src/directory.ts` and the tests are local additions.
10
+
11
+ QuickJS is supplied by pinned `quickjs-wasi@3.4.0` through its own package license. This package does not copy its Wasm binaries: the host statically imports them through the SDK build. Pinned SDK packages retain their distributed licenses and notices.
12
+
13
+ The shared `@sinestack/workflow-sdk` source `packages/sdk/src/compatibility.ts` maintains the pinned SDK build adaptation for lazy compute-instance identity, based on upstream's lazy initialization fix. It is part of host bundling rather than a second World or a mutable runtime-code loader.
14
+
15
+ The maintained adaptation was extracted from SinePowers commit `09f80f7463c07f17bc53ad7a80717214433b9211` into `fei-bai-inc/workflow`. Consumers install its generated package artifacts; no consumer-maintained source fork is required.
@@ -0,0 +1,23 @@
1
+ export interface WorkflowBuildOptions {
2
+ root: string;
3
+ target: 'node' | 'cloudflare';
4
+ generatedDir?: string;
5
+ outputDir?: string;
6
+ deploymentPrefix?: string;
7
+ identityInputs: readonly string[];
8
+ runtimeService?: {
9
+ service: string;
10
+ entrypoint: string;
11
+ };
12
+ compatibilityDate?: string;
13
+ }
14
+ export interface WorkflowBuildResult {
15
+ workflowId: string;
16
+ deploymentId: string;
17
+ generatedDir: string;
18
+ outputDir?: string;
19
+ configPath?: string;
20
+ manifestPath: string;
21
+ }
22
+ /** Build-time only: fixed infrastructure code; never evaluate provider or caller payloads. */
23
+ export declare function buildWorkflow(options: WorkflowBuildOptions): Promise<WorkflowBuildResult>;
package/dist/build.js ADDED
@@ -0,0 +1,143 @@
1
+ import { BaseBuilder } from '@workflow/builders';
2
+ import { build } from 'esbuild';
3
+ import { createHash } from 'node:crypto';
4
+ import { mkdir, readFile, writeFile, cp, readdir, stat } from 'node:fs/promises';
5
+ import { resolve, dirname } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { workflowCompatibilityPlugin } from "./compatibility.js";
8
+ /** Build-time only: fixed infrastructure code; never evaluate provider or caller payloads. */
9
+ export async function buildWorkflow(options) {
10
+ const root = resolve(options.root);
11
+ const sdkSource = resolve(dirname(fileURLToPath(import.meta.url)), '../src');
12
+ const sdkManifest = await readFile(resolve(sdkSource, '../package.json'));
13
+ const sdkPackage = JSON.parse(sdkManifest.toString('utf8'));
14
+ const implementation = `${sdkPackage.name}@${sdkPackage.version}`;
15
+ const generated = resolve(root, options.generatedDir ?? '.generated/workflow');
16
+ const target = options.target;
17
+ if (target !== 'node' && target !== 'cloudflare')
18
+ throw new Error('Expected node or cloudflare workflow target.');
19
+ const prefix = options.deploymentPrefix ?? 'sinewf';
20
+ if (!/^[a-z][a-z0-9-]{0,24}$/u.test(prefix))
21
+ throw new TypeError('Invalid immutable deployment prefix.');
22
+ if (!options.identityInputs.length)
23
+ throw new TypeError('Consumer effect code and contracts must participate in deployment identity.');
24
+ if (target === 'cloudflare' && (!options.runtimeService || !/^[a-z0-9][a-z0-9-]{0,62}$/u.test(options.runtimeService.service) || !/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(options.runtimeService.entrypoint)))
25
+ throw new TypeError('A trusted private runtime service and named entrypoint are required.');
26
+ const output = resolve(root, options.outputDir ?? '.output/workflow');
27
+ async function addConsumerIdentity(digest) {
28
+ // Pin infrastructure changes as well as product-owned side effects.
29
+ digest.update(sdkManifest);
30
+ for (const name of (await readdir(sdkSource)).filter(name => name.endsWith('.ts')).sort())
31
+ digest.update(name).update(await readFile(resolve(sdkSource, name)));
32
+ for (const path of [...options.identityInputs].sort()) {
33
+ const absolute = resolve(root, path), info = await stat(absolute);
34
+ if (info.isDirectory()) {
35
+ for (const name of (await readdir(absolute, { recursive: true })).sort()) {
36
+ const file = resolve(absolute, name);
37
+ if ((await stat(file)).isFile())
38
+ digest.update(`${path}/${name}`).update(await readFile(file));
39
+ }
40
+ }
41
+ else if (info.isFile())
42
+ digest.update(path).update(await readFile(absolute));
43
+ else
44
+ throw new TypeError(`Unsupported workflow identity input: ${path}`);
45
+ }
46
+ }
47
+ class WorkflowBuilder extends BaseBuilder {
48
+ workflowId = '';
49
+ // Upstream normally adds .gitignore entries under workingDir. Here that is
50
+ // an installed immutable package; build outputs belong to the consumer.
51
+ async ensureSwcIgnored() { }
52
+ async build() {
53
+ const inputs = [resolve(sdkSource, 'workflow.ts'), resolve(sdkSource, 'step.ts')];
54
+ const tsconfigPath = resolve(root, 'tsconfig.json');
55
+ const entries = await this.discoverEntries(inputs, generated, tsconfigPath);
56
+ await this.createStepsBundle({ inputFiles: inputs, outfile: resolve(generated, 'steps.mjs'), format: 'esm', tsconfigPath,
57
+ discoveredEntries: entries, skipEsmRequireBanner: true });
58
+ const result = await this.createWorkflowsBundle({ inputFiles: inputs, outfile: resolve(generated, 'flow.mjs'), format: 'esm',
59
+ tsconfigPath, discoveredEntries: entries, bundleFinalOutput: false });
60
+ if (result.interimBundleText === undefined)
61
+ throw new Error('Workflow compiler did not emit the fixed workflow bundle.');
62
+ const workflows = result.manifest.workflows ?? {};
63
+ const matches = Object.values(workflows).flatMap(value => Object.entries(value)).filter(([name]) => name === 'runWorkflow');
64
+ if (matches.length !== 1 || !matches[0])
65
+ throw new Error('The workflow must have exactly one compiled identity.');
66
+ this.workflowId = matches[0][1].workflowId;
67
+ if (!/^[a-zA-Z0-9_./@()[\]-]+$/u.test(this.workflowId) || /node_modules|\.bun|\.pnpm/u.test(this.workflowId)) {
68
+ throw new Error('The fixed workflow identity must not contain an installation path or package-manager encoding.');
69
+ }
70
+ await writeFile(resolve(generated, 'flow.mjs'), `import './steps.mjs';\nimport { workflowEntrypoint } from 'workflow/runtime';\nconst code = ${JSON.stringify(result.interimBundleText)};\nexport const createFlowRoute = () => workflowEntrypoint(code);\n`);
71
+ await writeFile(resolve(generated, 'flow.d.mts'), 'export declare function createFlowRoute(): (request: Request) => Promise<Response>;\n');
72
+ }
73
+ }
74
+ await mkdir(generated, { recursive: true });
75
+ if (target === 'cloudflare')
76
+ await mkdir(output, { recursive: true });
77
+ // The compiler uses workingDir for non-exported source identities. Consumer
78
+ // node_modules layouts (notably Bun's '+' paths) must never become durable IDs.
79
+ // Every input/output and the consumer tsconfig are absolute, so only the fixed
80
+ // infrastructure module identities are rooted here.
81
+ const builder = new WorkflowBuilder({ buildTarget: 'standalone', workingDir: sdkSource, projectRoot: root, moduleSpecifierRoot: sdkSource,
82
+ dirs: [sdkSource], stepsBundlePath: resolve(generated, 'steps.mjs'), workflowsBundlePath: resolve(generated, 'flow.mjs'),
83
+ webhookBundlePath: resolve(generated, 'webhook.mjs'), sourcemap: false, discoverWorkflowsInNodeModules: false, externalPackages: ['cloudflare:workers'] });
84
+ await builder.build();
85
+ // Both hosts execute the same compiler output. Node bundles this fixed route
86
+ // into Nitro; source discovery and compilation never happen during a request.
87
+ const nodeDigest = createHash('sha256');
88
+ for (const filename of ['flow.mjs', 'steps.mjs'])
89
+ nodeDigest.update(filename).update(await readFile(resolve(generated, filename)));
90
+ await addConsumerIdentity(nodeDigest);
91
+ const nodeDeploymentId = `${prefix}-node-${nodeDigest.digest('hex').slice(0, 24)}`;
92
+ await writeFile(resolve(generated, 'node-identity.mjs'), `export const workflowId = ${JSON.stringify(builder.workflowId)};\nexport const deploymentId = ${JSON.stringify(nodeDeploymentId)};\n`);
93
+ await writeFile(resolve(generated, 'node-identity.d.mts'), 'export declare const workflowId: string;\nexport declare const deploymentId: string;\n');
94
+ await writeFile(resolve(generated, 'manifest.node.json'), JSON.stringify({ schemaVersion: 1, workflowId: builder.workflowId, deploymentId: nodeDeploymentId, implementation, consumerIdentityInputs: options.identityInputs }, null, 2) + '\n');
95
+ if (target === 'node') {
96
+ return { workflowId: builder.workflowId, deploymentId: nodeDeploymentId, generatedDir: generated, manifestPath: resolve(generated, 'manifest.node.json') };
97
+ }
98
+ else {
99
+ const wasmFiles = [
100
+ ['quickjs-wasi/quickjs.wasm', 'quickjs.wasm'], ['quickjs-wasi/encoding.so', 'encoding.wasm'],
101
+ ['quickjs-wasi/headers.so', 'headers.wasm'], ['quickjs-wasi/url.so', 'url.wasm'],
102
+ ['quickjs-wasi/structured-clone.so', 'structured-clone.wasm'],
103
+ ];
104
+ for (const [specifier, name] of wasmFiles)
105
+ await cp(fileURLToPath(import.meta.resolve(specifier)), resolve(output, name));
106
+ await writeFile(resolve(generated, 'assets.mjs'), wasmFiles.map(([, name], index) => `import module${index} from './${name}';`).join('\n') +
107
+ '\nexport const modules = {quickjs:module0,encoding:module1,headers:module2,url:module3,structuredClone:module4};\n');
108
+ await writeFile(resolve(generated, 'assets.d.mts'), 'export declare const modules: { quickjs: WebAssembly.Module; encoding: WebAssembly.Module; headers: WebAssembly.Module; url: WebAssembly.Module; structuredClone: WebAssembly.Module };\n');
109
+ const result = await build({ absWorkingDir: root, entryPoints: [resolve(sdkSource, 'worker.ts')], outfile: resolve(output, 'index.mjs'),
110
+ bundle: true, format: 'esm', platform: 'neutral', target: 'es2023', conditions: ['workerd', 'worker', 'browser'],
111
+ external: ['cloudflare:*', 'node:*', './*.wasm'], minify: true, metafile: true,
112
+ plugins: [workflowCompatibilityPlugin()],
113
+ alias: { '@sine-workflow/generated/flow': resolve(generated, 'flow.mjs'), '@sine-workflow/generated/assets': resolve(generated, 'assets.mjs') },
114
+ define: { '__SINE_WORKFLOW_ID__': JSON.stringify(builder.workflowId), '__SINE_WORKFLOW_DEPLOYMENT__': JSON.stringify('sine-workflow-immutable-build') },
115
+ });
116
+ // The immutable deployment identity includes code, compiled engine contracts and Wasm.
117
+ const digest = createHash('sha256');
118
+ for (const filename of ['index.mjs', ...wasmFiles.map(([, name]) => name)])
119
+ digest.update(filename).update(await readFile(resolve(output, filename)));
120
+ await addConsumerIdentity(digest);
121
+ const deploymentId = `${prefix}-${digest.digest('hex').slice(0, 24)}`;
122
+ const index = await readFile(resolve(output, 'index.mjs'), 'utf8');
123
+ await writeFile(resolve(output, 'index.mjs'), index.replaceAll('sine-workflow-immutable-build', deploymentId));
124
+ const configuration = {
125
+ name: deploymentId, main: 'index.mjs', compatibility_date: options.compatibilityDate ?? '2026-10-06', compatibility_flags: ['nodejs_compat', 'enable_ctx_exports'],
126
+ no_bundle: true, workers_dev: false, preview_urls: false,
127
+ rules: [{ type: 'CompiledWasm', globs: ['**/*.wasm'], fallthrough: true }],
128
+ vars: { WORKFLOW_VM: 'quickjs', WORKFLOW_COMPRESSION_CODEC: 'gzip', SINE_WORKFLOW_DEPLOYMENT: deploymentId },
129
+ durable_objects: { bindings: [{ name: 'WORKFLOW_RUNS', class_name: 'RunObject' }, { name: 'WORKFLOW_TOKENS', class_name: 'TokenObject' }, { name: 'WORKFLOW_STREAMS', class_name: 'StreamObject' }] },
130
+ migrations: [{ tag: 'v1', new_sqlite_classes: ['RunObject', 'TokenObject', 'StreamObject'] }],
131
+ services: [{ binding: 'SINE_WORKFLOW_RUNTIME', ...options.runtimeService }],
132
+ observability: { enabled: true },
133
+ };
134
+ const worldRoot = dirname(fileURLToPath(import.meta.resolve('@sinestack/workflow-world-cloudflare/package.json')));
135
+ for (const name of ['LICENSE.workflow.txt', 'THIRD_PARTY_NOTICES.md', 'SOURCE_ORIGINS.json'])
136
+ await cp(resolve(worldRoot, name), resolve(output, name));
137
+ await writeFile(resolve(output, 'wrangler.json'), JSON.stringify(configuration, null, 2) + '\n');
138
+ await writeFile(resolve(output, 'manifest.json'), JSON.stringify({ schemaVersion: 1, deploymentId, workflowId: builder.workflowId, implementation, consumerIdentityInputs: options.identityInputs,
139
+ source: { repository: 'https://github.com/vercel/workflow', commit: 'a555966986af83b94cb77d1d427dfdb18a2732cc', pullRequest: 4682 },
140
+ inputs: Object.keys(result.metafile.inputs).sort(), files: (await readdir(output)).sort() }, null, 2) + '\n');
141
+ return { workflowId: builder.workflowId, deploymentId, generatedDir: generated, outputDir: output, configPath: resolve(output, 'wrangler.json'), manifestPath: resolve(output, 'manifest.json') };
142
+ }
143
+ }
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'esbuild';
2
+ /** Narrow, hash-bound upstream compatibility port; never mutates node_modules or evaluates input code. */
3
+ export declare function workflowCompatibilityPlugin(): Plugin;
@@ -0,0 +1,75 @@
1
+ // Build-only adaptation of vercel/workflow PR #4682 (Apache-2.0), commit a555966986af83b94cb77d1d427dfdb18a2732cc.
2
+ // SDK 5.2.3 still generates compute telemetry IDs at module load; Workers only permit randomness during requests.
3
+ import { createHash } from 'node:crypto';
4
+ import { readFile } from 'node:fs/promises';
5
+ import ts from 'typescript';
6
+ const fingerprints = {
7
+ 'runtime/compute-instance.js': 'fb94134ecb1aa7f5dc2f4dfe38e073e24f023743d2538a9ed1be3781ec5fb01f',
8
+ 'runtime.js': '1e7a1dffc2dbb91668f07e6fe4dbcf6b245c2a22dfeb604655e4bf2e9ca2ef35',
9
+ 'runtime/step-executor.js': '9ba44e47d56f5deae57ff8e46560094dd614161b89241824715230ae07b7c963',
10
+ 'runtime/suspension-handler.js': 'a86dac33cc640ad757e7e252ae4dd1d0f7a230cb2d0f0bd10b41ea5e2cc33322',
11
+ 'runtime/world.js': '6051f9184059de80a1b1fa61c2403d25354fc3c6b6aa83f4015dd7b8893efa48',
12
+ };
13
+ /** Narrow, hash-bound upstream compatibility port; never mutates node_modules or evaluates input code. */
14
+ export function workflowCompatibilityPlugin() {
15
+ return { name: 'sine-workflow-compatibility', setup(builder) {
16
+ builder.onLoad({ filter: /@workflow\/core\/dist\/(runtime\.js|runtime\/(world|compute-instance|step-executor|suspension-handler)\.js)$/ }, async (args) => {
17
+ const name = args.path.split('/@workflow/core/dist/')[1];
18
+ const expected = name === undefined ? undefined : fingerprints[name];
19
+ if (!expected)
20
+ throw new Error('Unexpected Workflow compatibility input.');
21
+ const source = await readFile(args.path, 'utf8');
22
+ if (createHash('sha256').update(source).digest('hex') !== expected)
23
+ throw new Error(`Workflow SDK compatibility input changed: ${name}. Review the upstream update before building.`);
24
+ const file = ts.createSourceFile(args.path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
25
+ if (name === 'runtime/compute-instance.js') {
26
+ return { contents: "import { ulid } from 'ulid';\nlet instanceId;\nexport function getComputeInstanceId() { return instanceId ??= `cinst_${ulid()}`; }\n", loader: 'js' };
27
+ }
28
+ if (name === 'runtime/world.js') {
29
+ // This deployment injects its World explicitly. Retain upstream caches and protocol checks,
30
+ // but remove ambient package discovery and unselected Node/Vercel backend imports.
31
+ const removeFunctions = { getRuntimeRequire: true, resolveModulePath: true };
32
+ let replaced = 0;
33
+ const printer = ts.createPrinter({ removeComments: true });
34
+ const statements = file.statements.flatMap(statement => {
35
+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) &&
36
+ ['node:module', 'node:url', '@workflow/utils', '@workflow/world-local', '@workflow/world-vercel'].includes(statement.moduleSpecifier.text))
37
+ return [];
38
+ if (ts.isFunctionDeclaration(statement) && statement.name && removeFunctions[statement.name.text])
39
+ return [];
40
+ if (ts.isVariableStatement(statement) && statement.declarationList.declarations.some(declaration => ts.isIdentifier(declaration.name) && declaration.name.text === 'createWorld')) {
41
+ replaced++;
42
+ return ["export const createWorld = async () => { throw new Error('Cloudflare workflow World must be explicitly injected before use.'); };"];
43
+ }
44
+ return [printer.printNode(ts.EmitHint.Unspecified, statement, file)];
45
+ });
46
+ if (replaced !== 1)
47
+ throw new Error('Workflow World initialization changed.');
48
+ return { contents: statements.join('\n'), loader: 'js' };
49
+ }
50
+ let imports = 0, usages = 0;
51
+ const transformed = ts.transform(file, [context => root => {
52
+ const visitor = node => {
53
+ if (ts.isImportSpecifier(node) && node.name.text === 'COMPUTE_INSTANCE_ID') {
54
+ imports++;
55
+ return ts.factory.updateImportSpecifier(node, false, undefined, ts.factory.createIdentifier('getComputeInstanceId'));
56
+ }
57
+ if (ts.isIdentifier(node) && node.text === 'COMPUTE_INSTANCE_ID') {
58
+ usages++;
59
+ return ts.factory.createCallExpression(ts.factory.createIdentifier('getComputeInstanceId'), undefined, []);
60
+ }
61
+ return ts.visitEachChild(node, visitor, context);
62
+ };
63
+ return ts.visitNode(root, visitor, ts.isSourceFile) ?? root;
64
+ }]);
65
+ try {
66
+ if (imports !== 1 || usages !== 1 || !transformed.transformed[0])
67
+ throw new Error('Workflow lazy ID adaptation did not match its reviewed shape.');
68
+ return { contents: ts.createPrinter({ removeComments: true }).printFile(transformed.transformed[0]), loader: 'js' };
69
+ }
70
+ finally {
71
+ transformed.dispose();
72
+ }
73
+ });
74
+ } };
75
+ }
package/dist/node.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { type WorkflowTicket, type WorkflowAdvance, type WorkflowScheduler } from '@sinestack/workflow-core';
2
+ /** One process owns this directory; Local World is not a distributed scheduler. */
3
+ export declare function createNodeWorkflow(options: {
4
+ dataDir: string;
5
+ deploymentId: string;
6
+ workflowId: string;
7
+ createFlowRoute(): (request: Request) => Promise<Response>;
8
+ advance(ticket: WorkflowTicket): Promise<WorkflowAdvance>;
9
+ }): Promise<WorkflowScheduler & {
10
+ start(): Promise<void>;
11
+ close(): Promise<void>;
12
+ }>;
package/dist/node.js ADDED
@@ -0,0 +1,109 @@
1
+ import { mkdir, readdir } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { createWorld } from '@workflow/world-local';
5
+ import { getQueueTopicPrefix, resolveQueueNamespace } from '@workflow/world';
6
+ import { start } from 'workflow/api';
7
+ import { setWorld } from 'workflow/runtime';
8
+ import { bindWorkflowRuntime } from "./runtime.js";
9
+ import { deriveWorkflowRunId, validateWorkflowTicket } from '@sinestack/workflow-core';
10
+ /** One process owns this directory; Local World is not a distributed scheduler. */
11
+ export async function createNodeWorkflow(options) {
12
+ const { deploymentId, workflowId, createFlowRoute } = options;
13
+ const directory = resolve(options.dataDir, 'workflow');
14
+ await mkdir(directory, { recursive: true });
15
+ const existingLocalState = await readdir(resolve(directory, 'local')).catch((error) => {
16
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
17
+ return [];
18
+ throw error;
19
+ });
20
+ // SQLite's OS-backed exclusive lock is released even after SIGKILL. Do not
21
+ // infer stale ownership from timeouts or delete another process's lock file.
22
+ const owner = new DatabaseSync(resolve(directory, 'owner.sqlite'));
23
+ // Pin the SDK sandbox for creation and replay. The SDK persists this choice
24
+ // on each run; no application source is evaluated through Node's vm engine.
25
+ if (process.env.WORKFLOW_VM && process.env.WORKFLOW_VM !== 'quickjs') {
26
+ owner.close();
27
+ throw new Error('The Node workflow executor requires WORKFLOW_VM=quickjs.');
28
+ }
29
+ process.env.WORKFLOW_VM = 'quickjs';
30
+ try {
31
+ owner.exec('BEGIN EXCLUSIVE');
32
+ owner.exec('CREATE TABLE IF NOT EXISTS workflow_owner (id INTEGER PRIMARY KEY CHECK(id=1), deployment_id TEXT NOT NULL)');
33
+ const prior = owner.prepare('SELECT deployment_id FROM workflow_owner WHERE id=1').get();
34
+ if (prior && prior.deployment_id !== deploymentId)
35
+ throw new Error('This workflow directory is pinned to another immutable deployment. Retain its original build until drained and use a separate executor data directory for the new release.');
36
+ if (!prior && existingLocalState.length)
37
+ throw new Error('Existing Local World data has no verified deployment pin. Retain the original build and data; implicit adoption by a new executor is refused.');
38
+ owner.prepare('INSERT OR IGNORE INTO workflow_owner(id,deployment_id) VALUES(1,?)').run(deploymentId);
39
+ // Commit the pin before holding the lifetime lock, so SIGKILL cannot erase it.
40
+ owner.exec('COMMIT');
41
+ owner.exec('BEGIN EXCLUSIVE');
42
+ if (owner.prepare('SELECT deployment_id FROM workflow_owner WHERE id=1').get()?.deployment_id !== deploymentId)
43
+ throw new Error('The workflow deployment ownership changed before acquiring its lifetime lock.');
44
+ }
45
+ catch (cause) {
46
+ owner.close();
47
+ if (cause instanceof Error && /deployment|implicit adoption/u.test(cause.message))
48
+ throw cause;
49
+ throw new Error('The Node workflow data directory already has an active owner.', { cause });
50
+ }
51
+ let unbind;
52
+ let closing = false;
53
+ const active = new Set();
54
+ const submissions = new Set();
55
+ const world = createWorld({ dataDir: resolve(directory, 'local'), recoverActiveRuns: true });
56
+ world.getDeploymentId = async () => deploymentId;
57
+ try {
58
+ unbind = bindWorkflowRuntime(ticket => options.advance(validateWorkflowTicket(ticket, { deploymentId })));
59
+ setWorld(world);
60
+ const route = createFlowRoute();
61
+ world.registerHandler(getQueueTopicPrefix('workflow', resolveQueueNamespace()), request => {
62
+ if (closing)
63
+ return Promise.resolve(new Response(null, { status: 503 }));
64
+ const delivery = route(request);
65
+ active.add(delivery);
66
+ void delivery.finally(() => active.delete(delivery)).catch(() => { });
67
+ return delivery;
68
+ });
69
+ }
70
+ catch (error) {
71
+ await world.close?.();
72
+ unbind?.();
73
+ owner.close();
74
+ throw error;
75
+ }
76
+ function submit(value, wake) {
77
+ if (closing)
78
+ return Promise.reject(new Error('The Node workflow executor is closing.'));
79
+ const work = (async () => {
80
+ const ticket = validateWorkflowTicket(value, { deploymentId });
81
+ const id = await deriveWorkflowRunId(ticket);
82
+ const run = await start({ workflowId }, [ticket], { world: { ...world, createRunId: () => id } });
83
+ if (wake)
84
+ await run.wakeUp();
85
+ })();
86
+ submissions.add(work);
87
+ void work.finally(() => submissions.delete(work)).catch(() => { });
88
+ return work;
89
+ }
90
+ let closed;
91
+ return {
92
+ deploymentId,
93
+ async start() { await world.start?.(); },
94
+ enqueue: ticket => submit(ticket, false),
95
+ wake: ticket => submit(ticket, true),
96
+ close() {
97
+ return closed ??= (async () => {
98
+ closing = true;
99
+ await Promise.allSettled([...submissions]);
100
+ await world.close?.();
101
+ // close() stops future deliveries but SDK direct handlers can still be
102
+ // finishing. Keep Runtime, authorization and secrets alive until drained.
103
+ await Promise.allSettled([...active]);
104
+ unbind?.();
105
+ owner.close();
106
+ })();
107
+ },
108
+ };
109
+ }
@@ -0,0 +1,5 @@
1
+ import type { WorkflowTicket, WorkflowAdvance } from '@sinestack/workflow-core';
2
+ type Advance = (ticket: WorkflowTicket) => Promise<WorkflowAdvance>;
3
+ export declare function bindWorkflowRuntime(advance: Advance): () => void;
4
+ export declare function advanceWorkflow(ticket: WorkflowTicket): Promise<WorkflowAdvance>;
5
+ export {};
@@ -0,0 +1,17 @@
1
+ // The compiler bundles steps separately. A process-global symbol keeps the
2
+ // trusted host callback identical in those bundles; it is never an HTTP port.
3
+ const key = Symbol.for('sine.workflow.runtime.v1');
4
+ const state = globalThis;
5
+ export function bindWorkflowRuntime(advance) {
6
+ if (state[key])
7
+ throw new Error('A workflow runtime is already bound in this process.');
8
+ state[key] = advance;
9
+ return () => { if (state[key] === advance)
10
+ delete state[key]; };
11
+ }
12
+ export async function advanceWorkflow(ticket) {
13
+ const advance = state[key];
14
+ if (!advance)
15
+ throw new Error('The trusted workflow runtime is unavailable.');
16
+ return advance(ticket);
17
+ }
package/dist/step.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { type WorkflowTicket, type WorkflowAdvance } from '@sinestack/workflow-core';
2
+ /** The runtime owner performs current authorization and durable phase deduplication on every invocation. */
3
+ export declare function advanceRun(ticket: WorkflowTicket): Promise<WorkflowAdvance>;
4
+ export declare namespace advanceRun {
5
+ var maxRetries: number;
6
+ }
package/dist/step.js ADDED
@@ -0,0 +1,11 @@
1
+ import { validateWorkflowAdvance } from '@sinestack/workflow-core';
2
+ import { advanceWorkflow } from "./runtime.js";
3
+ /** The runtime owner performs current authorization and durable phase deduplication on every invocation. */
4
+ export async function advanceRun(ticket) {
5
+ 'use step';
6
+ const result = await advanceWorkflow(ticket);
7
+ return validateWorkflowAdvance(result);
8
+ }
9
+ // One attempt per durable step. The owner handles provider retries, and the
10
+ // fixed workflow handles host outages without implicitly replaying effects.
11
+ advanceRun.maxRetries = 0;
@@ -0,0 +1,3 @@
1
+ import type { WorkflowTicket } from '@sinestack/workflow-core';
2
+ /** Fixed project orchestration. Neither caller code nor provider payloads enter this workflow. */
3
+ export declare function runWorkflow(ticket: WorkflowTicket): Promise<void>;
@@ -0,0 +1,20 @@
1
+ import { sleep } from 'workflow';
2
+ import { advanceRun } from "./step.js";
3
+ /** Fixed project orchestration. Neither caller code nor provider payloads enter this workflow. */
4
+ export async function runWorkflow(ticket) {
5
+ 'use workflow';
6
+ for (;;) {
7
+ try {
8
+ const result = await advanceRun(ticket);
9
+ if (result.kind === 'completed')
10
+ return;
11
+ await sleep(new Date(result.wakeAt));
12
+ }
13
+ catch {
14
+ // A temporarily unavailable state owner must not permanently fail the
15
+ // workflow after the SDK's finite step retries. Only the owner decides
16
+ // the business deadline and terminal outcome; retry its fenced advance.
17
+ await sleep('30s');
18
+ }
19
+ }
20
+ }
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@sinestack/workflow-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1-oidc.0",
4
+ "type": "module",
5
+ "license": "UNLICENSED",
6
+ "description": "Shared fixed Workflow SDK orchestration, Node host and immutable Cloudflare builder.",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/fei-bai-inc/workflow.git",
10
+ "directory": "packages/sdk"
11
+ },
12
+ "homepage": "https://github.com/fei-bai-inc/workflow/tree/main/packages/sdk#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/fei-bai-inc/workflow/issues"
15
+ },
16
+ "publishConfig": {
17
+ "registry": "https://registry.npmjs.org"
18
+ },
19
+ "engines": {
20
+ "node": ">=24.19.0"
21
+ },
22
+ "exports": {
23
+ "./node": {
24
+ "types": "./dist/node.d.ts",
25
+ "default": "./dist/node.js"
26
+ },
27
+ "./runtime": {
28
+ "types": "./dist/runtime.d.ts",
29
+ "default": "./dist/runtime.js"
30
+ },
31
+ "./build": {
32
+ "types": "./dist/build.d.ts",
33
+ "default": "./dist/build.js"
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "src",
40
+ "README.md",
41
+ "THIRD_PARTY_NOTICES.md",
42
+ "LICENSE.workflow.txt"
43
+ ],
44
+ "dependencies": {
45
+ "@sinestack/workflow-core": "0.1.1-oidc.0",
46
+ "@sinestack/workflow-world-cloudflare": "0.1.1-oidc.0",
47
+ "@workflow/builders": "5.0.6",
48
+ "@workflow/world": "5.0.5",
49
+ "@workflow/world-local": "5.1.2",
50
+ "quickjs-wasi": "3.4.0",
51
+ "esbuild": "0.28.1",
52
+ "typescript": "5.9.3"
53
+ },
54
+ "peerDependencies": {
55
+ "workflow": "5.2.3"
56
+ },
57
+ "scripts": {
58
+ "build": "tsc -p tsconfig.json"
59
+ }
6
60
  }
package/src/build.ts ADDED
@@ -0,0 +1,140 @@
1
+ import { BaseBuilder, type WorkflowManifest } from '@workflow/builders';
2
+ import { build } from 'esbuild';
3
+ import { createHash } from 'node:crypto';
4
+ import { mkdir, readFile, writeFile, cp, readdir, stat } from 'node:fs/promises';
5
+ import { resolve, dirname } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { workflowCompatibilityPlugin } from './compatibility.ts';
8
+
9
+ export interface WorkflowBuildOptions {
10
+ root: string;
11
+ target: 'node' | 'cloudflare';
12
+ generatedDir?: string;
13
+ outputDir?: string;
14
+ deploymentPrefix?: string;
15
+ identityInputs: readonly string[];
16
+ runtimeService?: { service: string; entrypoint: string };
17
+ compatibilityDate?: string;
18
+ }
19
+ export interface WorkflowBuildResult { workflowId: string; deploymentId: string; generatedDir: string; outputDir?: string; configPath?: string; manifestPath: string }
20
+
21
+ /** Build-time only: fixed infrastructure code; never evaluate provider or caller payloads. */
22
+ export async function buildWorkflow(options: WorkflowBuildOptions): Promise<WorkflowBuildResult> {
23
+ const root = resolve(options.root);
24
+ const sdkSource = resolve(dirname(fileURLToPath(import.meta.url)), '../src');
25
+ const sdkManifest = await readFile(resolve(sdkSource, '../package.json'));
26
+ const sdkPackage = JSON.parse(sdkManifest.toString('utf8')) as { name: string; version: string };
27
+ const implementation = `${sdkPackage.name}@${sdkPackage.version}`;
28
+ const generated = resolve(root, options.generatedDir ?? '.generated/workflow');
29
+ const target = options.target;
30
+ if (target !== 'node' && target !== 'cloudflare') throw new Error('Expected node or cloudflare workflow target.');
31
+ const prefix = options.deploymentPrefix ?? 'sinewf';
32
+ if (!/^[a-z][a-z0-9-]{0,24}$/u.test(prefix)) throw new TypeError('Invalid immutable deployment prefix.');
33
+ if (!options.identityInputs.length) throw new TypeError('Consumer effect code and contracts must participate in deployment identity.');
34
+ if (target === 'cloudflare' && (!options.runtimeService || !/^[a-z0-9][a-z0-9-]{0,62}$/u.test(options.runtimeService.service) || !/^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(options.runtimeService.entrypoint))) throw new TypeError('A trusted private runtime service and named entrypoint are required.');
35
+ const output = resolve(root, options.outputDir ?? '.output/workflow');
36
+ async function addConsumerIdentity(digest: ReturnType<typeof createHash>) {
37
+ // Pin infrastructure changes as well as product-owned side effects.
38
+ digest.update(sdkManifest);
39
+ for (const name of (await readdir(sdkSource)).filter(name => name.endsWith('.ts')).sort()) digest.update(name).update(await readFile(resolve(sdkSource, name)));
40
+ for (const path of [...options.identityInputs].sort()) {
41
+ const absolute = resolve(root, path), info = await stat(absolute);
42
+ if (info.isDirectory()) {
43
+ for (const name of (await readdir(absolute, { recursive: true })).sort()) {
44
+ const file = resolve(absolute, name);
45
+ if ((await stat(file)).isFile()) digest.update(`${path}/${name}`).update(await readFile(file));
46
+ }
47
+ } else if (info.isFile()) digest.update(path).update(await readFile(absolute));
48
+ else throw new TypeError(`Unsupported workflow identity input: ${path}`);
49
+ }
50
+ }
51
+
52
+ class WorkflowBuilder extends BaseBuilder {
53
+ workflowId = '';
54
+ // Upstream normally adds .gitignore entries under workingDir. Here that is
55
+ // an installed immutable package; build outputs belong to the consumer.
56
+ protected override async ensureSwcIgnored(): Promise<void> {}
57
+ async build() {
58
+ const inputs = [resolve(sdkSource, 'workflow.ts'), resolve(sdkSource, 'step.ts')];
59
+ const tsconfigPath = resolve(root, 'tsconfig.json');
60
+ const entries = await this.discoverEntries(inputs, generated, tsconfigPath);
61
+ await this.createStepsBundle({ inputFiles: inputs, outfile: resolve(generated, 'steps.mjs'), format: 'esm', tsconfigPath,
62
+ discoveredEntries: entries, skipEsmRequireBanner: true });
63
+ const result = await this.createWorkflowsBundle({ inputFiles: inputs, outfile: resolve(generated, 'flow.mjs'), format: 'esm',
64
+ tsconfigPath, discoveredEntries: entries, bundleFinalOutput: false });
65
+ if (result.interimBundleText === undefined) throw new Error('Workflow compiler did not emit the fixed workflow bundle.');
66
+ const workflows: NonNullable<WorkflowManifest['workflows']> = result.manifest.workflows ?? {};
67
+ const matches = Object.values(workflows).flatMap(value => Object.entries(value)).filter(([name]) => name === 'runWorkflow');
68
+ if (matches.length !== 1 || !matches[0]) throw new Error('The workflow must have exactly one compiled identity.');
69
+ this.workflowId = matches[0][1].workflowId;
70
+ if (!/^[a-zA-Z0-9_./@()[\]-]+$/u.test(this.workflowId) || /node_modules|\.bun|\.pnpm/u.test(this.workflowId)) {
71
+ throw new Error('The fixed workflow identity must not contain an installation path or package-manager encoding.');
72
+ }
73
+ await writeFile(resolve(generated, 'flow.mjs'), `import './steps.mjs';\nimport { workflowEntrypoint } from 'workflow/runtime';\nconst code = ${JSON.stringify(result.interimBundleText)};\nexport const createFlowRoute = () => workflowEntrypoint(code);\n`);
74
+ await writeFile(resolve(generated, 'flow.d.mts'), 'export declare function createFlowRoute(): (request: Request) => Promise<Response>;\n');
75
+ }
76
+ }
77
+ await mkdir(generated, { recursive: true });
78
+ if (target === 'cloudflare') await mkdir(output, { recursive: true });
79
+ // The compiler uses workingDir for non-exported source identities. Consumer
80
+ // node_modules layouts (notably Bun's '+' paths) must never become durable IDs.
81
+ // Every input/output and the consumer tsconfig are absolute, so only the fixed
82
+ // infrastructure module identities are rooted here.
83
+ const builder = new WorkflowBuilder({ buildTarget: 'standalone', workingDir: sdkSource, projectRoot: root, moduleSpecifierRoot: sdkSource,
84
+ dirs: [sdkSource], stepsBundlePath: resolve(generated, 'steps.mjs'), workflowsBundlePath: resolve(generated, 'flow.mjs'),
85
+ webhookBundlePath: resolve(generated, 'webhook.mjs'), sourcemap: false, discoverWorkflowsInNodeModules: false, externalPackages: ['cloudflare:workers'] });
86
+ await builder.build();
87
+ // Both hosts execute the same compiler output. Node bundles this fixed route
88
+ // into Nitro; source discovery and compilation never happen during a request.
89
+ const nodeDigest = createHash('sha256');
90
+ for (const filename of ['flow.mjs', 'steps.mjs']) nodeDigest.update(filename).update(await readFile(resolve(generated, filename)));
91
+ await addConsumerIdentity(nodeDigest);
92
+ const nodeDeploymentId = `${prefix}-node-${nodeDigest.digest('hex').slice(0, 24)}`;
93
+ await writeFile(resolve(generated, 'node-identity.mjs'), `export const workflowId = ${JSON.stringify(builder.workflowId)};\nexport const deploymentId = ${JSON.stringify(nodeDeploymentId)};\n`);
94
+ await writeFile(resolve(generated, 'node-identity.d.mts'), 'export declare const workflowId: string;\nexport declare const deploymentId: string;\n');
95
+ await writeFile(resolve(generated, 'manifest.node.json'), JSON.stringify({ schemaVersion: 1, workflowId: builder.workflowId, deploymentId: nodeDeploymentId, implementation, consumerIdentityInputs: options.identityInputs }, null, 2) + '\n');
96
+ if (target === 'node') {
97
+ return { workflowId: builder.workflowId, deploymentId: nodeDeploymentId, generatedDir: generated, manifestPath: resolve(generated, 'manifest.node.json') };
98
+ } else {
99
+ const wasmFiles = [
100
+ ['quickjs-wasi/quickjs.wasm', 'quickjs.wasm'], ['quickjs-wasi/encoding.so', 'encoding.wasm'],
101
+ ['quickjs-wasi/headers.so', 'headers.wasm'], ['quickjs-wasi/url.so', 'url.wasm'],
102
+ ['quickjs-wasi/structured-clone.so', 'structured-clone.wasm'],
103
+ ] as const;
104
+ for (const [specifier, name] of wasmFiles) await cp(fileURLToPath(import.meta.resolve(specifier)), resolve(output, name));
105
+ await writeFile(resolve(generated, 'assets.mjs'), wasmFiles.map(([, name], index) => `import module${index} from './${name}';`).join('\n') +
106
+ '\nexport const modules = {quickjs:module0,encoding:module1,headers:module2,url:module3,structuredClone:module4};\n');
107
+ await writeFile(resolve(generated, 'assets.d.mts'), 'export declare const modules: { quickjs: WebAssembly.Module; encoding: WebAssembly.Module; headers: WebAssembly.Module; url: WebAssembly.Module; structuredClone: WebAssembly.Module };\n');
108
+ const result = await build({ absWorkingDir: root, entryPoints: [resolve(sdkSource, 'worker.ts')], outfile: resolve(output, 'index.mjs'),
109
+ bundle: true, format: 'esm', platform: 'neutral', target: 'es2023', conditions: ['workerd', 'worker', 'browser'],
110
+ external: ['cloudflare:*', 'node:*', './*.wasm'], minify: true, metafile: true,
111
+ plugins: [workflowCompatibilityPlugin()],
112
+ alias: { '@sine-workflow/generated/flow': resolve(generated, 'flow.mjs'), '@sine-workflow/generated/assets': resolve(generated, 'assets.mjs') },
113
+ define: { '__SINE_WORKFLOW_ID__': JSON.stringify(builder.workflowId), '__SINE_WORKFLOW_DEPLOYMENT__': JSON.stringify('sine-workflow-immutable-build') },
114
+ });
115
+ // The immutable deployment identity includes code, compiled engine contracts and Wasm.
116
+ const digest = createHash('sha256');
117
+ for (const filename of ['index.mjs', ...wasmFiles.map(([, name]) => name)]) digest.update(filename).update(await readFile(resolve(output, filename)));
118
+ await addConsumerIdentity(digest);
119
+ const deploymentId = `${prefix}-${digest.digest('hex').slice(0, 24)}`;
120
+ const index = await readFile(resolve(output, 'index.mjs'), 'utf8');
121
+ await writeFile(resolve(output, 'index.mjs'), index.replaceAll('sine-workflow-immutable-build', deploymentId));
122
+ const configuration = {
123
+ name: deploymentId, main: 'index.mjs', compatibility_date: options.compatibilityDate ?? '2026-10-06', compatibility_flags: ['nodejs_compat', 'enable_ctx_exports'],
124
+ no_bundle: true, workers_dev: false, preview_urls: false,
125
+ rules: [{ type: 'CompiledWasm', globs: ['**/*.wasm'], fallthrough: true }],
126
+ vars: { WORKFLOW_VM: 'quickjs', WORKFLOW_COMPRESSION_CODEC: 'gzip', SINE_WORKFLOW_DEPLOYMENT: deploymentId },
127
+ durable_objects: { bindings: [{ name: 'WORKFLOW_RUNS', class_name: 'RunObject' }, { name: 'WORKFLOW_TOKENS', class_name: 'TokenObject' }, { name: 'WORKFLOW_STREAMS', class_name: 'StreamObject' }] },
128
+ migrations: [{ tag: 'v1', new_sqlite_classes: ['RunObject', 'TokenObject', 'StreamObject'] }],
129
+ services: [{ binding: 'SINE_WORKFLOW_RUNTIME', ...options.runtimeService }],
130
+ observability: { enabled: true },
131
+ };
132
+ const worldRoot = dirname(fileURLToPath(import.meta.resolve('@sinestack/workflow-world-cloudflare/package.json')));
133
+ for (const name of ['LICENSE.workflow.txt', 'THIRD_PARTY_NOTICES.md', 'SOURCE_ORIGINS.json']) await cp(resolve(worldRoot, name), resolve(output, name));
134
+ await writeFile(resolve(output, 'wrangler.json'), JSON.stringify(configuration, null, 2) + '\n');
135
+ await writeFile(resolve(output, 'manifest.json'), JSON.stringify({ schemaVersion: 1, deploymentId, workflowId: builder.workflowId, implementation, consumerIdentityInputs: options.identityInputs,
136
+ source: { repository: 'https://github.com/vercel/workflow', commit: 'a555966986af83b94cb77d1d427dfdb18a2732cc', pullRequest: 4682 },
137
+ inputs: Object.keys(result.metafile.inputs).sort(), files: (await readdir(output)).sort() }, null, 2) + '\n');
138
+ return { workflowId: builder.workflowId, deploymentId, generatedDir: generated, outputDir: output, configPath: resolve(output, 'wrangler.json'), manifestPath: resolve(output, 'manifest.json') };
139
+ }
140
+ }
@@ -0,0 +1,69 @@
1
+ // Build-only adaptation of vercel/workflow PR #4682 (Apache-2.0), commit a555966986af83b94cb77d1d427dfdb18a2732cc.
2
+ // SDK 5.2.3 still generates compute telemetry IDs at module load; Workers only permit randomness during requests.
3
+ import { createHash } from 'node:crypto';
4
+ import { readFile } from 'node:fs/promises';
5
+ import type { Plugin } from 'esbuild';
6
+ import ts from 'typescript';
7
+
8
+ const fingerprints: Readonly<Record<string, string>> = {
9
+ 'runtime/compute-instance.js': 'fb94134ecb1aa7f5dc2f4dfe38e073e24f023743d2538a9ed1be3781ec5fb01f',
10
+ 'runtime.js': '1e7a1dffc2dbb91668f07e6fe4dbcf6b245c2a22dfeb604655e4bf2e9ca2ef35',
11
+ 'runtime/step-executor.js': '9ba44e47d56f5deae57ff8e46560094dd614161b89241824715230ae07b7c963',
12
+ 'runtime/suspension-handler.js': 'a86dac33cc640ad757e7e252ae4dd1d0f7a230cb2d0f0bd10b41ea5e2cc33322',
13
+ 'runtime/world.js': '6051f9184059de80a1b1fa61c2403d25354fc3c6b6aa83f4015dd7b8893efa48',
14
+ };
15
+
16
+ /** Narrow, hash-bound upstream compatibility port; never mutates node_modules or evaluates input code. */
17
+ export function workflowCompatibilityPlugin(): Plugin {
18
+ return { name: 'sine-workflow-compatibility', setup(builder) {
19
+ builder.onLoad({ filter: /@workflow\/core\/dist\/(runtime\.js|runtime\/(world|compute-instance|step-executor|suspension-handler)\.js)$/ }, async args => {
20
+ const name = args.path.split('/@workflow/core/dist/')[1];
21
+ const expected = name === undefined ? undefined : fingerprints[name];
22
+ if (!expected) throw new Error('Unexpected Workflow compatibility input.');
23
+ const source = await readFile(args.path, 'utf8');
24
+ if (createHash('sha256').update(source).digest('hex') !== expected) throw new Error(`Workflow SDK compatibility input changed: ${name}. Review the upstream update before building.`);
25
+ const file = ts.createSourceFile(args.path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
26
+ if (name === 'runtime/compute-instance.js') {
27
+ return { contents: "import { ulid } from 'ulid';\nlet instanceId;\nexport function getComputeInstanceId() { return instanceId ??= `cinst_${ulid()}`; }\n", loader: 'js' };
28
+ }
29
+ if (name === 'runtime/world.js') {
30
+ // This deployment injects its World explicitly. Retain upstream caches and protocol checks,
31
+ // but remove ambient package discovery and unselected Node/Vercel backend imports.
32
+ const removeFunctions: Readonly<Record<string, true>> = { getRuntimeRequire: true, resolveModulePath: true };
33
+ let replaced = 0;
34
+ const printer = ts.createPrinter({ removeComments: true });
35
+ const statements = file.statements.flatMap(statement => {
36
+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) &&
37
+ ['node:module', 'node:url', '@workflow/utils', '@workflow/world-local', '@workflow/world-vercel'].includes(statement.moduleSpecifier.text)) return [];
38
+ if (ts.isFunctionDeclaration(statement) && statement.name && removeFunctions[statement.name.text]) return [];
39
+ if (ts.isVariableStatement(statement) && statement.declarationList.declarations.some(declaration => ts.isIdentifier(declaration.name) && declaration.name.text === 'createWorld')) {
40
+ replaced++;
41
+ return ["export const createWorld = async () => { throw new Error('Cloudflare workflow World must be explicitly injected before use.'); };"];
42
+ }
43
+ return [printer.printNode(ts.EmitHint.Unspecified, statement, file)];
44
+ });
45
+ if (replaced !== 1) throw new Error('Workflow World initialization changed.');
46
+ return { contents: statements.join('\n'), loader: 'js' };
47
+ }
48
+ let imports = 0, usages = 0;
49
+ const transformed = ts.transform(file, [context => root => {
50
+ const visitor: ts.Visitor = node => {
51
+ if (ts.isImportSpecifier(node) && node.name.text === 'COMPUTE_INSTANCE_ID') {
52
+ imports++;
53
+ return ts.factory.updateImportSpecifier(node, false, undefined, ts.factory.createIdentifier('getComputeInstanceId'));
54
+ }
55
+ if (ts.isIdentifier(node) && node.text === 'COMPUTE_INSTANCE_ID') {
56
+ usages++;
57
+ return ts.factory.createCallExpression(ts.factory.createIdentifier('getComputeInstanceId'), undefined, []);
58
+ }
59
+ return ts.visitEachChild(node, visitor, context);
60
+ };
61
+ return ts.visitNode(root, visitor, ts.isSourceFile) ?? root;
62
+ }]);
63
+ try {
64
+ if (imports !== 1 || usages !== 1 || !transformed.transformed[0]) throw new Error('Workflow lazy ID adaptation did not match its reviewed shape.');
65
+ return { contents: ts.createPrinter({ removeComments: true }).printFile(transformed.transformed[0]), loader: 'js' };
66
+ } finally { transformed.dispose(); }
67
+ });
68
+ } };
69
+ }
@@ -0,0 +1,7 @@
1
+ /** Build-owned static modules; emitted only by buildWorkflow, never supplied by API callers. */
2
+ declare module '@sine-workflow/generated/flow' {
3
+ export function createFlowRoute(): (request: Request) => Promise<Response>;
4
+ }
5
+ declare module '@sine-workflow/generated/assets' {
6
+ export const modules: { quickjs: WebAssembly.Module; encoding: WebAssembly.Module; headers: WebAssembly.Module; url: WebAssembly.Module; structuredClone: WebAssembly.Module };
7
+ }
package/src/node.ts ADDED
@@ -0,0 +1,106 @@
1
+ import { mkdir, readdir } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { createWorld } from '@workflow/world-local';
5
+ import { getQueueTopicPrefix, resolveQueueNamespace } from '@workflow/world';
6
+ import { start } from 'workflow/api';
7
+ import { setWorld } from 'workflow/runtime';
8
+ import { bindWorkflowRuntime } from './runtime.ts';
9
+ import { deriveWorkflowRunId, validateWorkflowTicket, type WorkflowTicket, type WorkflowAdvance, type WorkflowScheduler } from '@sinestack/workflow-core';
10
+
11
+ /** One process owns this directory; Local World is not a distributed scheduler. */
12
+ export async function createNodeWorkflow(options: {
13
+ dataDir: string;
14
+ deploymentId: string;
15
+ workflowId: string;
16
+ createFlowRoute(): (request: Request) => Promise<Response>;
17
+ advance(ticket: WorkflowTicket): Promise<WorkflowAdvance>;
18
+ }): Promise<WorkflowScheduler & { start(): Promise<void>; close(): Promise<void> }> {
19
+ const { deploymentId, workflowId, createFlowRoute } = options;
20
+ const directory = resolve(options.dataDir, 'workflow');
21
+ await mkdir(directory, { recursive: true });
22
+ const existingLocalState = await readdir(resolve(directory, 'local')).catch((error: unknown) => {
23
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return [];
24
+ throw error;
25
+ });
26
+ // SQLite's OS-backed exclusive lock is released even after SIGKILL. Do not
27
+ // infer stale ownership from timeouts or delete another process's lock file.
28
+ const owner = new DatabaseSync(resolve(directory, 'owner.sqlite'));
29
+ // Pin the SDK sandbox for creation and replay. The SDK persists this choice
30
+ // on each run; no application source is evaluated through Node's vm engine.
31
+ if (process.env.WORKFLOW_VM && process.env.WORKFLOW_VM !== 'quickjs') {
32
+ owner.close();
33
+ throw new Error('The Node workflow executor requires WORKFLOW_VM=quickjs.');
34
+ }
35
+ process.env.WORKFLOW_VM = 'quickjs';
36
+ try {
37
+ owner.exec('BEGIN EXCLUSIVE');
38
+ owner.exec('CREATE TABLE IF NOT EXISTS workflow_owner (id INTEGER PRIMARY KEY CHECK(id=1), deployment_id TEXT NOT NULL)');
39
+ const prior = owner.prepare('SELECT deployment_id FROM workflow_owner WHERE id=1').get();
40
+ if (prior && prior.deployment_id !== deploymentId) throw new Error('This workflow directory is pinned to another immutable deployment. Retain its original build until drained and use a separate executor data directory for the new release.');
41
+ if (!prior && existingLocalState.length) throw new Error('Existing Local World data has no verified deployment pin. Retain the original build and data; implicit adoption by a new executor is refused.');
42
+ owner.prepare('INSERT OR IGNORE INTO workflow_owner(id,deployment_id) VALUES(1,?)').run(deploymentId);
43
+ // Commit the pin before holding the lifetime lock, so SIGKILL cannot erase it.
44
+ owner.exec('COMMIT');
45
+ owner.exec('BEGIN EXCLUSIVE');
46
+ if (owner.prepare('SELECT deployment_id FROM workflow_owner WHERE id=1').get()?.deployment_id !== deploymentId) throw new Error('The workflow deployment ownership changed before acquiring its lifetime lock.');
47
+ } catch (cause) {
48
+ owner.close();
49
+ if (cause instanceof Error && /deployment|implicit adoption/u.test(cause.message)) throw cause;
50
+ throw new Error('The Node workflow data directory already has an active owner.', { cause });
51
+ }
52
+ let unbind: (() => void) | undefined;
53
+ let closing = false;
54
+ const active = new Set<Promise<Response>>();
55
+ const submissions = new Set<Promise<void>>();
56
+ const world = createWorld({ dataDir: resolve(directory, 'local'), recoverActiveRuns: true });
57
+ world.getDeploymentId = async () => deploymentId;
58
+ try {
59
+ unbind = bindWorkflowRuntime(ticket => options.advance(validateWorkflowTicket(ticket, { deploymentId })));
60
+ setWorld(world);
61
+ const route = createFlowRoute();
62
+ world.registerHandler(getQueueTopicPrefix('workflow', resolveQueueNamespace()), request => {
63
+ if (closing) return Promise.resolve(new Response(null, { status: 503 }));
64
+ const delivery = route(request);
65
+ active.add(delivery);
66
+ void delivery.finally(() => active.delete(delivery)).catch(() => {});
67
+ return delivery;
68
+ });
69
+ } catch (error) {
70
+ await world.close?.();
71
+ unbind?.();
72
+ owner.close();
73
+ throw error;
74
+ }
75
+ function submit(value: WorkflowTicket, wake: boolean): Promise<void> {
76
+ if (closing) return Promise.reject(new Error('The Node workflow executor is closing.'));
77
+ const work = (async () => {
78
+ const ticket = validateWorkflowTicket(value, { deploymentId });
79
+ const id = await deriveWorkflowRunId(ticket);
80
+ const run = await start({ workflowId }, [ticket], { world: { ...world, createRunId: () => id } });
81
+ if (wake) await run.wakeUp();
82
+ })();
83
+ submissions.add(work);
84
+ void work.finally(() => submissions.delete(work)).catch(() => {});
85
+ return work;
86
+ }
87
+ let closed: Promise<void> | undefined;
88
+ return {
89
+ deploymentId,
90
+ async start() { await world.start?.(); },
91
+ enqueue: ticket => submit(ticket, false),
92
+ wake: ticket => submit(ticket, true),
93
+ close() {
94
+ return closed ??= (async () => {
95
+ closing = true;
96
+ await Promise.allSettled([...submissions]);
97
+ await world.close?.();
98
+ // close() stops future deliveries but SDK direct handlers can still be
99
+ // finishing. Keep Runtime, authorization and secrets alive until drained.
100
+ await Promise.allSettled([...active]);
101
+ unbind?.();
102
+ owner.close();
103
+ })();
104
+ },
105
+ };
106
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { WorkflowTicket, WorkflowAdvance } from '@sinestack/workflow-core';
2
+
3
+ type Advance = (ticket: WorkflowTicket) => Promise<WorkflowAdvance>;
4
+ // The compiler bundles steps separately. A process-global symbol keeps the
5
+ // trusted host callback identical in those bundles; it is never an HTTP port.
6
+ const key = Symbol.for('sine.workflow.runtime.v1');
7
+ const state = globalThis as typeof globalThis & { [key]?: Advance };
8
+
9
+ export function bindWorkflowRuntime(advance: Advance): () => void {
10
+ if (state[key]) throw new Error('A workflow runtime is already bound in this process.');
11
+ state[key] = advance;
12
+ return () => { if (state[key] === advance) delete state[key]; };
13
+ }
14
+
15
+ export async function advanceWorkflow(ticket: WorkflowTicket): Promise<WorkflowAdvance> {
16
+ const advance = state[key];
17
+ if (!advance) throw new Error('The trusted workflow runtime is unavailable.');
18
+ return advance(ticket);
19
+ }
package/src/step.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { validateWorkflowAdvance, type WorkflowTicket, type WorkflowAdvance } from '@sinestack/workflow-core';
2
+ import { advanceWorkflow } from './runtime.ts';
3
+
4
+ /** The runtime owner performs current authorization and durable phase deduplication on every invocation. */
5
+ export async function advanceRun(ticket: WorkflowTicket): Promise<WorkflowAdvance> {
6
+ 'use step';
7
+ const result: unknown = await advanceWorkflow(ticket);
8
+ return validateWorkflowAdvance(result);
9
+ }
10
+
11
+ // One attempt per durable step. The owner handles provider retries, and the
12
+ // fixed workflow handles host outages without implicitly replaying effects.
13
+ advanceRun.maxRetries = 0;
package/src/worker.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { WorkerEntrypoint, env } from 'cloudflare:workers';
2
+ import { start } from 'workflow/api';
3
+ import { setWorld } from 'workflow/runtime';
4
+ import { setupCloudflareWorld } from '@sinestack/workflow-world-cloudflare';
5
+ import { createFlowRoute } from '@sine-workflow/generated/flow';
6
+ import { modules } from '@sine-workflow/generated/assets';
7
+ import { deriveWorkflowRunId, validateWorkflowTicket, validateWorkflowAdvance, type WorkflowTicket, type WorkflowAdvance } from '@sinestack/workflow-core';
8
+ import { bindWorkflowRuntime } from './runtime.ts';
9
+
10
+ export { RunObject, StepRunner, StreamObject, TokenObject } from '@sinestack/workflow-world-cloudflare';
11
+ declare const __SINE_WORKFLOW_ID__: string;
12
+ declare const __SINE_WORKFLOW_DEPLOYMENT__: string;
13
+
14
+ const world = setupCloudflareWorld({ deploymentId: __SINE_WORKFLOW_DEPLOYMENT__, createFlowRoute, setWorld, quickjs: modules });
15
+ bindWorkflowRuntime(async (ticket: WorkflowTicket): Promise<WorkflowAdvance> => {
16
+ const binding = (env as Record<string, unknown>).SINE_WORKFLOW_RUNTIME;
17
+ if (typeof binding !== 'object' || binding === null || !('advanceWorkflow' in binding) || typeof binding.advanceWorkflow !== 'function') {
18
+ throw new Error('The private workflow runtime binding is unavailable.');
19
+ }
20
+ return validateWorkflowAdvance(await binding.advanceWorkflow(ticket));
21
+ });
22
+
23
+ /** Only a named private service binding can submit work. The public fetch surface is closed. */
24
+ export class WorkflowService extends WorkerEntrypoint {
25
+ private async submit(value: unknown, wake: boolean): Promise<void> {
26
+ const ticket = validateWorkflowTicket(value, { deploymentId: __SINE_WORKFLOW_DEPLOYMENT__ });
27
+ const id = await deriveWorkflowRunId(ticket);
28
+ const run = await start({ workflowId: __SINE_WORKFLOW_ID__ }, [ticket], { world: { ...world, createRunId: () => id } });
29
+ if (wake) await run.wakeUp();
30
+ }
31
+ async enqueue(value: unknown): Promise<void> { return this.submit(value, false); }
32
+ async wake(value: unknown): Promise<void> { return this.submit(value, true); }
33
+ }
34
+
35
+ export default { fetch(): Response { return new Response(null, { status: 404 }); } };
@@ -0,0 +1,20 @@
1
+ import { sleep } from 'workflow';
2
+ import type { WorkflowTicket } from '@sinestack/workflow-core';
3
+ import { advanceRun } from './step.ts';
4
+
5
+ /** Fixed project orchestration. Neither caller code nor provider payloads enter this workflow. */
6
+ export async function runWorkflow(ticket: WorkflowTicket): Promise<void> {
7
+ 'use workflow';
8
+ for (;;) {
9
+ try {
10
+ const result = await advanceRun(ticket);
11
+ if (result.kind === 'completed') return;
12
+ await sleep(new Date(result.wakeAt));
13
+ } catch {
14
+ // A temporarily unavailable state owner must not permanently fail the
15
+ // workflow after the SDK's finite step retries. Only the owner decides
16
+ // the business deadline and terminal outcome; retry its fenced advance.
17
+ await sleep('30s');
18
+ }
19
+ }
20
+ }