@sinestack/workflow-world-cloudflare 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,33 @@
1
- # Temporary Holding Version
1
+ # Cloudflare Workflow World
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
+ Maintained source adaptation of vercel/workflow PR #4682 at `a555966986af83b94cb77d1d427dfdb18a2732cc`, using `workflow` / `@workflow/core` 5.2.3, World 5.0.5, errors 5.0.5, utils 5.0.2 and QuickJS WASI 3.4.0. See `THIRD_PARTY_NOTICES.md`, `SOURCE_ORIGINS.json` and `LICENSE.workflow.txt`.
4
+
5
+ ## Host contract
6
+
7
+ At module scope call `setupCloudflareWorld({ deploymentId, createFlowRoute, setWorld, quickjs, deliveryTimeoutMs? })`. It returns the actual SDK `World`, installs the static QuickJS compiled-assets singleton and passes that World to `setWorld`. `createFlowRoute` must create a fresh SDK route from the build-generated workflow code, not return a shared previously created handler. `quickjs` contains compiled `WebAssembly.Module` values for `quickjs`, `encoding`, `headers`, `url`, and `structuredClone`. Export `RunObject`, `TokenObject`, `StreamObject`, and the named Worker entrypoint `StepRunner` from the host module.
8
+
9
+ Bindings are `WORKFLOW_RUNS`, `WORKFLOW_TOKENS`, `WORKFLOW_STREAMS`, all using SQLite-backed Durable Object namespaces. Configure `nodejs_compat`, `enable_ctx_exports`, `WORKFLOW_VM=quickjs`, and a `WORKFLOW_ENCRYPTION_SECRET` containing base64-encoded 32 random bytes. The secret is required and must remain stable for the lifetime of the release's runs. It is read from the current Cloudflare environment; neither namespaces nor request environment are captured at setup. `createCloudflareWorld()` is exported for another caller needing the same configured runtime.
10
+
11
+ Workers storage/RPC types are explicit type-only imports from `@cloudflare/workers-types`; do not add a global triple-slash reference in this mixed DOM/Node repository. The narrow `cloudflare:workers` declarations forward official runtime export types and complement the host's existing `DurableObject` declaration.
12
+
13
+ `deploymentId` identifies an immutable executor build. Deploy each release to a distinct Worker service and distinct DO namespaces; retain the old executor and its secrets until its runs drain. The adapter does not select a newer release or migrate old code. The trusted host selects the release-specific service. Wrong-release creation, enqueue and invoke reject with `DEPLOYMENT_MISMATCH`; already persisted mismatched runs receive a `run_failed` event with that error code instead of remaining indefinitely held.
14
+
15
+ ## Durable behavior
16
+
17
+ Each run has a serialized event-mutation boundary, a dense 1-based event-slot journal and an in-memory projection reconstructed exclusively from its committed log. Multiple events appended by a store operation persist in one synchronous transaction. Stale writers receive the skipped committed slots. Cross-run hook token ownership uses serialized claims plus the run's liveness fence; hook disposal and terminal events remove the projected hook. Required hook lookup/listing, run reads/listing, steps, events, streams and queue methods are implemented. Run cancellation and hook disposal use SDK events rather than separate mutable entity APIs.
18
+
19
+ `runs.list` and unscoped `hooks.list` use a durable ID directory in the reserved `directory:runs` object inside `WORKFLOW_RUNS`, then read authoritative entities from each run. Registration precedes run creation; an interrupted registration cannot hide a committed run. This is a correct small-deployment operational listing, not an indexed analytics service: scanning all runs incurs proportional RPC and memory costs and can encounter Worker subrequest limits. Keep analytics and high-volume operator querying outside this adapter until a separately designed indexed backend is provided.
20
+
21
+ Queue signals and idempotency references persist before acknowledgment with an alarm backstop. Duplicate wakes for terminal runs are ignored. Flow delivery is single-runner; queued steps use separate named Worker RPC invocations. Retry attempts use capped exponential backoff and park after 100 failed/interrupted attempts. `RunObject.inspect()` exposes parked reasons for operator inspection. `RunObject.reset()` is a trusted RPC eviction hook; do not expose these methods through public HTTP.
22
+
23
+ Delivery defaults to 120 seconds and can be configured with `deliveryTimeoutMs`. On timeout the run object stops scheduling new work, persists the retry/backoff, arms an alarm, flushes storage, then aborts the instance. Its successor creates a fresh route and reconstructs the journal; an old never-settling handler cannot keep the new runner permanently busy. A step Worker RPC itself cannot be forcibly cancelled by the owning DO. Host effect execution must therefore have a shorter bounded deadline and a durable phase/lease ledger that reconciles uncertain effects; a timeout is never proof that an external effect did not occur. Each consumer runtime owns that ledger, not the World.
24
+
25
+ Snapshots store the SDK metadata+bytes envelope transactionally in bounded chunks. Streams preserve ordered chunks, closure, negative indexes and polling readers. Encryption protects SDK payloads and snapshots; metadata, IDs and operational state remain available to trusted namespace access.
26
+
27
+ Explicit invocation idempotency keys use a per-key singleflight boundary. Hook receipt, accepted outcome and wake signal commit together; the journal's resume identity survives cold reconstruction. A cached accepted reply repairs wake publication rather than re-executing the input handler. This does not advertise the wider optional SDK hook-retention/force-claim contract.
28
+
29
+ ## Capabilities and verification
30
+
31
+ `invoke` is supported. Optional batch writes, retained/force-claimed/deduplicated hooks, dynamic user-supplied workflow code, analytics, attribute updates and long-poll run status are not advertised. Their absence is intentional, not a throwing required-method stub. Runtime replay continues to use the conservative SDK paths.
32
+
33
+ This package exports TypeScript source and needs no standalone build. `@sinestack/workflow-sdk/build` owns bundling, static Wasm imports and pinned compatibility transforms; each consumer supplies deployment bindings and effect-code identity inputs. Journal/dense-slot/replay and delivery-deadline regressions run in the root test gate. `packages/sdk/test/cloudflare.test.ts` runs the actual SDK/QuickJS executor and an offline product-ledger fixture in workerd with SQLite persistence and private bindings, restarts both workers, and verifies one effect and one terminal state. SinePowers retains its product-specific Firecrawl/usage integration test. This does not establish live provider or cloud deployment verification. The pinned SDK QuickJS singleton is an internal API: changing SDK versions requires re-review, not a floating dependency update.
@@ -0,0 +1,92 @@
1
+ {
2
+ "repository": "https://github.com/vercel/workflow",
3
+ "pullRequest": 4682,
4
+ "commit": "a555966986af83b94cb77d1d427dfdb18a2732cc",
5
+ "license": "Apache-2.0",
6
+ "licenseFile": "LICENSE.workflow.txt",
7
+ "files": [
8
+ {
9
+ "path": "packages/world-cloudflare/src/cloudflare.d.ts",
10
+ "upstreamPath": "packages/world-cloudflare/src/cloudflare.d.ts",
11
+ "upstreamSha256": "6c5d246048bd24759e9c95c03e4e974010b562be0148a80909d5e26187bb1f12",
12
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/cloudflare.d.ts"
13
+ },
14
+ {
15
+ "path": "packages/world-cloudflare/src/encryption.ts",
16
+ "upstreamPath": "packages/world-cloudflare/src/encryption.ts",
17
+ "upstreamSha256": "f6c7639322ab7a4ad9f107fc7206d561ce2d21a131dbc48094331d61b96bcf80",
18
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/encryption.ts"
19
+ },
20
+ {
21
+ "path": "packages/world-cloudflare/src/index.ts",
22
+ "upstreamPath": "packages/world-cloudflare/src/index.ts",
23
+ "upstreamSha256": "664942902f71e9ddd49aadd1f27497f4bfbe690d041e7967807f75a968aaf087",
24
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/index.ts"
25
+ },
26
+ {
27
+ "path": "packages/world-cloudflare/src/quickjs.ts",
28
+ "upstreamPath": "packages/world-cloudflare/src/quickjs.ts",
29
+ "upstreamSha256": "dee6ec4a9572ac0597fe02fd63d0f0773c785a1ef60301ab2cb8ae1373759a54",
30
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/quickjs.ts"
31
+ },
32
+ {
33
+ "path": "packages/world-cloudflare/src/rpc.ts",
34
+ "upstreamPath": "packages/world-cloudflare/src/rpc.ts",
35
+ "upstreamSha256": "82fd48fd50b611218edfd255d242dc8bb863af17177e97b5fdfb06f137a7b33f",
36
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/rpc.ts"
37
+ },
38
+ {
39
+ "path": "packages/world-cloudflare/src/run-object.ts",
40
+ "upstreamPath": "packages/world-cloudflare/src/run-object.ts",
41
+ "upstreamSha256": "148a55eb1c89cccf181810258e646b815c47755f20cd56da8a0dd27a16af1ab2",
42
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/run-object.ts"
43
+ },
44
+ {
45
+ "path": "packages/world-cloudflare/src/runtime.ts",
46
+ "upstreamPath": "packages/world-cloudflare/src/runtime.ts",
47
+ "upstreamSha256": "c77696eced96f0a2a87417596242b9be491c9b993211d3efb8830dfc340f6e47",
48
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/runtime.ts"
49
+ },
50
+ {
51
+ "path": "packages/world-cloudflare/src/step-runner.ts",
52
+ "upstreamPath": "packages/world-cloudflare/src/step-runner.ts",
53
+ "upstreamSha256": "ef16b5f3a2209975dea0ddf6b64ae06215dbc3b5d41b76e9f6ec3372935599a2",
54
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/step-runner.ts"
55
+ },
56
+ {
57
+ "path": "packages/world-cloudflare/src/stream-object.ts",
58
+ "upstreamPath": "packages/world-cloudflare/src/stream-object.ts",
59
+ "upstreamSha256": "58ae1ad44fbde0631be5ae45de09d9286a91598b694f7fd7c0d7c0780fb00dec",
60
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/stream-object.ts"
61
+ },
62
+ {
63
+ "path": "packages/world-cloudflare/src/token-object.ts",
64
+ "upstreamPath": "packages/world-cloudflare/src/token-object.ts",
65
+ "upstreamSha256": "76f244be433546dbb94f284ad79842b8140e07622baff6c6d2be04faa09ad6d6",
66
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/token-object.ts"
67
+ },
68
+ {
69
+ "path": "packages/world-cloudflare/src/world.ts",
70
+ "upstreamPath": "packages/world-cloudflare/src/world.ts",
71
+ "upstreamSha256": "cee256e538fa1f44e10aa2d3649cbd1b2ca1244d4c5408b27d3046d60cef95f5",
72
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-cloudflare/src/world.ts"
73
+ },
74
+ {
75
+ "path": "packages/world-cloudflare/src/store/ids.ts",
76
+ "upstreamPath": "packages/world-sim/src/ids.ts",
77
+ "upstreamSha256": "0b993eea898d7bba23758f2a03e9aa014e21913b78aa740d24d8a59fa626b4c2",
78
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-sim/src/ids.ts"
79
+ },
80
+ {
81
+ "path": "packages/world-cloudflare/src/store/store.ts",
82
+ "upstreamPath": "packages/world-sim/src/store.ts",
83
+ "upstreamSha256": "3f214bc677c4f5d19ab00e62a689018552415d602b6f4631f397ecec8bad9faf",
84
+ "url": "https://github.com/vercel/workflow/blob/a555966986af83b94cb77d1d427dfdb18a2732cc/packages/world-sim/src/store.ts"
85
+ }
86
+ ],
87
+ "extractedFrom": {
88
+ "repository": "https://github.com/fei-bai-inc/sine-powers",
89
+ "commit": "09f80f7463c07f17bc53ad7a80717214433b9211",
90
+ "path": "packages/workflow-cloudflare"
91
+ }
92
+ }
@@ -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.
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@sinestack/workflow-world-cloudflare",
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": "Apache-2.0",
6
+ "description": "Durable Object workflow journal, recovery and private execution for Cloudflare Workers.",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/fei-bai-inc/workflow.git",
10
+ "directory": "packages/world-cloudflare"
11
+ },
12
+ "homepage": "https://github.com/fei-bai-inc/workflow/tree/main/packages/world-cloudflare#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/fei-bai-inc/workflow/issues"
15
+ },
16
+ "publishConfig": {
17
+ "registry": "https://registry.npmjs.org"
18
+ },
19
+ "exports": {
20
+ ".": "./src/index.ts",
21
+ "./package.json": "./package.json"
22
+ },
23
+ "dependencies": {
24
+ "@cloudflare/workers-types": "5.20261006.1",
25
+ "@workflow/core": "5.2.3",
26
+ "@workflow/errors": "5.0.5",
27
+ "@workflow/utils": "5.0.2",
28
+ "@workflow/world": "5.0.5",
29
+ "quickjs-wasi": "3.4.0",
30
+ "ulid": "3.0.1",
31
+ "workflow": "5.2.3"
32
+ },
33
+ "files": [
34
+ "src",
35
+ "README.md",
36
+ "THIRD_PARTY_NOTICES.md",
37
+ "LICENSE.workflow.txt",
38
+ "SOURCE_ORIGINS.json"
39
+ ]
6
40
  }
@@ -0,0 +1,6 @@
1
+ /** Bind only runtime module exports to their official types; retain DOM/Node globals. */
2
+ declare module 'cloudflare:workers' {
3
+ export const DurableObject: typeof import('@cloudflare/workers-types').CloudflareWorkersModule.DurableObject;
4
+ export const WorkerEntrypoint: typeof import('@cloudflare/workers-types').CloudflareWorkersModule.WorkerEntrypoint;
5
+ export const env: typeof import('@cloudflare/workers-types').CloudflareWorkersModule.env;
6
+ }
@@ -0,0 +1,71 @@
1
+ import { WorkflowRunNotFoundError, WorkflowWorldError } from '@workflow/errors';
2
+ import type { Hook, ListHooksParams, ListWorkflowRunsParams, PaginatedResponse, PaginationOptions, WorkflowRun, WorkflowRunWithoutData } from '@workflow/world';
3
+ import { call, RUNS_BINDING } from './rpc.ts';
4
+
5
+ /** Reserved object in the release's WORKFLOW_RUNS namespace. Only IDs live here. */
6
+ export const DIRECTORY_NAME = 'directory:runs';
7
+
8
+ export async function registerRun(runId: string): Promise<void> {
9
+ await call(RUNS_BINDING, DIRECTORY_NAME, 'registerRun', runId);
10
+ }
11
+
12
+ async function* runIds(): AsyncGenerator<string> {
13
+ let cursor: string | undefined;
14
+ do {
15
+ const page = await call<{ ids: string[]; cursor: string | null }>(
16
+ RUNS_BINDING, DIRECTORY_NAME, 'listRunIds', cursor,
17
+ );
18
+ yield* page.ids;
19
+ cursor = page.cursor ?? undefined;
20
+ } while (cursor !== undefined);
21
+ }
22
+
23
+ function paginate<T extends { createdAt: Date }>(rows: T[], id: (row: T) => string, options?: PaginationOptions): PaginatedResponse<T> {
24
+ const limit = options?.limit ?? 20;
25
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000) {
26
+ throw new WorkflowWorldError('Pagination limit must be between 1 and 1000', { status: 400 });
27
+ }
28
+ const key = (row: T) => `${new Date(row.createdAt).toISOString()}|${id(row)}`;
29
+ const asc = options?.sortOrder === 'asc';
30
+ rows.sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0) * (asc ? 1 : -1));
31
+ const cursor = options?.cursor;
32
+ const eligible = cursor ? rows.filter(row => asc ? key(row) > cursor : key(row) < cursor) : rows;
33
+ const data = eligible.slice(0, limit);
34
+ const last = data.at(-1);
35
+ return { data, hasMore: eligible.length > limit, cursor: last ? key(last) : null };
36
+ }
37
+
38
+ export function listRuns(params: ListWorkflowRunsParams & { resolveData: 'none' }): Promise<PaginatedResponse<WorkflowRunWithoutData>>;
39
+ export function listRuns(params?: ListWorkflowRunsParams & { resolveData?: 'all' }): Promise<PaginatedResponse<WorkflowRun>>;
40
+ export function listRuns(params?: ListWorkflowRunsParams): Promise<PaginatedResponse<WorkflowRun | WorkflowRunWithoutData>>;
41
+ export async function listRuns(params?: ListWorkflowRunsParams): Promise<PaginatedResponse<WorkflowRun | WorkflowRunWithoutData>> {
42
+ const rows: (WorkflowRun | WorkflowRunWithoutData)[] = [];
43
+ for await (const id of runIds()) {
44
+ try {
45
+ const run = await call<WorkflowRun | WorkflowRunWithoutData>(RUNS_BINDING, id, 'call', 'runsGet', [id, { resolveData: params?.resolveData ?? 'all' }]);
46
+ if (params?.workflowName !== undefined && run.workflowName !== params.workflowName) continue;
47
+ if (params?.status !== undefined && !(Array.isArray(params.status) ? params.status.includes(run.status) : run.status === params.status)) continue;
48
+ rows.push(run);
49
+ } catch (error) {
50
+ // IDs register before run creation: an interrupted creation is not a run.
51
+ if (!WorkflowRunNotFoundError.is(error)) throw error;
52
+ }
53
+ }
54
+ return paginate(rows, run => run.runId, params?.pagination);
55
+ }
56
+
57
+ export async function listAllHooks(params: ListHooksParams): Promise<PaginatedResponse<Hook>> {
58
+ const rows: Hook[] = [];
59
+ for await (const id of runIds()) {
60
+ let cursor: string | undefined;
61
+ do {
62
+ const page = await call<PaginatedResponse<Hook>>(RUNS_BINDING, id, 'call', 'hooksList', [{
63
+ runId: id, resolveData: params.resolveData ?? 'all',
64
+ pagination: { limit: 1000, sortOrder: 'asc', ...(cursor ? { cursor } : {}) },
65
+ }]);
66
+ rows.push(...page.data);
67
+ cursor = page.hasMore ? page.cursor ?? undefined : undefined;
68
+ } while (cursor !== undefined);
69
+ }
70
+ return paginate(rows, hook => hook.hookId, params.pagination);
71
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Per-run encryption keys: HKDF-SHA256 over a Worker secret, with the run id
3
+ * as context, the same construction `@workflow/world-vercel` uses with its
4
+ * deployment key. Core encrypts run payloads with the key and, because a run
5
+ * has one, also encrypts VM snapshots (it refuses to store them unencrypted).
6
+ *
7
+ * The required secret is `WORKFLOW_ENCRYPTION_SECRET` (base64, 32 bytes).
8
+ * Read the current Workers binding on every call so binding overrides and
9
+ * environment selection cannot reuse another environment's cached secret.
10
+ */
11
+ import type { WorkflowRun } from '@workflow/world';
12
+ import { env } from 'cloudflare:workers';
13
+
14
+ function secretBytes(): Uint8Array<ArrayBuffer> {
15
+ const raw: unknown = Reflect.get(env, 'WORKFLOW_ENCRYPTION_SECRET');
16
+ if (typeof raw !== 'string' || raw.length === 0) {
17
+ throw new Error('WORKFLOW_ENCRYPTION_SECRET is required');
18
+ }
19
+ let decoded: string;
20
+ try {
21
+ decoded = atob(raw);
22
+ } catch {
23
+ throw new Error('WORKFLOW_ENCRYPTION_SECRET must be 32 bytes of base64');
24
+ }
25
+ if (decoded.length !== 32) {
26
+ throw new Error('WORKFLOW_ENCRYPTION_SECRET must be 32 bytes of base64');
27
+ }
28
+ return Uint8Array.from(decoded, (character) => character.charCodeAt(0));
29
+ }
30
+
31
+ export async function getEncryptionKeyForRun(
32
+ run: WorkflowRun | string
33
+ ): Promise<Uint8Array<ArrayBuffer>> {
34
+ const secret = secretBytes();
35
+ const runId = typeof run === 'string' ? run : run.runId;
36
+ const base = await crypto.subtle.importKey('raw', secret, 'HKDF', false, [
37
+ 'deriveBits',
38
+ ]);
39
+ const bits = await crypto.subtle.deriveBits(
40
+ {
41
+ name: 'HKDF',
42
+ hash: 'SHA-256',
43
+ salt: new Uint8Array(32),
44
+ info: new TextEncoder().encode(`workflow-cloudflare|${runId}`),
45
+ },
46
+ base,
47
+ 256
48
+ );
49
+ return new Uint8Array(bits);
50
+ }
package/src/index.ts ADDED
@@ -0,0 +1,53 @@
1
+ /// <reference path="./cloudflare.d.ts" />
2
+ /**
3
+ * Maintained Cloudflare Workflow World: each workflow run is a Durable Object
4
+ * that owns its journal and executes its pinned workflow build.
5
+ *
6
+ * A Worker using it must:
7
+ * - call `setupCloudflareWorld()` at module scope with its build's
8
+ * deployment id, the generated workflow route, and the QuickJS modules;
9
+ * - re-export `RunObject`, `TokenObject`, `StreamObject` and `StepRunner`
10
+ * from its entrypoint, bound as `WORKFLOW_RUNS`, `WORKFLOW_TOKENS` and
11
+ * `WORKFLOW_STREAMS`;
12
+ * - run with `WORKFLOW_VM=quickjs` and the `nodejs_compat` and
13
+ * `enable_ctx_exports` compatibility flags.
14
+ */
15
+ import { installQuickJSModules, type QuickJSModules } from './quickjs.ts';
16
+ import { configureRuntime, type FlowRoute } from './runtime.ts';
17
+ import { createCloudflareWorld } from './world.ts';
18
+
19
+ export { RunObject } from './run-object.ts';
20
+ export { StepRunner } from './step-runner.ts';
21
+ export { StreamObject } from './stream-object.ts';
22
+ export { TokenObject } from './token-object.ts';
23
+ export { createCloudflareWorld };
24
+ export type { QuickJSModules };
25
+
26
+ export interface SetupOptions {
27
+ deploymentId: string;
28
+ /** `createFlowRoute` from the statically generated workflow bundle. */
29
+ createFlowRoute: () => FlowRoute;
30
+ quickjs: QuickJSModules;
31
+ /** Default 120 seconds. Must exceed the host's bounded step-effect budget. */
32
+ deliveryTimeoutMs?: number;
33
+ /** `setWorld` from `workflow/runtime`, so the World becomes the active one. */
34
+ setWorld: (world: ReturnType<typeof createCloudflareWorld>) => void;
35
+ }
36
+
37
+ /** Wire the World into this isolate. Safe at module scope (no I/O). */
38
+ export function setupCloudflareWorld(options: SetupOptions) {
39
+ if (!options.deploymentId.trim()) throw new Error('A nonempty immutable deploymentId is required');
40
+ const deliveryTimeoutMs = options.deliveryTimeoutMs ?? 120_000;
41
+ if (!Number.isSafeInteger(deliveryTimeoutMs) || deliveryTimeoutMs < 1000) {
42
+ throw new Error('deliveryTimeoutMs must be an integer of at least 1000');
43
+ }
44
+ installQuickJSModules(options.quickjs);
45
+ configureRuntime({
46
+ deploymentId: options.deploymentId,
47
+ createFlowRoute: options.createFlowRoute,
48
+ deliveryTimeoutMs,
49
+ });
50
+ const world = createCloudflareWorld();
51
+ options.setWorld(world);
52
+ return world;
53
+ }
package/src/quickjs.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Supply precompiled QuickJS WebAssembly modules to `@workflow/core`.
3
+ *
4
+ * Workers forbid compiling WebAssembly from bytes at runtime, which is what
5
+ * core does by default (`WebAssembly.compile(quickjsWasm)`). Wrangler instead
6
+ * compiles `.wasm`/`.so` imports at deploy time and hands the Worker
7
+ * `WebAssembly.Module`s. Core caches its compiled assets in a process-wide
8
+ * singleton; seeding that singleton with these modules makes core skip its own
9
+ * compile step.
10
+ *
11
+ * The singleton identity and shape mirror SDK 5.2.3's `getCompiledAssets()`.
12
+ * Mutate its shared state rather than replacing it: core may already hold
13
+ * a reference to the singleton when the Worker installs its static modules.
14
+ */
15
+ import { globalSingleton } from '@workflow/utils';
16
+
17
+ export interface QuickJSModules {
18
+ quickjs: WebAssembly.Module;
19
+ encoding: WebAssembly.Module;
20
+ headers: WebAssembly.Module;
21
+ url: WebAssembly.Module;
22
+ structuredClone: WebAssembly.Module;
23
+ }
24
+
25
+ interface CompiledAssets {
26
+ wasm: WebAssembly.Module;
27
+ extensions: {
28
+ name: string;
29
+ wasm: WebAssembly.Module;
30
+ initFn?: string;
31
+ }[];
32
+ }
33
+
34
+ const quickjsAssets = globalSingleton(
35
+ '@workflow/core//quickjsCompiledAssets',
36
+ 1,
37
+ (): { promise: Promise<CompiledAssets> | undefined } => ({
38
+ promise: undefined,
39
+ })
40
+ );
41
+
42
+ export function installQuickJSModules(modules: QuickJSModules): void {
43
+ quickjsAssets.promise = Promise.resolve({
44
+ wasm: modules.quickjs,
45
+ extensions: [
46
+ { name: 'encoding', wasm: modules.encoding },
47
+ { name: 'headers', wasm: modules.headers },
48
+ { name: 'url', wasm: modules.url },
49
+ {
50
+ name: 'structured-clone',
51
+ wasm: modules.structuredClone,
52
+ initFn: 'qjs_ext_structured_clone_init',
53
+ },
54
+ ],
55
+ });
56
+ }