From ad90cf5b257be01ba0332e35c946902ace5e7589 Mon Sep 17 00:00:00 2001
From: Ryan Lee
Date: Tue, 6 Oct 2026 03:36:33 +0000
Subject: [PATCH 001/112] feat(global): import statelyai/xstate v6 packages
verbatim
Six packages of statelyai/xstate branch `next` at
2146ae26ebfc7e6a624b3a1f237f9e6ddc30b9f5 (MIT, Copyright (c) 2015 David
Khourshid) are copied unchanged under packages/xstate/, as owned members
(REPO-O1). Upstream is a reference, never a merge source.
- packages/core -> packages/xstate/xstate
- packages/xstate-effect -> packages/xstate/xstate-effect
- packages/xstate-test -> packages/xstate/xstate-test
- packages/xstate-react -> packages/xstate/xstate-react
- packages/xstate-store -> packages/xstate/xstate-store
- packages/xstate-store-react -> packages/xstate/xstate-store-react
Identity: every copied src/ and test/ tree object equals the upstream tree
object at the pin (git write-tree --prefix vs git rev-parse :),
except xstate-store/test, which differs only by the excluded files below.
Excluded (build configuration, or tests of bindings this repo does not fork):
- packages/{core,xstate-effect,xstate-test,xstate-react,xstate-store,xstate-store-react}/vitest.config.mts
- packages/xstate-store/vitest.config.vue.mts, vitest.config.solid.mts
- packages/xstate-store/test/{vue.test.ts,UseActor.vue,UseActorRef.vue,UseSelector.vue} (imports @xstate/vue)
- packages/core/{actors,durable,fsm,graph,validation}/package.json (preconstruct entrypoint stubs)
- packages/core/.gitignore, packages/xstate-store-react/tsconfig.json
Added: the repository's root MIT LICENSE in xstate-effect and
xstate-store-react, which upstream ships without a package LICENSE.
Declared bypass (CONST-W3): committed with --no-verify. The pre-commit hook
runs dprint fmt over staged files, which would rewrite upstream sources and
break the tree identity above. The commit message was checked with
`pnpm exec commitlint`. Formatting lands as the next, separate commit; the
dprint check gate runs on the pull request head.
---
xstate-effect/CHANGELOG.md | 105 +
xstate-effect/LICENSE | 22 +
xstate-effect/README.md | 265 +
xstate-effect/docs/actors.md | 236 +
xstate-effect/docs/atoms-and-react.md | 248 +
xstate-effect/docs/effect-logic.md | 183 +
xstate-effect/docs/matching-states.md | 125 +
xstate-effect/docs/meta.json | 13 +
xstate-effect/docs/observing-actors.md | 228 +
xstate-effect/docs/quick-start.md | 152 +
xstate-effect/docs/schemas-and-actions.md | 171 +
xstate-effect/docs/testing-and-errors.md | 198 +
xstate-effect/package.json | 47 +
xstate-effect/src/actor.test.ts | 459 +
xstate-effect/src/actor.ts | 415 +
xstate-effect/src/actorScope.ts | 16 +
xstate-effect/src/atom.test.ts | 264 +
xstate-effect/src/atom.ts | 176 +
xstate-effect/src/brands.ts | 3 +
xstate-effect/src/createEffectActor.ts | 407 +
xstate-effect/src/effectActor.ts | 265 +
xstate-effect/src/errors.ts | 43 +
xstate-effect/src/fromEffect.ts | 709 ++
xstate-effect/src/index.test.ts | 875 ++
xstate-effect/src/index.ts | 52 +
xstate-effect/src/internal.ts | 291 +
xstate-effect/src/lint.test.ts | 108 +
xstate-effect/src/persistence.test.ts | 657 ++
xstate-effect/src/requirements.types.test.ts | 335 +
xstate-effect/src/runtime.test.ts | 1198 ++
xstate-effect/src/schema.ts | 214 +
xstate-effect/src/setupEffect.ts | 423 +
xstate-effect/src/state.test.ts | 154 +
xstate-effect/src/state.ts | 133 +
xstate-effect/src/types.ts | 111 +
.../test/lint-fixtures/declared-effect.ts | 26 +
.../test/lint-fixtures/inline-effect.ts | 28 +
.../test/lint-fixtures/oxlintrc.fixtures.json | 10 +
xstate-react/CHANGELOG.md | 1067 ++
xstate-react/LICENSE | 22 +
xstate-react/README.md | 52 +
xstate-react/docs/global-state.md | 108 +
xstate-react/docs/input-and-snapshots.md | 118 +
xstate-react/docs/meta.json | 12 +
xstate-react/docs/selectors.md | 118 +
xstate-react/docs/server-rendering.md | 102 +
xstate-react/docs/shared-actors.md | 161 +
xstate-react/docs/testing.md | 143 +
xstate-react/docs/use-machine.md | 140 +
xstate-react/package.json | 80 +
xstate-react/src/createActorContext.ts | 84 +
xstate-react/src/false.ts | 1 +
xstate-react/src/index.ts | 8 +
xstate-react/src/shallowEqual.ts | 37 +
xstate-react/src/true.ts | 1 +
xstate-react/src/useActor.ts | 72 +
xstate-react/src/useActorRef.ts | 144 +
xstate-react/src/useMachine.ts | 22 +
xstate-react/src/useSelector.ts | 56 +
xstate-react/test/createActorContext.test.tsx | 545 +
.../test/fastRefresh.production.test.tsx | 47 +
xstate-react/test/fastRefresh.test.tsx | 285 +
xstate-react/test/issueRegressions.test.tsx | 137 +
.../lint-fixtures/machine-in-component.tsx | 45 +
.../machine-outside-component.tsx | 21 +
.../test/lint-fixtures/oxlintrc.fixtures.json | 10 +
xstate-react/test/lint.test.ts | 92 +
xstate-react/test/types.test.tsx | 270 +
xstate-react/test/useActor.test.tsx | 1019 ++
xstate-react/test/useActorRef.test.tsx | 645 ++
xstate-react/test/useSelector.test.tsx | 1022 ++
xstate-react/test/utils.tsx | 37 +
xstate-store-react/CHANGELOG.md | 133 +
xstate-store-react/LICENSE | 22 +
xstate-store-react/README.md | 187 +
xstate-store-react/package.json | 50 +
xstate-store-react/src/index.test.tsx | 476 +
xstate-store-react/src/index.ts | 387 +
xstate-store-react/src/types.test.tsx | 251 +
xstate-store/CHANGELOG.md | 1752 +++
xstate-store/LICENSE | 22 +
xstate-store/MIGRATION.md | 439 +
xstate-store/README.md | 523 +
.../docs/effects-and-emitted-events.md | 61 +
xstate-store/docs/events-and-context.md | 82 +
xstate-store/docs/frameworks.md | 27 +
xstate-store/docs/meta.json | 14 +
xstate-store/docs/migration.md | 21 +
xstate-store/docs/persistence.md | 48 +
xstate-store/docs/quick-start.md | 62 +
xstate-store/docs/selectors.md | 57 +
xstate-store/docs/typescript.md | 32 +
xstate-store/docs/undo-redo.md | 43 +
xstate-store/package.json | 64 +
xstate-store/src/alien.ts | 654 ++
xstate-store/src/atom.ts | 420 +
xstate-store/src/fromStore.ts | 337 +
xstate-store/src/index.ts | 72 +
xstate-store/src/persist.ts | 1083 ++
xstate-store/src/reset.ts | 96 +
xstate-store/src/schema.ts | 77 +
xstate-store/src/select.test.ts | 243 +
xstate-store/src/shallowEqual.ts | 37 +
xstate-store/src/store.ts | 869 ++
xstate-store/src/types.ts | 784 ++
xstate-store/src/undo.ts | 464 +
xstate-store/src/validate.ts | 266 +
xstate-store/src/validationError.ts | 9 +
xstate-store/test/atom.test.ts | 1045 ++
xstate-store/test/broadcast.test.ts | 194 +
xstate-store/test/fromStore.test.ts | 180 +
xstate-store/test/persist.test.ts | 1565 +++
xstate-store/test/reset.test.ts | 175 +
xstate-store/test/store.test.ts | 1555 +++
xstate-store/test/types.test.tsx | 520 +
xstate-store/test/undo.test.ts | 1244 +++
xstate-store/test/validate.test.ts | 347 +
xstate-test/CHANGELOG.md | 167 +
xstate-test/LICENSE | 21 +
xstate-test/README.md | 1813 +++
xstate-test/package.json | 61 +
xstate-test/src/adapter.ts | 525 +
xstate-test/src/effect-schema.ts | 64 +
xstate-test/src/engine/constants.ts | 2 +
xstate-test/src/engine/coverage.ts | 1196 ++
xstate-test/src/engine/deduplicatePaths.ts | 65 +
xstate-test/src/engine/eventDescriptors.ts | 245 +
xstate-test/src/engine/index.ts | 6 +
xstate-test/src/engine/outcomes.ts | 122 +
.../src/engine/propertyLinearizability.ts | 337 +
xstate-test/src/engine/propertyTest.ts | 4687 ++++++++
xstate-test/src/engine/report.ts | 930 ++
xstate-test/src/engine/suite.ts | 455 +
xstate-test/src/engine/testPaths.ts | 1021 ++
xstate-test/src/engine/utils.ts | 60 +
xstate-test/src/failures.ts | 156 +
xstate-test/src/index.ts | 115 +
xstate-test/src/pick.ts | 41 +
xstate-test/src/playwright.ts | 669 ++
xstate-test/src/propertyTest.ts | 424 +
xstate-test/src/scheduler.ts | 122 +
xstate-test/src/schema.ts | 1408 +++
xstate-test/src/vitest.ts | 321 +
xstate-test/test/advancedPropertyTest.test.ts | 908 ++
xstate-test/test/campaignAssertions.test.ts | 300 +
xstate-test/test/docsExamples.test.ts | 1431 +++
xstate-test/test/effectSchema.test.ts | 31 +
.../test/engine/perfPairsDedup.test.ts | 190 +
.../test/engine/propertyExecuted.test.ts | 202 +
.../test/engine/propertyExploration.test.ts | 262 +
.../engine/propertyLinearizability.test.ts | 232 +
.../test/engine/propertyRegressions.test.ts | 474 +
.../test/engine/propertyReplay.test.ts | 141 +
.../test/engine/propertyReport.test.ts | 160 +
.../test/engine/propertySearch.test.ts | 153 +
xstate-test/test/engine/propertySuite.test.ts | 198 +
xstate-test/test/engine/propertyTest.test.ts | 409 +
.../test/engine/propertyTestAdapter.ts | 219 +
xstate-test/test/engine/symmetry.test.ts | 183 +
xstate-test/test/engine/testPaths.test.ts | 520 +
.../engine/testPathsInternalEvents.test.ts | 218 +
.../test/engine/unifiedTestApi.test.ts | 137 +
xstate-test/test/executedEffects.test.ts | 197 +
xstate-test/test/exploration.test.ts | 202 +
xstate-test/test/failureDatabase.test.ts | 184 +
xstate-test/test/fakePage.ts | 245 +
xstate-test/test/fastCheckWrappers.test.ts | 143 +
.../test/pairsRequirementsWeights.test.ts | 224 +
xstate-test/test/pick.types.test.ts | 75 +
xstate-test/test/playwrightArtifacts.test.ts | 264 +
xstate-test/test/playwrightPage.types.test.ts | 29 +
xstate-test/test/playwrightSut.test.ts | 416 +
xstate-test/test/propertyTest.test.ts | 391 +
xstate-test/test/propertyTest.types.test.ts | 136 +
xstate-test/test/randomAdapter.ts | 201 +
xstate-test/test/reachability.test.ts | 196 +
xstate-test/test/reportingOptions.test.ts | 154 +
xstate-test/test/scheduler.test.ts | 163 +
xstate-test/test/schema.test.ts | 562 +
xstate-test/test/search.test.ts | 125 +
xstate-test/test/suite.test.ts | 72 +
xstate-test/test/symmetry.test.ts | 248 +
.../test/temporalPayloadsReplay.test.ts | 691 ++
xstate-test/test/vitest.test.ts | 186 +
xstate/CHANGELOG.md | 9765 +++++++++++++++++
xstate/LICENSE | 22 +
xstate/README.md | 637 ++
xstate/bin/xstate.js | 36 +
xstate/package.json | 155 +
xstate/src/IndexedHeap.ts | 65 +
xstate/src/Mailbox.ts | 57 +
xstate/src/SimulatedClock.ts | 89 +
xstate/src/State.ts | 809 ++
xstate/src/StateMachine.ts | 1858 ++++
xstate/src/StateNode.ts | 736 ++
xstate/src/actions.ts | 66 +
xstate/src/actorScope.ts | 85 +
xstate/src/actorSource.ts | 26 +
xstate/src/actors/attached.ts | 116 +
xstate/src/actors/callback.ts | 314 +
xstate/src/actors/index.ts | 73 +
xstate/src/actors/listener.ts | 83 +
xstate/src/actors/logic.ts | 591 +
xstate/src/actors/observable.ts | 550 +
xstate/src/actors/promise.ts | 507 +
xstate/src/actors/subscription.ts | 103 +
xstate/src/assert.ts | 50 +
xstate/src/base.types.ts | 137 +
xstate/src/constants.ts | 15 +
xstate/src/createActor.ts | 1422 +++
xstate/src/createMachine.ts | 419 +
xstate/src/createMachineFromConfig.ts | 1110 ++
xstate/src/delay.ts | 65 +
xstate/src/devDiagnostics.ts | 162 +
xstate/src/durable/index.ts | 882 ++
xstate/src/effectDescriptor.ts | 206 +
xstate/src/eventUtils.ts | 128 +
xstate/src/false.ts | 1 +
xstate/src/fsm.ts | 481 +
xstate/src/fsm/index.ts | 17 +
xstate/src/graph/actorScope.ts | 16 +
xstate/src/graph/adjacency.ts | 153 +
xstate/src/graph/alterPath.ts | 33 +
xstate/src/graph/graph.ts | 256 +
xstate/src/graph/index.ts | 12 +
xstate/src/graph/pathFromEvents.ts | 96 +
xstate/src/graph/shortestPaths.ts | 140 +
xstate/src/graph/simplePaths.ts | 127 +
.../test/__snapshots__/graph.test.ts.snap | 1232 +++
xstate/src/graph/test/adjacency.test.ts | 104 +
xstate/src/graph/test/dieHard.test.ts | 217 +
xstate/src/graph/test/graph.test.ts | 895 ++
xstate/src/graph/test/index.test.ts | 171 +
xstate/src/graph/test/paths.test.ts | 212 +
xstate/src/graph/test/shortestPaths.test.ts | 181 +
.../graph/test/traversal-regressions.test.ts | 140 +
xstate/src/graph/types.test.ts | 182 +
xstate/src/graph/types.ts | 204 +
xstate/src/hotSwap.ts | 189 +
xstate/src/index.ts | 221 +
xstate/src/inertActorScope.ts | 291 +
xstate/src/inspection.ts | 133 +
xstate/src/inspectionAmbient.ts | 45 +
xstate/src/machine.schema.json | 393 +
xstate/src/machineVersion.types.ts | 61 +
xstate/src/machineVersions.ts | 576 +
xstate/src/mapState.ts | 93 +
xstate/src/memo.ts | 14 +
xstate/src/persistedSnapshot.schema.json | 144 +
xstate/src/persistedSnapshotFormat.ts | 65 +
xstate/src/remoteActorRef.ts | 141 +
xstate/src/reportUnhandledError.ts | 13 +
xstate/src/runtimeHelpers.ts | 202 +
xstate/src/schema.types.ts | 152 +
xstate/src/serialize.ts | 229 +
xstate/src/setup.ts | 5618 ++++++++++
xstate/src/snapshotActorRef.ts | 319 +
xstate/src/spawn.ts | 65 +
xstate/src/stateUtils.ts | 2980 +++++
xstate/src/symbolObservable.ts | 3 +
xstate/src/system.ts | 1093 ++
xstate/src/systemLogicMetadata.ts | 2 +
xstate/src/systemTransition.ts | 1137 ++
xstate/src/timerClock.ts | 15 +
xstate/src/toPromise.ts | 38 +
xstate/src/transition.ts | 353 +
xstate/src/transitionActions.ts | 1337 +++
xstate/src/true.ts | 1 +
xstate/src/types.ts | 3603 ++++++
xstate/src/types.v6.ts | 2399 ++++
xstate/src/typestates.types.ts | 107 +
xstate/src/utils.ts | 465 +
xstate/src/validation.ts | 14 +
xstate/src/validation.types.ts | 49 +
xstate/src/validation/index.ts | 419 +
xstate/src/waitFor.ts | 130 +
xstate/test/actions.test.ts | 4214 +++++++
xstate/test/activities.test.ts | 400 +
xstate/test/actor.test.ts | 2132 ++++
xstate/test/actorLogic.test.ts | 1578 +++
xstate/test/addressFirstIdentity.test.ts | 1584 +++
xstate/test/after.test.ts | 704 ++
xstate/test/assert.test.ts | 111 +
xstate/test/assert.v6.test.ts | 121 +
xstate/test/assign.test.ts | 264 +
xstate/test/asyncErrorSchema.types.test.ts | 131 +
xstate/test/asyncTransition.test.ts | 211 +
.../test/childCompletionEvents.types.test.ts | 125 +
xstate/test/choice.test.ts | 192 +
xstate/test/clock.test.ts | 148 +
xstate/test/conversion.test.ts | 70 +
xstate/test/createActor.test.ts | 281 +
xstate/test/createInvoke.test.ts | 841 ++
xstate/test/custom-interpreter.test.ts | 971 ++
xstate/test/declarations.test.ts | 233 +
xstate/test/deep.test.ts | 495 +
xstate/test/delayNames.types.test.ts | 161 +
xstate/test/deterministic.test.ts | 295 +
xstate/test/durable-adapters/inngest.test.ts | 180 +
xstate/test/durable-adapters/rivet.test.ts | 175 +
xstate/test/durable-address-first.test.ts | 657 ++
xstate/test/durable-adoption.test.ts | 346 +
xstate/test/durable-conformance.ts | 349 +
.../test/durable-event-journal-timers.test.ts | 185 +
.../test/durable-execution-identity.test.ts | 226 +
xstate/test/durable-execution.test.ts | 376 +
xstate/test/durable-inspection.test.ts | 80 +
xstate/test/durable-interpreter.test.ts | 395 +
xstate/test/durable-reference-host.test.ts | 223 +
xstate/test/durable-restore.test.ts | 544 +
xstate/test/emit.test.ts | 552 +
xstate/test/errorPrecedence.test.ts | 322 +
xstate/test/errors.test.ts | 1621 +++
xstate/test/event.test.ts | 149 +
xstate/test/eventBoundary.test.ts | 251 +
xstate/test/eventDescriptors.test.ts | 543 +
xstate/test/eventDescriptors.types.test.ts | 162 +
xstate/test/examples.6.16.test.ts | 57 +
xstate/test/examples.6.17.test.ts | 136 +
xstate/test/examples.6.6.test.ts | 63 +
xstate/test/examples.6.8.test.ts | 79 +
xstate/test/examples.6.9.test.ts | 108 +
xstate/test/examples.cd.test.ts | 89 +
xstate/test/final.test.ts | 1707 +++
xstate/test/firstTenMinutes.v6.test.ts | 198 +
.../declarations/created-invoke-inference.ts | 768 ++
.../fixtures/declarations/created-invoke.ts | 130 +
.../fixtures/declarations/narrowed-context.ts | 27 +
.../declarations/registered-child-consumer.ts | 19 +
.../declarations/registered-child-parent.ts | 68 +
.../fixtures/declarations/registered-child.ts | 42 +
.../fixtures/declarations/strict-targets.ts | 52 +
xstate/test/fsm-entrypoint.test.ts | 25 +
xstate/test/fsm.actor.test.ts | 79 +
xstate/test/fsm.differential.test.ts | 107 +
xstate/test/fsm.setup.test.ts | 221 +
xstate/test/fsm.test.ts | 132 +
xstate/test/fsm.types.test.ts | 147 +
xstate/test/guards.test.ts | 957 ++
xstate/test/history.test.ts | 1633 +++
xstate/test/id.test.ts | 216 +
xstate/test/initial.test.ts | 192 +
xstate/test/input.test.ts | 410 +
xstate/test/inspect.test.ts | 705 ++
xstate/test/inspection.conformance.v6.test.ts | 229 +
xstate/test/internalEvents.test.ts | 254 +
xstate/test/internalTransitions.test.ts | 432 +
xstate/test/interpreter.test.ts | 2161 ++++
xstate/test/invalid.test.ts | 166 +
xstate/test/invoke.test.ts | 3837 +++++++
xstate/test/issue5454.test.ts | 119 +
xstate/test/issueRegressions.test.ts | 291 +
xstate/test/issueRegressions.types.test.ts | 248 +
xstate/test/json.test.ts | 1236 +++
xstate/test/listen.test.ts | 728 ++
xstate/test/logger.test.ts | 46 +
xstate/test/logical-timers.test.ts | 297 +
xstate/test/machine.test.ts | 403 +
xstate/test/machineFromConfig.test.ts | 157 +
xstate/test/machineOutput.types.test.ts | 312 +
xstate/test/machineVersions.test.ts | 1159 ++
xstate/test/machineVersions.types.test.ts | 284 +
xstate/test/macrostepBound.test.ts | 107 +
xstate/test/mapState.test.ts | 523 +
xstate/test/match.test.ts | 122 +
xstate/test/memory.test.ts | 215 +
xstate/test/meta.test.ts | 721 ++
xstate/test/microstep.test.ts | 421 +
xstate/test/microstep.v6.test.ts | 175 +
xstate/test/multiple.test.ts | 160 +
xstate/test/multiple.v6.test.ts | 160 +
xstate/test/order.test.ts | 86 +
xstate/test/parallel.test.ts | 1666 +++
xstate/test/parallelConformance.test.ts | 147 +
xstate/test/persistedSnapshot.types.test.ts | 200 +
xstate/test/persistenceConformance.v6.test.ts | 779 ++
xstate/test/predictableExec.test.ts | 601 +
xstate/test/rehydration.test.ts | 663 ++
xstate/test/rehydration.v6.test.ts | 516 +
xstate/test/resolve.test.ts | 73 +
xstate/test/resolve.v6.test.ts | 73 +
xstate/test/restoreEventless.test.ts | 75 +
xstate/test/restoreTerminal.test.ts | 109 +
xstate/test/restored-effects.test.ts | 156 +
xstate/test/route.test.ts | 554 +
xstate/test/runtimeValidation.test.ts | 772 ++
xstate/test/runtimeValidation.types.test.ts | 190 +
xstate/test/select.test.ts | 332 +
.../test/serialization.conformance.v6.test.ts | 509 +
xstate/test/setup.test.ts | 297 +
xstate/test/setupStateContracts.test.ts | 2062 ++++
xstate/test/sourceTyping.types.test.ts | 344 +
xstate/test/spawn.test.ts | 25 +
xstate/test/spawn.types.test.ts | 198 +
xstate/test/spawnChild.test.ts | 208 +
xstate/test/state.test.ts | 551 +
xstate/test/stateIn.test.ts | 549 +
xstate/test/stateInput.persistence.test.ts | 187 +
xstate/test/stateInput.test.ts | 2533 +++++
xstate/test/strictTargets.types.test.ts | 376 +
xstate/test/system.test.ts | 765 ++
xstate/test/systemOnRejectedEvent.test.ts | 113 +
xstate/test/systemTransition.test.ts | 1003 ++
xstate/test/tags.test.ts | 148 +
xstate/test/timeout.test.ts | 705 ++
xstate/test/timers.persistence.test.ts | 305 +
xstate/test/toPromise.test.ts | 147 +
xstate/test/transient.test.ts | 877 ++
xstate/test/transition.test.ts | 3251 ++++++
xstate/test/transitionFunctions.test.ts | 106 +
xstate/test/trigger.test.ts | 126 +
xstate/test/typeHelpers.test.ts | 257 +
xstate/test/typeSchemas.test.ts | 380 +
xstate/test/typeStates.test.ts | 97 +
xstate/test/types.test.ts | 6891 ++++++++++++
xstate/test/unhandledEvents.test.ts | 120 +
xstate/test/utils.ts | 117 +
xstate/test/v5ConfigDiagnostics.test.ts | 291 +
xstate/test/v6.test.ts | 156 +
xstate/test/versioning.test.ts | 200 +
xstate/test/vizTypeFriction.types.test.ts | 67 +
xstate/test/waitFor.test.ts | 404 +
422 files changed, 186185 insertions(+)
create mode 100644 xstate-effect/CHANGELOG.md
create mode 100644 xstate-effect/LICENSE
create mode 100644 xstate-effect/README.md
create mode 100644 xstate-effect/docs/actors.md
create mode 100644 xstate-effect/docs/atoms-and-react.md
create mode 100644 xstate-effect/docs/effect-logic.md
create mode 100644 xstate-effect/docs/matching-states.md
create mode 100644 xstate-effect/docs/meta.json
create mode 100644 xstate-effect/docs/observing-actors.md
create mode 100644 xstate-effect/docs/quick-start.md
create mode 100644 xstate-effect/docs/schemas-and-actions.md
create mode 100644 xstate-effect/docs/testing-and-errors.md
create mode 100644 xstate-effect/package.json
create mode 100644 xstate-effect/src/actor.test.ts
create mode 100644 xstate-effect/src/actor.ts
create mode 100644 xstate-effect/src/actorScope.ts
create mode 100644 xstate-effect/src/atom.test.ts
create mode 100644 xstate-effect/src/atom.ts
create mode 100644 xstate-effect/src/brands.ts
create mode 100644 xstate-effect/src/createEffectActor.ts
create mode 100644 xstate-effect/src/effectActor.ts
create mode 100644 xstate-effect/src/errors.ts
create mode 100644 xstate-effect/src/fromEffect.ts
create mode 100644 xstate-effect/src/index.test.ts
create mode 100644 xstate-effect/src/index.ts
create mode 100644 xstate-effect/src/internal.ts
create mode 100644 xstate-effect/src/lint.test.ts
create mode 100644 xstate-effect/src/persistence.test.ts
create mode 100644 xstate-effect/src/requirements.types.test.ts
create mode 100644 xstate-effect/src/runtime.test.ts
create mode 100644 xstate-effect/src/schema.ts
create mode 100644 xstate-effect/src/setupEffect.ts
create mode 100644 xstate-effect/src/state.test.ts
create mode 100644 xstate-effect/src/state.ts
create mode 100644 xstate-effect/src/types.ts
create mode 100644 xstate-effect/test/lint-fixtures/declared-effect.ts
create mode 100644 xstate-effect/test/lint-fixtures/inline-effect.ts
create mode 100644 xstate-effect/test/lint-fixtures/oxlintrc.fixtures.json
create mode 100644 xstate-react/CHANGELOG.md
create mode 100644 xstate-react/LICENSE
create mode 100644 xstate-react/README.md
create mode 100644 xstate-react/docs/global-state.md
create mode 100644 xstate-react/docs/input-and-snapshots.md
create mode 100644 xstate-react/docs/meta.json
create mode 100644 xstate-react/docs/selectors.md
create mode 100644 xstate-react/docs/server-rendering.md
create mode 100644 xstate-react/docs/shared-actors.md
create mode 100644 xstate-react/docs/testing.md
create mode 100644 xstate-react/docs/use-machine.md
create mode 100644 xstate-react/package.json
create mode 100644 xstate-react/src/createActorContext.ts
create mode 100644 xstate-react/src/false.ts
create mode 100644 xstate-react/src/index.ts
create mode 100644 xstate-react/src/shallowEqual.ts
create mode 100644 xstate-react/src/true.ts
create mode 100644 xstate-react/src/useActor.ts
create mode 100644 xstate-react/src/useActorRef.ts
create mode 100644 xstate-react/src/useMachine.ts
create mode 100644 xstate-react/src/useSelector.ts
create mode 100644 xstate-react/test/createActorContext.test.tsx
create mode 100644 xstate-react/test/fastRefresh.production.test.tsx
create mode 100644 xstate-react/test/fastRefresh.test.tsx
create mode 100644 xstate-react/test/issueRegressions.test.tsx
create mode 100644 xstate-react/test/lint-fixtures/machine-in-component.tsx
create mode 100644 xstate-react/test/lint-fixtures/machine-outside-component.tsx
create mode 100644 xstate-react/test/lint-fixtures/oxlintrc.fixtures.json
create mode 100644 xstate-react/test/lint.test.ts
create mode 100644 xstate-react/test/types.test.tsx
create mode 100644 xstate-react/test/useActor.test.tsx
create mode 100644 xstate-react/test/useActorRef.test.tsx
create mode 100644 xstate-react/test/useSelector.test.tsx
create mode 100644 xstate-react/test/utils.tsx
create mode 100644 xstate-store-react/CHANGELOG.md
create mode 100644 xstate-store-react/LICENSE
create mode 100644 xstate-store-react/README.md
create mode 100644 xstate-store-react/package.json
create mode 100644 xstate-store-react/src/index.test.tsx
create mode 100644 xstate-store-react/src/index.ts
create mode 100644 xstate-store-react/src/types.test.tsx
create mode 100644 xstate-store/CHANGELOG.md
create mode 100644 xstate-store/LICENSE
create mode 100644 xstate-store/MIGRATION.md
create mode 100644 xstate-store/README.md
create mode 100644 xstate-store/docs/effects-and-emitted-events.md
create mode 100644 xstate-store/docs/events-and-context.md
create mode 100644 xstate-store/docs/frameworks.md
create mode 100644 xstate-store/docs/meta.json
create mode 100644 xstate-store/docs/migration.md
create mode 100644 xstate-store/docs/persistence.md
create mode 100644 xstate-store/docs/quick-start.md
create mode 100644 xstate-store/docs/selectors.md
create mode 100644 xstate-store/docs/typescript.md
create mode 100644 xstate-store/docs/undo-redo.md
create mode 100644 xstate-store/package.json
create mode 100644 xstate-store/src/alien.ts
create mode 100644 xstate-store/src/atom.ts
create mode 100644 xstate-store/src/fromStore.ts
create mode 100644 xstate-store/src/index.ts
create mode 100644 xstate-store/src/persist.ts
create mode 100644 xstate-store/src/reset.ts
create mode 100644 xstate-store/src/schema.ts
create mode 100644 xstate-store/src/select.test.ts
create mode 100644 xstate-store/src/shallowEqual.ts
create mode 100644 xstate-store/src/store.ts
create mode 100644 xstate-store/src/types.ts
create mode 100644 xstate-store/src/undo.ts
create mode 100644 xstate-store/src/validate.ts
create mode 100644 xstate-store/src/validationError.ts
create mode 100644 xstate-store/test/atom.test.ts
create mode 100644 xstate-store/test/broadcast.test.ts
create mode 100644 xstate-store/test/fromStore.test.ts
create mode 100644 xstate-store/test/persist.test.ts
create mode 100644 xstate-store/test/reset.test.ts
create mode 100644 xstate-store/test/store.test.ts
create mode 100644 xstate-store/test/types.test.tsx
create mode 100644 xstate-store/test/undo.test.ts
create mode 100644 xstate-store/test/validate.test.ts
create mode 100644 xstate-test/CHANGELOG.md
create mode 100644 xstate-test/LICENSE
create mode 100644 xstate-test/README.md
create mode 100644 xstate-test/package.json
create mode 100644 xstate-test/src/adapter.ts
create mode 100644 xstate-test/src/effect-schema.ts
create mode 100644 xstate-test/src/engine/constants.ts
create mode 100644 xstate-test/src/engine/coverage.ts
create mode 100644 xstate-test/src/engine/deduplicatePaths.ts
create mode 100644 xstate-test/src/engine/eventDescriptors.ts
create mode 100644 xstate-test/src/engine/index.ts
create mode 100644 xstate-test/src/engine/outcomes.ts
create mode 100644 xstate-test/src/engine/propertyLinearizability.ts
create mode 100644 xstate-test/src/engine/propertyTest.ts
create mode 100644 xstate-test/src/engine/report.ts
create mode 100644 xstate-test/src/engine/suite.ts
create mode 100644 xstate-test/src/engine/testPaths.ts
create mode 100644 xstate-test/src/engine/utils.ts
create mode 100644 xstate-test/src/failures.ts
create mode 100644 xstate-test/src/index.ts
create mode 100644 xstate-test/src/pick.ts
create mode 100644 xstate-test/src/playwright.ts
create mode 100644 xstate-test/src/propertyTest.ts
create mode 100644 xstate-test/src/scheduler.ts
create mode 100644 xstate-test/src/schema.ts
create mode 100644 xstate-test/src/vitest.ts
create mode 100644 xstate-test/test/advancedPropertyTest.test.ts
create mode 100644 xstate-test/test/campaignAssertions.test.ts
create mode 100644 xstate-test/test/docsExamples.test.ts
create mode 100644 xstate-test/test/effectSchema.test.ts
create mode 100644 xstate-test/test/engine/perfPairsDedup.test.ts
create mode 100644 xstate-test/test/engine/propertyExecuted.test.ts
create mode 100644 xstate-test/test/engine/propertyExploration.test.ts
create mode 100644 xstate-test/test/engine/propertyLinearizability.test.ts
create mode 100644 xstate-test/test/engine/propertyRegressions.test.ts
create mode 100644 xstate-test/test/engine/propertyReplay.test.ts
create mode 100644 xstate-test/test/engine/propertyReport.test.ts
create mode 100644 xstate-test/test/engine/propertySearch.test.ts
create mode 100644 xstate-test/test/engine/propertySuite.test.ts
create mode 100644 xstate-test/test/engine/propertyTest.test.ts
create mode 100644 xstate-test/test/engine/propertyTestAdapter.ts
create mode 100644 xstate-test/test/engine/symmetry.test.ts
create mode 100644 xstate-test/test/engine/testPaths.test.ts
create mode 100644 xstate-test/test/engine/testPathsInternalEvents.test.ts
create mode 100644 xstate-test/test/engine/unifiedTestApi.test.ts
create mode 100644 xstate-test/test/executedEffects.test.ts
create mode 100644 xstate-test/test/exploration.test.ts
create mode 100644 xstate-test/test/failureDatabase.test.ts
create mode 100644 xstate-test/test/fakePage.ts
create mode 100644 xstate-test/test/fastCheckWrappers.test.ts
create mode 100644 xstate-test/test/pairsRequirementsWeights.test.ts
create mode 100644 xstate-test/test/pick.types.test.ts
create mode 100644 xstate-test/test/playwrightArtifacts.test.ts
create mode 100644 xstate-test/test/playwrightPage.types.test.ts
create mode 100644 xstate-test/test/playwrightSut.test.ts
create mode 100644 xstate-test/test/propertyTest.test.ts
create mode 100644 xstate-test/test/propertyTest.types.test.ts
create mode 100644 xstate-test/test/randomAdapter.ts
create mode 100644 xstate-test/test/reachability.test.ts
create mode 100644 xstate-test/test/reportingOptions.test.ts
create mode 100644 xstate-test/test/scheduler.test.ts
create mode 100644 xstate-test/test/schema.test.ts
create mode 100644 xstate-test/test/search.test.ts
create mode 100644 xstate-test/test/suite.test.ts
create mode 100644 xstate-test/test/symmetry.test.ts
create mode 100644 xstate-test/test/temporalPayloadsReplay.test.ts
create mode 100644 xstate-test/test/vitest.test.ts
create mode 100644 xstate/CHANGELOG.md
create mode 100644 xstate/LICENSE
create mode 100644 xstate/README.md
create mode 100755 xstate/bin/xstate.js
create mode 100644 xstate/package.json
create mode 100644 xstate/src/IndexedHeap.ts
create mode 100644 xstate/src/Mailbox.ts
create mode 100644 xstate/src/SimulatedClock.ts
create mode 100644 xstate/src/State.ts
create mode 100644 xstate/src/StateMachine.ts
create mode 100644 xstate/src/StateNode.ts
create mode 100644 xstate/src/actions.ts
create mode 100644 xstate/src/actorScope.ts
create mode 100644 xstate/src/actorSource.ts
create mode 100644 xstate/src/actors/attached.ts
create mode 100644 xstate/src/actors/callback.ts
create mode 100644 xstate/src/actors/index.ts
create mode 100644 xstate/src/actors/listener.ts
create mode 100644 xstate/src/actors/logic.ts
create mode 100644 xstate/src/actors/observable.ts
create mode 100644 xstate/src/actors/promise.ts
create mode 100644 xstate/src/actors/subscription.ts
create mode 100644 xstate/src/assert.ts
create mode 100644 xstate/src/base.types.ts
create mode 100644 xstate/src/constants.ts
create mode 100644 xstate/src/createActor.ts
create mode 100644 xstate/src/createMachine.ts
create mode 100644 xstate/src/createMachineFromConfig.ts
create mode 100644 xstate/src/delay.ts
create mode 100644 xstate/src/devDiagnostics.ts
create mode 100644 xstate/src/durable/index.ts
create mode 100644 xstate/src/effectDescriptor.ts
create mode 100644 xstate/src/eventUtils.ts
create mode 100644 xstate/src/false.ts
create mode 100644 xstate/src/fsm.ts
create mode 100644 xstate/src/fsm/index.ts
create mode 100644 xstate/src/graph/actorScope.ts
create mode 100644 xstate/src/graph/adjacency.ts
create mode 100644 xstate/src/graph/alterPath.ts
create mode 100644 xstate/src/graph/graph.ts
create mode 100644 xstate/src/graph/index.ts
create mode 100644 xstate/src/graph/pathFromEvents.ts
create mode 100644 xstate/src/graph/shortestPaths.ts
create mode 100644 xstate/src/graph/simplePaths.ts
create mode 100644 xstate/src/graph/test/__snapshots__/graph.test.ts.snap
create mode 100644 xstate/src/graph/test/adjacency.test.ts
create mode 100644 xstate/src/graph/test/dieHard.test.ts
create mode 100644 xstate/src/graph/test/graph.test.ts
create mode 100644 xstate/src/graph/test/index.test.ts
create mode 100644 xstate/src/graph/test/paths.test.ts
create mode 100644 xstate/src/graph/test/shortestPaths.test.ts
create mode 100644 xstate/src/graph/test/traversal-regressions.test.ts
create mode 100644 xstate/src/graph/types.test.ts
create mode 100644 xstate/src/graph/types.ts
create mode 100644 xstate/src/hotSwap.ts
create mode 100644 xstate/src/index.ts
create mode 100644 xstate/src/inertActorScope.ts
create mode 100644 xstate/src/inspection.ts
create mode 100644 xstate/src/inspectionAmbient.ts
create mode 100644 xstate/src/machine.schema.json
create mode 100644 xstate/src/machineVersion.types.ts
create mode 100644 xstate/src/machineVersions.ts
create mode 100644 xstate/src/mapState.ts
create mode 100644 xstate/src/memo.ts
create mode 100644 xstate/src/persistedSnapshot.schema.json
create mode 100644 xstate/src/persistedSnapshotFormat.ts
create mode 100644 xstate/src/remoteActorRef.ts
create mode 100644 xstate/src/reportUnhandledError.ts
create mode 100644 xstate/src/runtimeHelpers.ts
create mode 100644 xstate/src/schema.types.ts
create mode 100644 xstate/src/serialize.ts
create mode 100644 xstate/src/setup.ts
create mode 100644 xstate/src/snapshotActorRef.ts
create mode 100644 xstate/src/spawn.ts
create mode 100644 xstate/src/stateUtils.ts
create mode 100644 xstate/src/symbolObservable.ts
create mode 100644 xstate/src/system.ts
create mode 100644 xstate/src/systemLogicMetadata.ts
create mode 100644 xstate/src/systemTransition.ts
create mode 100644 xstate/src/timerClock.ts
create mode 100644 xstate/src/toPromise.ts
create mode 100644 xstate/src/transition.ts
create mode 100644 xstate/src/transitionActions.ts
create mode 100644 xstate/src/true.ts
create mode 100644 xstate/src/types.ts
create mode 100644 xstate/src/types.v6.ts
create mode 100644 xstate/src/typestates.types.ts
create mode 100644 xstate/src/utils.ts
create mode 100644 xstate/src/validation.ts
create mode 100644 xstate/src/validation.types.ts
create mode 100644 xstate/src/validation/index.ts
create mode 100644 xstate/src/waitFor.ts
create mode 100644 xstate/test/actions.test.ts
create mode 100644 xstate/test/activities.test.ts
create mode 100644 xstate/test/actor.test.ts
create mode 100644 xstate/test/actorLogic.test.ts
create mode 100644 xstate/test/addressFirstIdentity.test.ts
create mode 100644 xstate/test/after.test.ts
create mode 100644 xstate/test/assert.test.ts
create mode 100644 xstate/test/assert.v6.test.ts
create mode 100644 xstate/test/assign.test.ts
create mode 100644 xstate/test/asyncErrorSchema.types.test.ts
create mode 100644 xstate/test/asyncTransition.test.ts
create mode 100644 xstate/test/childCompletionEvents.types.test.ts
create mode 100644 xstate/test/choice.test.ts
create mode 100644 xstate/test/clock.test.ts
create mode 100644 xstate/test/conversion.test.ts
create mode 100644 xstate/test/createActor.test.ts
create mode 100644 xstate/test/createInvoke.test.ts
create mode 100644 xstate/test/custom-interpreter.test.ts
create mode 100644 xstate/test/declarations.test.ts
create mode 100644 xstate/test/deep.test.ts
create mode 100644 xstate/test/delayNames.types.test.ts
create mode 100644 xstate/test/deterministic.test.ts
create mode 100644 xstate/test/durable-adapters/inngest.test.ts
create mode 100644 xstate/test/durable-adapters/rivet.test.ts
create mode 100644 xstate/test/durable-address-first.test.ts
create mode 100644 xstate/test/durable-adoption.test.ts
create mode 100644 xstate/test/durable-conformance.ts
create mode 100644 xstate/test/durable-event-journal-timers.test.ts
create mode 100644 xstate/test/durable-execution-identity.test.ts
create mode 100644 xstate/test/durable-execution.test.ts
create mode 100644 xstate/test/durable-inspection.test.ts
create mode 100644 xstate/test/durable-interpreter.test.ts
create mode 100644 xstate/test/durable-reference-host.test.ts
create mode 100644 xstate/test/durable-restore.test.ts
create mode 100644 xstate/test/emit.test.ts
create mode 100644 xstate/test/errorPrecedence.test.ts
create mode 100644 xstate/test/errors.test.ts
create mode 100644 xstate/test/event.test.ts
create mode 100644 xstate/test/eventBoundary.test.ts
create mode 100644 xstate/test/eventDescriptors.test.ts
create mode 100644 xstate/test/eventDescriptors.types.test.ts
create mode 100644 xstate/test/examples.6.16.test.ts
create mode 100644 xstate/test/examples.6.17.test.ts
create mode 100644 xstate/test/examples.6.6.test.ts
create mode 100644 xstate/test/examples.6.8.test.ts
create mode 100644 xstate/test/examples.6.9.test.ts
create mode 100644 xstate/test/examples.cd.test.ts
create mode 100644 xstate/test/final.test.ts
create mode 100644 xstate/test/firstTenMinutes.v6.test.ts
create mode 100644 xstate/test/fixtures/declarations/created-invoke-inference.ts
create mode 100644 xstate/test/fixtures/declarations/created-invoke.ts
create mode 100644 xstate/test/fixtures/declarations/narrowed-context.ts
create mode 100644 xstate/test/fixtures/declarations/registered-child-consumer.ts
create mode 100644 xstate/test/fixtures/declarations/registered-child-parent.ts
create mode 100644 xstate/test/fixtures/declarations/registered-child.ts
create mode 100644 xstate/test/fixtures/declarations/strict-targets.ts
create mode 100644 xstate/test/fsm-entrypoint.test.ts
create mode 100644 xstate/test/fsm.actor.test.ts
create mode 100644 xstate/test/fsm.differential.test.ts
create mode 100644 xstate/test/fsm.setup.test.ts
create mode 100644 xstate/test/fsm.test.ts
create mode 100644 xstate/test/fsm.types.test.ts
create mode 100644 xstate/test/guards.test.ts
create mode 100644 xstate/test/history.test.ts
create mode 100644 xstate/test/id.test.ts
create mode 100644 xstate/test/initial.test.ts
create mode 100644 xstate/test/input.test.ts
create mode 100644 xstate/test/inspect.test.ts
create mode 100644 xstate/test/inspection.conformance.v6.test.ts
create mode 100644 xstate/test/internalEvents.test.ts
create mode 100644 xstate/test/internalTransitions.test.ts
create mode 100644 xstate/test/interpreter.test.ts
create mode 100644 xstate/test/invalid.test.ts
create mode 100644 xstate/test/invoke.test.ts
create mode 100644 xstate/test/issue5454.test.ts
create mode 100644 xstate/test/issueRegressions.test.ts
create mode 100644 xstate/test/issueRegressions.types.test.ts
create mode 100644 xstate/test/json.test.ts
create mode 100644 xstate/test/listen.test.ts
create mode 100644 xstate/test/logger.test.ts
create mode 100644 xstate/test/logical-timers.test.ts
create mode 100644 xstate/test/machine.test.ts
create mode 100644 xstate/test/machineFromConfig.test.ts
create mode 100644 xstate/test/machineOutput.types.test.ts
create mode 100644 xstate/test/machineVersions.test.ts
create mode 100644 xstate/test/machineVersions.types.test.ts
create mode 100644 xstate/test/macrostepBound.test.ts
create mode 100644 xstate/test/mapState.test.ts
create mode 100644 xstate/test/match.test.ts
create mode 100644 xstate/test/memory.test.ts
create mode 100644 xstate/test/meta.test.ts
create mode 100644 xstate/test/microstep.test.ts
create mode 100644 xstate/test/microstep.v6.test.ts
create mode 100644 xstate/test/multiple.test.ts
create mode 100644 xstate/test/multiple.v6.test.ts
create mode 100644 xstate/test/order.test.ts
create mode 100644 xstate/test/parallel.test.ts
create mode 100644 xstate/test/parallelConformance.test.ts
create mode 100644 xstate/test/persistedSnapshot.types.test.ts
create mode 100644 xstate/test/persistenceConformance.v6.test.ts
create mode 100644 xstate/test/predictableExec.test.ts
create mode 100644 xstate/test/rehydration.test.ts
create mode 100644 xstate/test/rehydration.v6.test.ts
create mode 100644 xstate/test/resolve.test.ts
create mode 100644 xstate/test/resolve.v6.test.ts
create mode 100644 xstate/test/restoreEventless.test.ts
create mode 100644 xstate/test/restoreTerminal.test.ts
create mode 100644 xstate/test/restored-effects.test.ts
create mode 100644 xstate/test/route.test.ts
create mode 100644 xstate/test/runtimeValidation.test.ts
create mode 100644 xstate/test/runtimeValidation.types.test.ts
create mode 100644 xstate/test/select.test.ts
create mode 100644 xstate/test/serialization.conformance.v6.test.ts
create mode 100644 xstate/test/setup.test.ts
create mode 100644 xstate/test/setupStateContracts.test.ts
create mode 100644 xstate/test/sourceTyping.types.test.ts
create mode 100644 xstate/test/spawn.test.ts
create mode 100644 xstate/test/spawn.types.test.ts
create mode 100644 xstate/test/spawnChild.test.ts
create mode 100644 xstate/test/state.test.ts
create mode 100644 xstate/test/stateIn.test.ts
create mode 100644 xstate/test/stateInput.persistence.test.ts
create mode 100644 xstate/test/stateInput.test.ts
create mode 100644 xstate/test/strictTargets.types.test.ts
create mode 100644 xstate/test/system.test.ts
create mode 100644 xstate/test/systemOnRejectedEvent.test.ts
create mode 100644 xstate/test/systemTransition.test.ts
create mode 100644 xstate/test/tags.test.ts
create mode 100644 xstate/test/timeout.test.ts
create mode 100644 xstate/test/timers.persistence.test.ts
create mode 100644 xstate/test/toPromise.test.ts
create mode 100644 xstate/test/transient.test.ts
create mode 100644 xstate/test/transition.test.ts
create mode 100644 xstate/test/transitionFunctions.test.ts
create mode 100644 xstate/test/trigger.test.ts
create mode 100644 xstate/test/typeHelpers.test.ts
create mode 100644 xstate/test/typeSchemas.test.ts
create mode 100644 xstate/test/typeStates.test.ts
create mode 100644 xstate/test/types.test.ts
create mode 100644 xstate/test/unhandledEvents.test.ts
create mode 100644 xstate/test/utils.ts
create mode 100644 xstate/test/v5ConfigDiagnostics.test.ts
create mode 100644 xstate/test/v6.test.ts
create mode 100644 xstate/test/versioning.test.ts
create mode 100644 xstate/test/vizTypeFriction.types.test.ts
create mode 100644 xstate/test/waitFor.test.ts
diff --git a/xstate-effect/CHANGELOG.md b/xstate-effect/CHANGELOG.md
new file mode 100644
index 00000000..e7476a79
--- /dev/null
+++ b/xstate-effect/CHANGELOG.md
@@ -0,0 +1,105 @@
+# @xstate/effect
+
+## 0.1.0-alpha.7
+
+### Patch Changes
+
+- 902becb: `createEffectActor` accepts a persisted snapshot. The actor resumes in the persisted state and context without re-running entry actions, and pending delayed transitions keep their original deadlines on Effect's `Clock`.
+
+ ```ts
+ const saved = actor.getPersistedSnapshot();
+ // later, possibly in another process
+ const restored = yield* createEffectActor(machine, { snapshot: saved });
+ ```
+
+ State-machine children resume their persisted state, and completed children do not restart. Running Effect tasks and streams, including a root `fromEffect` or `fromEffectStream` actor, restart from the beginning, as running async and callback actors do with XState's `createActor(logic, { snapshot })`. A snapshot-only restore does not need `input`.
+
+## 0.1.0-alpha.6
+
+### Patch Changes
+
+- e6bb41e: Require stable Effect 4 (`^4.0.0`) instead of the Effect 4 release candidate.
+
+ Update atom integration to use Effect 4’s `effect/reactivity` module.
+
+## 0.1.0-alpha.5
+
+### Patch Changes
+
+- 5228c00: Infer the current service requirements of actions and actors replaced with `machine.provide`. Require declared actor input in `createActorAtoms`, consistently with `createEffectActor`.
+
+ Effect tasks and streams now release their resources when they complete, fail or are cancelled. Actor shutdown waits for task cleanup before releasing resources shared for the actor's lifetime. Use `withActorScope` around an acquisition to keep its resource until the owning Effect actor stops:
+
+ ```ts
+ import { Effect } from 'effect';
+ import { withActorScope } from '@xstate/effect';
+
+ const session = Effect.acquireRelease(
+ Effect.succeed({ id: 'session' }),
+ () => Effect.log('Session closed')
+ ).pipe(withActorScope);
+ ```
+
+ Improve XState Effect guides with complete, tested workflow, stream, inspection and React examples.
+
+## 0.1.0-alpha.4
+
+### Patch Changes
+
+- 8576291: Remove the `@xstate.deadletter` inspection event; observe undelivered events with the `onRejectedEvent` option. The inspection protocol is now exactly `@xstate.actor` and `@xstate.transition`. In `@xstate/effect`, `deadLetters(actor)` now streams `EventRejection` objects.
+
+ ```ts
+ createActor(machine, {
+ onRejectedEvent: (rejection) => {
+ console.log(rejection.event.type, rejection.reason, rejection.issues);
+ }
+ });
+ ```
+
+ Undelivered events are also available through `system.onRejectedEvent(listener)`, which accepts any number of listeners added at any time and returns a subscription. The `onRejectedEvent` option registers a listener the same way.
+
+ ```ts
+ const subscription = actor.system.onRejectedEvent((rejection) => {
+ console.log(rejection.event.type, rejection.reason);
+ });
+ subscription.unsubscribe();
+ ```
+
+## 0.1.0-alpha.3
+
+### Patch Changes
+
+- f5ea38e: Clarify that joining a machine exposes unknown errors, distinguish stopped actors from failed actors, and provide a typed oxlint plugin for strict TypeScript projects.
+
+## 0.1.0-alpha.2
+
+### Minor Changes
+
+- dcc21df: Add experimental Effect 4 integration for XState v6.
+
+ - `createEffectActor(logic)` starts an actor as a scoped Effect resource: it stops, and its running Effects are interrupted, when the enclosing `Scope` closes. Delays run on the Effect `Clock`, so `TestClock` drives delayed transitions, and declared Effect actions run with the services in scope. It returns an `EffectActor` handle that implements XState's `ActorRef` contract; `send` enqueues the event and the actor processes it on its own fiber.
+ - `fromEffect`, `fromEffectStream` and `fromEffectEventStream` turn Effects and Streams into actor logic with typed failures and service requirements. Interruption from inside the Effect reports an `EffectInterruptedError`.
+ - `setupEffect` accepts Effect schemas and Effect-returning actions.
+ - `@xstate/effect/atom` exports `createActorAtoms`, which runs an actor in an `Atom.runtime` from `effect/unstable/reactivity` and exposes `actor`, `snapshot`, `send` and `select` atoms for reactive UIs such as `@effect/atom-react`.
+ - `taggedState(snapshot)` and `TaggedState` view a machine snapshot as a tagged union over its states, with `_tag` as the dotted state path and `context` narrowed to that state, for `Match.tag` and `Match.exhaustive`. The `state` atom from `createActorAtoms` exposes the same view.
+ - `send`, `snapshots`, `emitted`, `waitFor`, `join`, `inspect` and `deadLetters` expose an actor as Effects and Streams. `send` and `waitFor` are dual, so they take the actor first or can be piped. `waitFor` narrows its result when given a type predicate, and accepts a `timeout` that fails with `Cause.TimeoutError`. `join` waits for an actor's final output. `deadLetters` streams the events the actor's system could not deliver.
+
+ ```ts
+ import { Effect, Schema } from 'effect';
+ import { createEffectActor, fromEffect, join } from '@xstate/effect';
+
+ const loadUser = fromEffect({
+ schemas: {
+ input: Schema.Struct({ id: Schema.String }),
+ output: Schema.Struct({ id: Schema.String })
+ },
+ effect: ({ input }) => Effect.succeed({ id: input.id })
+ });
+
+ const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(loadUser, { input: { id: '42' } });
+ return yield* join(actor);
+ });
+
+ await Effect.runPromise(Effect.scoped(program));
+ ```
diff --git a/xstate-effect/LICENSE b/xstate-effect/LICENSE
new file mode 100644
index 00000000..fc1fe941
--- /dev/null
+++ b/xstate-effect/LICENSE
@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 David Khourshid
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
diff --git a/xstate-effect/README.md b/xstate-effect/README.md
new file mode 100644
index 00000000..4f7f9d37
--- /dev/null
+++ b/xstate-effect/README.md
@@ -0,0 +1,265 @@
+# @xstate/effect
+
+Combine XState's event-driven workflows with Effect services, scopes, clocks and tracing.
+
+- Model approval, cancellation, deadlines and retry as explicit states and events.
+- Invoke Effect tasks when their result determines the next state.
+- Provide services once for the actor and its child logic.
+- Keep actor lifetime inside your Effect application.
+
+This package is experimental. It targets XState v6 alpha and Effect 4.
+
+## Installation
+
+
+
+```bash
+npm install @xstate/effect@alpha xstate@alpha effect@^4
+```
+
+## XState Effect: Quick start
+
+
+
+A release waits for approval, expires after 30 seconds, and allows cancellation during deployment. A failed deployment waits for an explicit retry:
+
+
+
+```ts
+import { Context, Effect, Schema } from 'effect';
+import {
+ createEffectActor,
+ fromEffect,
+ send,
+ setupEffect,
+ waitFor
+} from '@xstate/effect';
+
+export class Deployments extends Context.Service<
+ Deployments,
+ { readonly deploy: (release: string) => Effect.Effect }
+>()('@app/Deployments') {}
+
+const deploy = fromEffect({
+ schemas: { input: Schema.Struct({ release: Schema.String }) },
+ effect: ({ input }) => Deployments.use((api) => api.deploy(input.release))
+});
+
+export const approvalMachine = setupEffect({
+ schemas: { input: Schema.Struct({ release: Schema.String }) },
+ actors: { deploy }
+}).createMachine({
+ context: ({ input }) => ({ release: input.release, url: '' }),
+ initial: 'awaitingApproval',
+ states: {
+ awaitingApproval: {
+ after: { 30000: { target: 'expired' } },
+ on: {
+ APPROVE: { target: 'deploying' },
+ CANCEL: { target: 'cancelled' }
+ }
+ },
+ deploying: {
+ invoke: {
+ src: 'deploy',
+ input: ({ context }) => ({ release: context.release }),
+ onDone: ({ context, event }) => ({
+ target: 'deployed',
+ context: { ...context, url: event.output }
+ }),
+ onError: { target: 'failed' }
+ },
+ on: { CANCEL: { target: 'cancelled' } }
+ },
+ failed: {
+ on: {
+ RETRY: { target: 'deploying' },
+ CANCEL: { target: 'cancelled' }
+ }
+ },
+ deployed: { type: 'final' },
+ expired: { type: 'final' },
+ cancelled: { type: 'final' }
+ }
+});
+
+export const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(approvalMachine, {
+ input: { release: 'v1.2.0' }
+ });
+ // A UI, webhook or CLI can send this event after a person approves.
+ yield* send(actor, { type: 'APPROVE' });
+ const snapshot = yield* waitFor(actor, (s) => s.matches('deployed'), {
+ timeout: '5 seconds'
+ });
+ return snapshot.context.url;
+});
+
+export const result = await Effect.runPromise(
+ program.pipe(
+ Effect.scoped,
+ Effect.provideService(Deployments, {
+ // Replace this demo service with your deployment API.
+ deploy: (release) => Effect.succeed(`https://example.com/${release}`)
+ })
+ )
+);
+console.log(result); // 'https://example.com/v1.2.0'
+```
+
+The demo service runs locally. Replace it with your deployment API. The machine defines which events are valid in each state; Effect provides the deployment service and owns the actor's lifetime.
+
+Start Effect-backed logic with `createEffectActor` inside an Effect scope.
+
+
+Runtime and cancellation details
+
+- `createEffectActor` runs pure XState transitions from an Effect fiber. Its mailbox processes events in order; timers use Effect's `Clock`.
+- Events are processed asynchronously. Read their outcomes with `waitFor`, `join` or `snapshots`.
+- Starting Effect-backed logic with XState's `createActor` produces an error because the Effect host is missing.
+- Leaving an invoking state interrupts its local Effect. It does not undo work already accepted by an external API; model cancellation or rollback explicitly when needed.
+
+
+
+## Guides
+
+| Guide | Examples |
+| --- | --- |
+| [Quick start](docs/quick-start.md) | Release approval, expiry, cancellation and retry. |
+| [Actors](docs/actors.md) | Share an actor through a Layer and ManagedRuntime. |
+| [Observing actors](docs/observing-actors.md) | Snapshot history, output and streamed reminders. |
+| [Matching states](docs/matching-states.md) | Exhaustive matching and per-state context. |
+| [Effect actor logic](docs/effect-logic.md) | Report tasks, upload progress and rollout health events. |
+| [Schemas and actions](docs/schemas-and-actions.md) | Runtime event validation and background audit entries. |
+| [Atoms and React](docs/atoms-and-react.md) | Registry ownership, approval controls and useSelector. |
+| [Testing and errors](docs/testing-and-errors.md) | TestClock, task retries, supervision and typed failures. |
+
+Runnable copies live in [examples/effect-workflows](../../examples/effect-workflows). Their tests verify the docs use the same code.
+
+## Actors
+
+The actor stops and interrupts its hosted Effects when its enclosing scope closes. Use `Effect.scoped` for a bounded program, or `Layer.effect` to share an actor for an application's lifetime.
+
+- Invoked Effect tasks and streams own their resources and release them on completion, failure or cancellation.
+- Background actions use the owning actor's scope.
+- Use `withActorScope` around resource acquisition to keep a resource until the owning actor stops.
+
+Provide Layers outside the actor's scope, so services remain available during cleanup. Dispose a `ManagedRuntime` when its owner shuts down. See [actors](docs/actors.md).
+
+### Requirements
+
+`RequirementsFrom` collects services from declared Effect actions, declared actors and inline invocations, including child machines up to 10 levels deep. `createEffectActor` returns `Effect, never, R | Scope>`. Provided action and actor overrides update that service union. Actor and invocation scopes are supplied automatically.
+
+
+Requirement limits
+
+Deeper requirements are not inferred. Provide them explicitly or flatten the machine tree. Inline spawned Effect logic is rejected; register it in `actors` before spawning it.
+
+The actor's later errors are observed through `join` or snapshots. Invalid input rejected during creation is a defect.
+
+
+
+### Observing actors
+
+
+
+| Function | Use |
+| --- | --- |
+| `send` | Enqueue an event. |
+| `snapshots` | Stream the current snapshot and changes. |
+| `waitFor` | Await a snapshot predicate, optionally with a timeout. |
+| `join` | Await final output or failure. |
+| `emitted` | Stream notifications emitted by the actor. |
+| `inspect` | Stream system inspection events. |
+| `deadLetters` | Observe delivery failures. |
+
+`send` and `waitFor` support direct and pipeable usage. See [complete observation examples](docs/observing-actors.md).
+
+### Matching states
+
+
+
+`taggedState(snapshot)` exposes `_tag`, `value`, `context` and `snapshot`. Use `TaggedState` with Effect's `Match.tag` and `Match.exhaustive`. Per-state context narrows with the tag. See [matching states](docs/matching-states.md).
+
+## Effect actor logic
+
+
+
+| Function | Behavior |
+| --- | --- |
+| `fromEffect` | Run a task; its success value is the actor's output. |
+| `fromEffectStream` | Expose the latest stream item as snapshot context. |
+| `fromEffectEventStream` | Relay stream items to the parent as events. |
+
+For example, a progress stream can feed an upload UI:
+
+
+
+```ts
+import { Effect, Option, Stream } from 'effect';
+import { createEffectActor, fromEffectStream, snapshots } from '@xstate/effect';
+
+// Demo upload progress. Replace with your upload SDK's progress stream.
+const uploadProgress = fromEffectStream(Stream.make(0, 25, 60, 100));
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(uploadProgress);
+ return yield* snapshots(actor).pipe(
+ Stream.filter((s) => s.context !== undefined),
+ Stream.map((s) => s.context),
+ Stream.runLast,
+ Effect.map(Option.getOrThrow)
+ );
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // 100
+```
+
+See [Effect actor logic](docs/effect-logic.md) for tasks and a stream that drives rollout transitions.
+
+## Schemas and actions
+
+
+
+`setupEffect` accepts Effect schemas for input, context, events, output and per-state context. Types are inferred without manual conversion. Add `standardSchemaValidator()` from `xstate/validation` for runtime checks.
+
+### Declared only
+
+
+
+- Register background Effect actions in `setupEffect({ actions })`; enqueue them with explicit arguments.
+- Invoke `fromEffect` logic when the machine needs to wait for a result.
+- Register spawned Effect logic in `actors`, then use `enq.spawn(args.actors.worker)`.
+
+See [schemas and actions](docs/schemas-and-actions.md) for a complete audit example, runtime schema constraints and inline-source pitfalls.
+
+## Atoms and React
+
+
+
+`createActorAtoms` from `@xstate/effect/atom` exposes `actor`, `snapshot`, `result`, `send`, `select` and `state`. Its `Atom.runtime` must provide the logic's services. Pass `{ input }` when the logic requires input; missing or mismatched input is a type error.
+
+- Read atoms with `@effect/atom-react` in React, or an `AtomRegistry` elsewhere.
+- The registry owns their lifetime; dispose it when its owner shuts down.
+- `useSelector` from `@xstate/react` can also read an existing `EffectActor` directly.
+
+See [atoms and React](docs/atoms-and-react.md) for complete examples with imports, runtime setup and cleanup.
+
+## Testing and errors
+
+
+
+- Use `TestClock` to drive deadlines without waiting for real time.
+- `ActorStoppedError` reports a stop before an awaited result.
+- `EffectInterruptedError` reports self-interruption inside Effect logic.
+- Timed waits fail with Effect's `Cause.TimeoutError`.
+- `join` preserves a task's typed failure. Unexpected machine errors have type `unknown`.
+
+See [testing and errors](docs/testing-and-errors.md) for executable deadline, retry and failure examples. Persisted snapshots record actor state; pass one to `createEffectActor(logic, { snapshot })` to resume the actor. See [persisting and restoring](docs/actors.md#persisting-and-restoring).
+
+## Tracing
+
+
+
+Hosted work uses spans named `fromEffect`, `fromEffectStream`, `fromEffectEventStream` and `action.`. Each carries `xstate.actor.id` and `xstate.actor.address`. Provide a `Tracer` to record and export them.
diff --git a/xstate-effect/docs/actors.md b/xstate-effect/docs/actors.md
new file mode 100644
index 00000000..2d7bd7af
--- /dev/null
+++ b/xstate-effect/docs/actors.md
@@ -0,0 +1,236 @@
+---
+title: "XState Effect: Actors"
+description: Create actors whose lifetime and dependencies belong to an Effect application.
+---
+
+`createEffectActor(logic, options?)` starts an actor and returns its handle as a scoped Effect.
+
+- Pass `options.input` when the logic requires input.
+- Pass `options.snapshot` to resume an actor from a persisted snapshot. See [persisting and restoring](#persisting-and-restoring).
+- Provide the services required by its declared actions and child actors.
+- Use `Effect.scoped` for a bounded program, or a Layer for an application service.
+
+The [quick start](quick-start.md) shows an actor with input and a deployment service.
+
+## Lifetime
+
+The enclosing scope owns the actor. When that scope closes, the actor stops and its hosted Effects are interrupted.
+
+- `Effect.scoped(program)` closes the scope when `program` finishes.
+- `actor.stop()` stops the actor explicitly.
+- Tasks created with `fromEffect`, `fromEffectStream` and `fromEffectEventStream` have their own scopes. Their resources are released when the task completes, fails or is interrupted.
+- Background Effect actions use the owning actor's scope. Their resources are released when that actor stops.
+- Use `withActorScope` around a resource acquisition to keep it until the owning actor stops.
+- The enclosing scope waits for the actor's finalizers before finishing its own cleanup.
+
+Provide application Layers outside `Effect.scoped`, with `program.pipe(Effect.scoped, Effect.provide(AppLayer))`, so services remain available while actor cleanup runs.
+
+### Resource lifetimes
+
+This release task owns a temporary workspace and opens a cache for the rest of the workflow. The workspace closes before the machine handles `onDone`; the cache closes when the owning actor stops.
+
+
+
+```ts
+import { Effect } from 'effect';
+import {
+ createEffectActor,
+ fromEffect,
+ waitFor,
+ withActorScope
+} from '@xstate/effect';
+import { setup } from 'xstate';
+
+const events: string[] = [];
+const prepareRelease = fromEffect(
+ Effect.gen(function* () {
+ // Keep the shared cache open for the rest of the release workflow.
+ yield* Effect.acquireRelease(
+ Effect.succeed({ name: 'release-cache' }),
+ () => Effect.sync(() => events.push('close cache'))
+ ).pipe(withActorScope);
+
+ // This temporary workspace belongs to this invocation.
+ yield* Effect.acquireRelease(
+ Effect.succeed({ directory: '/tmp/release' }),
+ () => Effect.sync(() => events.push('remove workspace'))
+ );
+ events.push('prepare release');
+ return 'artifact ready';
+ })
+);
+
+const releaseMachine = setup({ actors: { prepareRelease } }).createMachine({
+ initial: 'preparing',
+ states: {
+ preparing: {
+ invoke: { src: 'prepareRelease', onDone: { target: 'ready' } }
+ },
+ ready: {}
+ }
+});
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(releaseMachine);
+ yield* waitFor(actor, (snapshot) => snapshot.matches('ready'));
+ events.push('ready for approval');
+ // The workspace is gone; the cache stays open while the actor is alive.
+});
+
+await Effect.runPromise(Effect.scoped(program));
+export const result = events;
+console.log(result);
+// ['prepare release', 'remove workspace', 'ready for approval', 'close cache']
+```
+
+The resource objects in this demo are local stand-ins. Replace their acquisition and release Effects with your file, connection or subscription APIs.
+
+`withActorScope` uses the scope of the root actor created by `createEffectActor`, including when called from a nested invocation. Apply it to the acquisition whose lifetime you want to extend.
+
+## Provide an actor as a service
+
+Use `Layer.effect` to share one actor across requests. This review actor stays alive across calls to the `ManagedRuntime`:
+
+
+
+```ts
+import { Context, Effect, Layer, ManagedRuntime } from 'effect';
+import {
+ createEffectActor,
+ send,
+ waitFor,
+ type EffectActor
+} from '@xstate/effect';
+import { createMachine } from 'xstate';
+
+const reviewMachine = createMachine({
+ initial: 'pending',
+ states: {
+ pending: { on: { APPROVE: { target: 'approved' } } },
+ approved: {}
+ }
+});
+
+class ReviewActor extends Context.Service<
+ ReviewActor,
+ EffectActor
+>()('@app/ReviewActor') {}
+
+const ReviewActorLayer = Layer.effect(
+ ReviewActor,
+ createEffectActor(reviewMachine)
+);
+const runtime = ManagedRuntime.make(ReviewActorLayer);
+
+try {
+ const snapshot = await runtime.runPromise(
+ Effect.gen(function* () {
+ const actor = yield* ReviewActor;
+ yield* send(actor, { type: 'APPROVE' });
+ return yield* waitFor(actor, (s) => s.matches('approved'));
+ })
+ );
+ console.log(snapshot.value); // 'approved'
+} finally {
+ await runtime.dispose();
+}
+```
+
+- The Layer starts the actor when it is built.
+- `EffectActor` types the service and its events.
+- `runtime.dispose()` closes the runtime, stops the actor and releases its resources. Call it when your application shuts down.
+
+If the machine requires services, provide their Layers to the actor Layer with `Layer.provide`.
+
+## Clock
+
+`after` transitions and delayed sends use Effect's `Clock`. In tests, `TestClock` advances those timers without waiting for real time. See the [complete deadline example](testing-and-errors.md#testclock).
+
+Timers are interrupted when the actor stops.
+
+## Persisting and restoring
+
+An actor can outlive its process. Save `actor.getPersistedSnapshot()` after an event, then pass the saved snapshot to `createEffectActor` when the next event arrives, in the same process or another one.
+
+
+
+```ts
+import { Effect } from 'effect';
+import { createEffectActor, waitFor } from '@xstate/effect';
+import { createMachine, type Snapshot } from 'xstate';
+
+const review = createMachine({
+ id: 'review',
+ initial: 'draft',
+ states: {
+ draft: { on: { SUBMIT: { target: 'inReview' } } },
+ inReview: { on: { APPROVE: { target: 'approved' } } },
+ approved: { type: 'final' }
+ }
+});
+
+// Handle one event, then return the snapshot to store.
+const handle = (
+ stored: Snapshot | undefined,
+ event: { type: 'SUBMIT' } | { type: 'APPROVE' }
+) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(review, { snapshot: stored });
+ const before = actor.getSnapshot();
+ actor.send(event);
+ yield* waitFor(actor, (snapshot) => snapshot !== before);
+ return JSON.parse(JSON.stringify(actor.getPersistedSnapshot()));
+ })
+ );
+
+const program = Effect.gen(function* () {
+ const submitted = yield* handle(undefined, { type: 'SUBMIT' });
+ // Store `submitted` in a database row or a Durable Object, possibly for days.
+ const approved = yield* handle(submitted, { type: 'APPROVE' });
+ return approved.status;
+});
+
+export const result = await Effect.runPromise(program);
+console.log(result); // 'done'
+```
+
+Restoring resumes the persisted state and context without running entry actions again.
+
+- A pending `after` transition or delayed send keeps its original deadline, measured on Effect's `Clock`. A deadline that passed while the snapshot was stored fires as soon as the actor starts.
+- State-machine children resume their persisted state and context.
+- Completed children do not restart.
+- Running Effect tasks and streams restart from the beginning: a `fromEffect` task runs its Effect again, and a `fromEffectStream` or `fromEffectEventStream` stream starts again from its first item. A half-finished Effect cannot be persisted, so this matches how XState restarts running async and callback actors. Make that work safe to repeat, for example with an idempotency key.
+- A snapshot-only restore does not need `input`, even when the logic requires it.
+- The restored actor belongs to the enclosing scope like any other: closing the scope stops it, its children and its timers.
+
+## Actor handle
+
+The `EffectActor` handle supports:
+
+- `send`, `getSnapshot`, `subscribe` and `on` from XState's actor reference contract;
+- `inspect`, `getPersistedSnapshot` and `stop`;
+- this package's [actor functions](observing-actors.md) and `useSelector` from `@xstate/react`.
+
+## Requirements
+
+`RequirementsFrom` collects the services needed by:
+
+- actions registered with `setupEffect({ actions })`;
+- actors registered with `setup({ actors })` or `setupEffect({ actors })`;
+- inline `invoke.src` logic, at the root or in a state;
+- those same sources inside child machines, up to 10 levels of nesting.
+
+`createEffectActor` returns `Effect, never, R | Scope>`, where `R` is that service union. TypeScript checks that you provide those services before running the program. Overrides passed to `machine.provide` contribute their current services, replacing the requirements of the sources they override. Actor and invocation scopes are supplied automatically.
+
+Declare spawned Effect logic in `actors` and spawn it by name. See [declared sources](schemas-and-actions.md#declared-sources).
+
+
+Requirement inference limits and creation errors
+
+- Requirements deeper than 10 machine levels are not collected. Flatten that tree, or provide the deeper services explicitly.
+- Inline logic passed to `enq.spawn` is invisible to requirement inference and is rejected at runtime.
+- The `never` error channel means actor creation has no typed failures. It does not describe the actor's later result; use `join` to observe that result.
+- Missing services and other programming errors can put the actor in the `error` status. Invalid input rejected by a runtime validator makes creation fail as a defect.
+
+
diff --git a/xstate-effect/docs/atoms-and-react.md b/xstate-effect/docs/atoms-and-react.md
new file mode 100644
index 00000000..138566b3
--- /dev/null
+++ b/xstate-effect/docs/atoms-and-react.md
@@ -0,0 +1,248 @@
+---
+title: "XState Effect: Atoms and React"
+description: Read workflow state and send events from an Effect-powered UI.
+---
+
+Use `@xstate/effect/atom` to expose an actor through Effect's reactive atoms. The runtime owns the actor; components read its state and send events.
+
+`effect/reactivity` is an unstable Effect module. This entry point follows it and may change independently of the rest of the package.
+
+## Create actor atoms
+
+`createActorAtoms(runtime, logic, options?)` takes an `Atom.runtime` whose Layer provides the logic's services. When the logic requires input, pass `{ input }`; TypeScript rejects missing or mismatched input, just as it does with `createEffectActor`.
+
+This complete example waits for the runtime, sends an approval and reads a selector:
+
+
+
+```ts
+import { Effect, Layer } from 'effect';
+import { AsyncResult, Atom, AtomRegistry } from 'effect/reactivity';
+import { waitFor } from '@xstate/effect';
+import { createActorAtoms } from '@xstate/effect/atom';
+import { createMachine } from 'xstate';
+
+const reviewMachine = createMachine({
+ initial: 'pending',
+ states: {
+ pending: { on: { APPROVE: { target: 'approved' } } },
+ approved: {}
+ }
+});
+
+const runtime = Atom.runtime(Layer.empty);
+const review = createActorAtoms(runtime, reviewMachine);
+const status = review.select((snapshot) => snapshot.value);
+const registry = AtomRegistry.make();
+const unmount = registry.mount(status);
+
+export let result: string | undefined;
+try {
+ const actor = await Effect.runPromise(
+ AtomRegistry.getResult(registry, review.actor)
+ );
+ // Wait for the runtime before sending.
+ registry.set(review.send, { type: 'APPROVE' });
+ await Effect.runPromise(waitFor(actor, (s) => s.matches('approved')));
+ const current = registry.get(status);
+ if (AsyncResult.isSuccess(current)) {
+ result = current.value;
+ console.log(result); // 'approved'
+ }
+} finally {
+ unmount();
+ registry.dispose();
+}
+```
+
+- The actor starts when one of its atoms is first read or mounted.
+- It is released when its atoms have no consumers, subject to the registry's idle lifetime.
+- Dispose the registry when its owner shuts down.
+- A runtime missing a required service is a type error.
+
+## Atom reference
+
+| Atom | Value |
+| --- | --- |
+| `actor` | `AsyncResult>`. |
+| `snapshot` | `AsyncResult`, including error snapshots. |
+| `result` | A failure when the actor errors, suitable for error handling. |
+| `send` | Writable atom that accepts an event and reports the last send. |
+| `select(f)` | Derived `AsyncResult` from the snapshot. |
+| `state` | The snapshot as a [tagged union](matching-states.md). |
+
+The runtime Layer's error type is included in the atoms' error channels. `result` also includes the actor's `ErrorFrom`.
+
+
+Sending before the runtime is ready
+
+The `send` atom enqueues an event once the actor is ready. Sending while the runtime is still building records `NotReadyError` instead. That class is exported from `@xstate/effect/atom`. Wait for the actor, or render controls after `useAtomSuspense` has resolved.
+
+
+
+## React
+
+Install the React bindings that match your Effect version:
+
+```bash
+npm install @effect/atom-react react react-dom
+```
+
+The example uses an approval workflow with a demo publishing task. `RegistryProvider` owns the atom registry, and `Suspense` handles startup:
+
+
+
+```tsx
+import { Suspense } from 'react';
+import { Effect, Layer } from 'effect';
+import { Atom } from 'effect/reactivity';
+import {
+ RegistryProvider,
+ useAtomSet,
+ useAtomSuspense
+} from '@effect/atom-react';
+import { fromEffect, setupEffect } from '@xstate/effect';
+import { createActorAtoms } from '@xstate/effect/atom';
+
+const reviewMachine = setupEffect({
+ actors: { publish: fromEffect(Effect.sleep('10 millis')) }
+}).createMachine({
+ initial: 'pending',
+ states: {
+ pending: { on: { APPROVE: { target: 'publishing' } } },
+ publishing: {
+ invoke: { src: 'publish', onDone: { target: 'published' } }
+ },
+ published: {}
+ }
+});
+
+const runtime = Atom.runtime(Layer.empty);
+const review = createActorAtoms(runtime, reviewMachine);
+const status = review.select((snapshot) => snapshot.value);
+
+function Review() {
+ const { value } = useAtomSuspense(status);
+ const send = useAtomSet(review.send);
+ return (
+
+ {value}
+
+
+ );
+}
+
+export function App() {
+ return (
+
+ Starting review…
}>
+
+
+
+ );
+}
+```
+
+- `useAtomSuspense` waits for the runtime and actor, then returns a successful result.
+- `useAtomValue` returns the `AsyncResult` directly, for components that render loading and failure states themselves.
+- `useAtomMount(review.actor)` lets an owner component retain the actor while child components read selectors.
+- Use `Atom.keepAlive` to retain an atom for the registry's lifetime, or `Atom.family` for one actor per input.
+
+
+Starting actors from React hooks
+
+`useMachine`, `useActor` and `useActorRef` from `@xstate/react` start logic through XState's `createActor`. Start Effect-backed logic in an Effect runtime with `createEffectActor`, then consume it through atoms or `useSelector`.
+
+
+
+## Use an actor handle directly
+
+`useSelector` accepts an `EffectActor`. Build the actor in a `ManagedRuntime`, pass it to a component and dispose the runtime when the application shuts down:
+
+
+
+```tsx
+import { Context, Layer, ManagedRuntime } from 'effect';
+import { createEffectActor, type EffectActor } from '@xstate/effect';
+import { useSelector } from '@xstate/react';
+import { createMachine } from 'xstate';
+
+const reviewMachine = createMachine({
+ initial: 'pending',
+ states: {
+ pending: { on: { APPROVE: { target: 'approved' } } },
+ approved: {}
+ }
+});
+
+class ReviewActor extends Context.Service<
+ ReviewActor,
+ EffectActor
+>()('@app/ReviewActor') {}
+
+export const runtime = ManagedRuntime.make(
+ Layer.effect(ReviewActor, createEffectActor(reviewMachine))
+);
+export const actor = await runtime.runPromise(ReviewActor);
+
+// Render in your React application.
+export function Review({
+ actor
+}: {
+ actor: EffectActor;
+}) {
+ const status = useSelector(actor, (s) => s.value);
+ return (
+
+ );
+}
+
+// Call await runtime.dispose() when the application shuts down.
+```
+
+## Required input
+
+Pass the actor's input when creating its atoms:
+
+
+
+```ts
+import { Effect, Layer, Schema } from 'effect';
+import { Atom, AtomRegistry } from 'effect/reactivity';
+import { fromEffect, join } from '@xstate/effect';
+import { createActorAtoms } from '@xstate/effect/atom';
+
+const prepare = fromEffect({
+ schemas: { input: Schema.Struct({ release: Schema.String }) },
+ effect: ({ input }) => Effect.succeed(`Prepared ${input.release}`)
+});
+
+const runtime = Atom.runtime(Layer.empty);
+const atoms = createActorAtoms(runtime, prepare, {
+ input: { release: 'v1.2.0' }
+});
+const registry = AtomRegistry.make();
+const unmount = registry.mount(atoms.snapshot);
+
+export let result: string | undefined;
+try {
+ const actor = await Effect.runPromise(
+ AtomRegistry.getResult(registry, atoms.actor)
+ );
+ result = await Effect.runPromise(join(actor));
+ console.log(result); // Prepared v1.2.0
+} finally {
+ unmount();
+ registry.dispose();
+}
+```
diff --git a/xstate-effect/docs/effect-logic.md b/xstate-effect/docs/effect-logic.md
new file mode 100644
index 00000000..12c89862
--- /dev/null
+++ b/xstate-effect/docs/effect-logic.md
@@ -0,0 +1,183 @@
+---
+title: "XState Effect: Actor logic"
+description: Use Effect tasks and streams as parts of an event-driven workflow.
+---
+
+Turn an Effect or Stream into [actor logic](../../../docs/actor-logic.md) with one of these functions. Start it with `createEffectActor`, or invoke it from a machine running under `createEffectActor`.
+
+| Function | Use it for |
+| --- | --- |
+| `fromEffect` | A task whose result decides the next state. |
+| `fromEffectStream` | A changing value, such as upload progress. |
+| `fromEffectEventStream` | Events that drive a workflow, such as health checks. |
+
+Each accepts a value, a function of actor arguments that returns the value, or a configuration object with `id`, `schemas`, `validator` and `effect` or `stream`.
+
+## `fromEffect`
+
+Use `fromEffect` for work the machine waits for: publishing a release, reserving inventory or building a report. The [quick start](quick-start.md) invokes a deployment task and handles success, failure and cancellation.
+
+Here is a complete task with typed input and output:
+
+
+
+```ts
+import { Effect, Schema } from 'effect';
+import { createEffectActor, fromEffect, join } from '@xstate/effect';
+
+const buildReport = fromEffect({
+ schemas: { input: Schema.Struct({ orderIds: Schema.Array(Schema.String) }) },
+ effect: ({ input, emit }) =>
+ Effect.sync(() => {
+ emit({ type: 'reportBuilt', count: input.orderIds.length });
+ return { total: input.orderIds.length };
+ })
+});
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(buildReport, {
+ input: { orderIds: ['order-1', 'order-2'] }
+ });
+ return yield* join(actor);
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // { total: 2 }
+```
+
+- The actor is `active` while the Effect runs.
+- Success puts it in `done` and stores the value in `output`.
+- Failure puts it in `error`; `join` and an invoking machine's `onError` receive the typed error.
+- The task actor has no context of its own.
+
+### Actor arguments
+
+The function form receives `EffectSourceArgs` once per actor start:
+
+| Field | Description |
+| --- | --- |
+| `input` | The actor's input. |
+| `self` | The actor's reference. |
+| `system` | The actor system. |
+| `emit` | Emits a notification for `actor.on(...)` and `emitted(actor)`. |
+
+Input and output schemas are optional. Missing types are inferred from the function or Effect. See [schemas and actions](schemas-and-actions.md) for runtime validation.
+
+### Cancellation and failure
+
+Leaving an invoking state or stopping the actor interrupts the running Effect. Each task runs in its own scope:
+
+- `Effect.acquireRelease` and `Effect.addFinalizer` clean up before a completed or failed task reports its outcome.
+- Cancelling an invocation interrupts the task and runs its cleanup while the parent can continue in another state.
+- Use `withActorScope` for resources that should stay open until the owning actor stops. See [resource lifetimes](actors.md#resource-lifetimes).
+
+Use Effect's retry and timeout combinators inside the task.
+
+
+How Effect exits map to actors
+
+| Exit | Actor result |
+| --- | --- |
+| Success | `done`, with the success value as `output`. |
+| Typed failure | `error`, with the failure value as `error`. |
+| Defect | `error`, with the squashed cause. |
+| Interrupted because the actor stopped or the invoking state exited | Stopped, without an error. |
+| Self-interruption inside the Effect | `error`, with `EffectInterruptedError`. |
+
+`Effect.timeout` fails with `Cause.TimeoutError`. A lost `Effect.race` interrupts only the loser; the actor completes with the winner.
+
+
+
+## `fromEffectStream`
+
+Use `fromEffectStream` when consumers need the latest value. For example, upload progress becomes the actor's snapshot context:
+
+
+
+```ts
+import { Effect, Option, Stream } from 'effect';
+import { createEffectActor, fromEffectStream, snapshots } from '@xstate/effect';
+
+// Demo upload progress. Replace with your upload SDK's progress stream.
+const uploadProgress = fromEffectStream(Stream.make(0, 25, 60, 100));
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(uploadProgress);
+ return yield* snapshots(actor).pipe(
+ Stream.filter((s) => s.context !== undefined),
+ Stream.map((s) => s.context),
+ Stream.runLast,
+ Effect.map(Option.getOrThrow)
+ );
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // 100
+```
+
+The demo stream is finite. Replace it with your upload SDK's progress stream; the actor exposes each new percentage as `snapshot.context`.
+
+- Context is `undefined` until the first item arrives.
+- Completion puts the actor in `done`, with no output; the last context remains readable.
+- Stream failure puts the actor in `error`.
+- Read changing values with `snapshots`, `waitFor` or a UI selector.
+
+## `fromEffectEventStream`
+
+Use `fromEffectEventStream` when stream items should trigger transitions. This deployment feed first reports a healthy rollout, then a health failure that requests rollback:
+
+
+
+```ts
+import { Effect, Stream } from 'effect';
+import {
+ createEffectActor,
+ fromEffectEventStream,
+ join,
+ setupEffect
+} from '@xstate/effect';
+
+// A deployment feed drives the workflow, rather than just displaying data.
+const deploymentEvents = fromEffectEventStream(
+ Stream.make({ type: 'HEALTHY' }, { type: 'UNHEALTHY' })
+);
+
+const rolloutMachine = setupEffect({
+ actors: { deploymentEvents }
+}).createMachine({
+ output: () => 'rollback requested',
+ initial: 'monitoring',
+ states: {
+ monitoring: {
+ invoke: { src: 'deploymentEvents' },
+ initial: 'checking',
+ states: {
+ checking: { on: { HEALTHY: { target: 'healthy' } } },
+ healthy: {}
+ },
+ on: { UNHEALTHY: { target: 'rollingBack' } }
+ },
+ rollingBack: { type: 'final' }
+ }
+});
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(rolloutMachine);
+ return yield* join(actor);
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // 'rollback requested'
+```
+
+The stream belongs to `monitoring`, so it stays active when that state moves from `checking` to `healthy`. Leaving `monitoring` stops the stream actor and interrupts its consumption.
+
+- Each item is relayed to the parent machine as an event.
+- Completion puts the stream actor in `done`, with no output.
+- Stream failure puts it in `error`; handle it with the invocation's `onError`.
+
+Use this pattern for WebSocket messages, job updates or subscription feeds that change a workflow's state.
+
+## Tracing
+
+The three functions run inside spans named `fromEffect`, `fromEffectStream` and `fromEffectEventStream`. See [tracing](testing-and-errors.md#tracing).
diff --git a/xstate-effect/docs/matching-states.md b/xstate-effect/docs/matching-states.md
new file mode 100644
index 00000000..762e1037
--- /dev/null
+++ b/xstate-effect/docs/matching-states.md
@@ -0,0 +1,125 @@
+---
+title: "XState Effect: Matching states"
+description: Render workflow states with exhaustive Effect Match branches.
+---
+
+`taggedState(snapshot)` gives a machine snapshot an Effect-style `_tag`. Use `Match.tag` and `Match.exhaustive` to describe every state of a workflow.
+
+In this review example, only the approved state has a `reviewer`. Matching that tag also narrows its context:
+
+
+
+```ts
+import { Effect, Match, Schema, Stream } from 'effect';
+import {
+ createEffectActor,
+ send,
+ setupEffect,
+ snapshots,
+ taggedState,
+ type TaggedState
+} from '@xstate/effect';
+
+const reviewMachine = setupEffect({
+ states: {
+ approved: {
+ schemas: { context: Schema.Struct({ reviewer: Schema.String }) }
+ }
+ }
+}).createMachine({
+ initial: 'pending',
+ states: {
+ pending: {
+ on: { APPROVE: { target: 'approved', context: { reviewer: 'Ada' } } }
+ },
+ approved: { type: 'final' }
+ }
+});
+
+const describe = Match.type>().pipe(
+ Match.tag('pending', () => 'Waiting for review'),
+ Match.tag('approved', ({ context }) => `Approved by ${context.reviewer}`),
+ Match.exhaustive
+);
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(reviewMachine);
+ return [
+ ...(yield* snapshots(actor).pipe(
+ Stream.tap((s) =>
+ s.matches('pending') ? send(actor, { type: 'APPROVE' }) : Effect.void
+ ),
+ Stream.map(taggedState),
+ Stream.map(describe),
+ Stream.runCollect
+ ))
+ ];
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // ['Waiting for review', 'Approved by Ada']
+```
+
+Adding a state requires adding a matching branch before `Match.exhaustive` will typecheck.
+
+## Tagged state fields
+
+| Field | Description |
+| --- | --- |
+| `_tag` | The dotted state path, such as `review.approved`. |
+| `value` | The XState state value. |
+| `context` | The context for that state, including its per-state schema. |
+| `snapshot` | The original snapshot. |
+
+- `TaggedState` names the union for a machine.
+- `TaggedStateFrom` names it for a snapshot type.
+- `StateTag` names the tag for one state value.
+
+Declare per-state context with `setupEffect({ states })`. See [schemas and actions](schemas-and-actions.md).
+
+## Parallel states
+
+A parallel workflow can wait for review while building a release. Its `_tag` stops at the parallel state; when the root is parallel, the tag is `'(machine)'`. Inspect `value` or use `snapshot.matches` to read individual regions:
+
+
+
+```ts
+import { Effect, Match } from 'effect';
+import {
+ createEffectActor,
+ taggedState,
+ type TaggedState
+} from '@xstate/effect';
+import { createMachine } from 'xstate';
+
+const releaseMachine = createMachine({
+ type: 'parallel',
+ states: {
+ review: { initial: 'pending', states: { pending: {}, approved: {} } },
+ build: { initial: 'running', states: { running: {}, passed: {} } }
+ }
+});
+
+const describe = Match.type>().pipe(
+ Match.tag('(machine)', ({ snapshot }) =>
+ snapshot.matches({ build: 'running' })
+ ? 'Build in progress'
+ : 'Build finished'
+ ),
+ Match.exhaustive
+);
+
+export const result = await Effect.runPromise(
+ Effect.scoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(releaseMachine);
+ return describe(taggedState(actor.getSnapshot()));
+ })
+ )
+);
+console.log(result); // 'Build in progress'
+```
+
+## UI atoms
+
+`createActorAtoms` exposes this same tagged union through its `state` atom. A UI can match on states without calling `taggedState` itself. See [atoms and React](atoms-and-react.md).
diff --git a/xstate-effect/docs/meta.json b/xstate-effect/docs/meta.json
new file mode 100644
index 00000000..59a98d26
--- /dev/null
+++ b/xstate-effect/docs/meta.json
@@ -0,0 +1,13 @@
+{
+ "title": "XState Effect",
+ "pages": [
+ "quick-start",
+ "actors",
+ "observing-actors",
+ "matching-states",
+ "effect-logic",
+ "schemas-and-actions",
+ "atoms-and-react",
+ "testing-and-errors"
+ ]
+}
diff --git a/xstate-effect/docs/observing-actors.md b/xstate-effect/docs/observing-actors.md
new file mode 100644
index 00000000..4d7a6185
--- /dev/null
+++ b/xstate-effect/docs/observing-actors.md
@@ -0,0 +1,228 @@
+---
+title: "XState Effect: Observing actors"
+description: Send events and observe workflow state, results and notifications.
+---
+
+Use these functions with an `EffectActor`, a child from `snapshot.children` or another XState actor reference.
+
+| Function | Result |
+| --- | --- |
+| `send(actor, event)` | Enqueues an event as `Effect`. |
+| `snapshots(actor)` | Streams the current snapshot, then changes. |
+| `waitFor(actor, predicate)` | Waits for a matching snapshot. |
+| `join(actor)` | Waits for the actor's final output. |
+| `emitted(actor)` | Streams emitted events. |
+| `inspect(actor)` | Streams system inspection events. |
+| `deadLetters(actor)` | Streams events the system could not deliver. |
+
+## Send, observe and join
+
+This example records a review's state changes and reads its final output:
+
+
+
+```ts
+import { Effect, Stream, pipe } from 'effect';
+import {
+ createEffectActor,
+ join,
+ send,
+ snapshots,
+ waitFor
+} from '@xstate/effect';
+import { createMachine } from 'xstate';
+
+const reviewMachine = createMachine({
+ output: () => ({ approved: true }),
+ initial: 'pending',
+ states: {
+ pending: { on: { APPROVE: { target: 'approved' } } },
+ approved: { type: 'final' }
+ }
+});
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(reviewMachine);
+ const history = yield* snapshots(actor).pipe(
+ // Send after the subscription sees the initial state.
+ Stream.tap((s) =>
+ s.matches('pending')
+ ? pipe(actor, send({ type: 'APPROVE' }))
+ : Effect.void
+ ),
+ Stream.map((s) => s.value),
+ Stream.runCollect
+ );
+ yield* waitFor(actor, (s) => s.matches('approved'), { timeout: '5 seconds' });
+ return { history: [...history], output: yield* join(actor) };
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result);
+// { history: ['pending', 'approved'], output: { approved: true } }
+```
+
+- `send` enqueues an event; use `waitFor`, `snapshots` or `join` to observe the outcome.
+- `send` and `waitFor` also support pipeable usage, as shown with `pipe(actor, send(...))`.
+- `snapshots` begins with the current snapshot and ends when the actor completes or stops. An error snapshot is emitted before the stream ends.
+- `waitFor` succeeds immediately if the current snapshot already matches. Its `{ timeout }` option bounds the wait.
+- A type predicate passed to `waitFor` narrows the returned snapshot.
+- `join` succeeds with `output` when the actor reaches `done`.
+
+
+Wait and join failures
+
+- `waitFor` fails with `ActorStoppedError` if the actor stops or errors before matching. Its timeout fails with Effect's `Cause.TimeoutError`.
+- `join` fails with `snapshot.error` when the actor errors, or `ActorStoppedError` when it stops without output.
+- `join` on `fromEffect` logic preserves the Effect's typed error. A machine's error type is `unknown`: actions can throw arbitrary values and unhandled child errors can fail the machine.
+- Model expected domain outcomes as final states with output. Handle unexpected machine errors with `Effect.catch`, or use `Effect.orDie` to treat them as defects.
+
+
+
+## Stream notifications
+
+Use `emitted` for notifications sent with `enq.emit` or `EffectSourceArgs.emit`. This workflow emits a reminder every second while a review is pending:
+
+
+
+```ts
+import { Effect, Schema, Stream } from 'effect';
+import { createEffectActor, emitted, setupEffect } from '@xstate/effect';
+
+const reminderMachine = setupEffect({
+ schemas: {
+ emitted: { reminder: Schema.Struct({ message: Schema.String }) }
+ }
+}).createMachine({
+ initial: 'waiting',
+ states: {
+ waiting: { after: { 1000: { target: 'reminding' } } },
+ reminding: {
+ entry: (_, enq) =>
+ enq.emit({ type: 'reminder', message: 'Review pending' }),
+ after: { 0: { target: 'waiting' } }
+ }
+ }
+});
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(reminderMachine);
+ return [...(yield* emitted(actor).pipe(Stream.take(1), Stream.runCollect))];
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // [{ type: 'reminder', message: 'Review pending' }]
+```
+
+`Stream.take(1)` ends this consumer after one reminder. Use `Stream.runForEach` for a subscriber that handles ongoing notifications. Emitted events are not replayed; start the consumer before the events you need to observe.
+
+`emitted` ends when the actor completes, errors or stops. Interrupting the consumer also ends it and removes its listener.
+
+## Inspect execution
+
+`inspect(actor)` streams [inspection events](../../../docs/inspection.md) for the actor's system. Use `Stream.runForEach(inspect(actor), ...)` to record actor creation and transitions. Start that consumer before the events you want to inspect, and keep it in the same scope as the actor.
+
+For a visual inspector, forward `actor.inspect` events through the SDK's `actor`, `event` and `snapshot` methods, using session IDs to identify actors across execution steps. This demo uses the optional `INSPECT=1` flag and releases the subscription and inspector with its Effect scope:
+
+
+
+```ts
+import { createInspector } from '@statelyai/sdk';
+import { Effect } from 'effect';
+import type { Snapshot } from 'xstate';
+import {
+ createEffectActor,
+ fromEffect,
+ join,
+ send,
+ setupEffect
+} from '@xstate/effect';
+
+const reviewMachine = setupEffect({
+ actors: { publish: fromEffect(Effect.succeed('Release published')) }
+}).createMachine({
+ id: 'releaseReview',
+ output: () => 'Release published',
+ initial: 'awaitingApproval',
+ states: {
+ awaitingApproval: { on: { APPROVE: { target: 'publishing' } } },
+ publishing: { invoke: { src: 'publish', onDone: { target: 'published' } } },
+ published: { type: 'final' }
+ }
+});
+
+// Keep wire snapshots JSON-safe; actor snapshots contain live child references.
+const inspectorSnapshot = (snapshot: Snapshot) => ({
+ status: snapshot.status,
+ ...('value' in snapshot ? { value: snapshot.value } : {})
+});
+
+export const program = Effect.gen(function* () {
+ const inspector = yield* Effect.acquireRelease(
+ Effect.sync(() =>
+ process.env.INSPECT === '1' ? createInspector() : undefined
+ ),
+ (inspector) => Effect.sync(() => inspector?.destroy())
+ );
+ const actor = yield* createEffectActor(reviewMachine);
+ if (inspector) {
+ inspector.actor(actor.sessionId!, {
+ machine: reviewMachine.config,
+ snapshot: inspectorSnapshot(actor.getSnapshot())
+ });
+ yield* Effect.acquireRelease(
+ Effect.sync(() =>
+ actor.inspect((event) => {
+ // Session IDs stay stable across Effect's pure execution steps.
+ const id = event.actorRef.sessionId!;
+ if (event.type === '@xstate.actor') {
+ inspector.actor(id, {
+ parent: event.parentRef?.sessionId,
+ snapshot: inspectorSnapshot(event.snapshot)
+ });
+ } else {
+ inspector.event(id, event.event, {
+ source: event.sourceRef?.sessionId
+ });
+ inspector.snapshot(
+ id,
+ inspectorSnapshot(event.snapshot),
+ event.event
+ );
+ if (event.snapshot.status !== 'active') inspector.stop(id);
+ }
+ })
+ ),
+ (subscription) => Effect.sync(() => subscription.unsubscribe())
+ );
+ // Let the inspector connect before the demo sends its first event.
+ yield* Effect.promise(() => inspector.ready);
+ }
+ yield* send(actor, { type: 'APPROVE' });
+ return yield* join(actor);
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // 'Release published'
+```
+
+Set `INSPECT=1` when running the program to open the Stately inspector and send machine definitions, snapshots and events to its hosted relay. Without the flag, the demo runs locally.
+
+## Dead letters
+
+Observe `deadLetters` to diagnose delivery failures. For example, run `Stream.runForEach(deadLetters(actor), (rejection) => Effect.logWarning(rejection))` in a scoped fiber while the actor is in use.
+
+Each rejection includes the event and a reason:
+
+- `stopped`: the target has stopped;
+- `invalidEvent`: the payload failed the target's runtime schema validation;
+- `internalEvent`: an internal event was sent from outside its owning actor.
+
+A delivered event can still have no transition in the current state. Dead letters describe delivery, not whether the workflow changed state.
+
+
+Why send does not fail
+
+`send` has no typed failures. A dead letter is reported through `system.onRejectedEvent`, separately from actor errors and inspection events. `deadLetters` removes that listener when the stream ends.
+
+
diff --git a/xstate-effect/docs/quick-start.md b/xstate-effect/docs/quick-start.md
new file mode 100644
index 00000000..e6f02958
--- /dev/null
+++ b/xstate-effect/docs/quick-start.md
@@ -0,0 +1,152 @@
+---
+title: "XState Effect: Quick start"
+description: Combine event-driven workflows with Effect services, cancellation and testing.
+---
+
+XState models how a workflow responds to events. Effect runs the work inside it. Use them together when a process needs both:
+
+- **Explicit states:** show whether a release is waiting for approval, deploying, failed or complete.
+- **Events over time:** accept approval from a person, cancellation from a UI or retry from an operator.
+- **Effect services:** provide the same dependencies, clock and tracing to the machine's work.
+- **Scoped lifetime:** stop the actor and interrupt its hosted Effects when its scope closes.
+
+## Install
+
+This package is experimental. It targets XState v6 alpha and Effect 4.
+
+```bash
+npm install @xstate/effect@alpha xstate@alpha effect@^4
+```
+
+## Model a release approval
+
+A release waits for approval for up to 30 seconds. Approval starts deployment; cancellation is available while waiting or deploying. If deployment fails, an operator can retry.
+
+
+
+```ts
+import { Context, Effect, Schema } from 'effect';
+import {
+ createEffectActor,
+ fromEffect,
+ send,
+ setupEffect,
+ waitFor
+} from '@xstate/effect';
+
+export class Deployments extends Context.Service<
+ Deployments,
+ { readonly deploy: (release: string) => Effect.Effect }
+>()('@app/Deployments') {}
+
+const deploy = fromEffect({
+ schemas: { input: Schema.Struct({ release: Schema.String }) },
+ effect: ({ input }) => Deployments.use((api) => api.deploy(input.release))
+});
+
+export const approvalMachine = setupEffect({
+ schemas: { input: Schema.Struct({ release: Schema.String }) },
+ actors: { deploy }
+}).createMachine({
+ context: ({ input }) => ({ release: input.release, url: '' }),
+ initial: 'awaitingApproval',
+ states: {
+ awaitingApproval: {
+ after: { 30000: { target: 'expired' } },
+ on: {
+ APPROVE: { target: 'deploying' },
+ CANCEL: { target: 'cancelled' }
+ }
+ },
+ deploying: {
+ invoke: {
+ src: 'deploy',
+ input: ({ context }) => ({ release: context.release }),
+ onDone: ({ context, event }) => ({
+ target: 'deployed',
+ context: { ...context, url: event.output }
+ }),
+ onError: { target: 'failed' }
+ },
+ on: { CANCEL: { target: 'cancelled' } }
+ },
+ failed: {
+ on: {
+ RETRY: { target: 'deploying' },
+ CANCEL: { target: 'cancelled' }
+ }
+ },
+ deployed: { type: 'final' },
+ expired: { type: 'final' },
+ cancelled: { type: 'final' }
+ }
+});
+
+export const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(approvalMachine, {
+ input: { release: 'v1.2.0' }
+ });
+ // A UI, webhook or CLI can send this event after a person approves.
+ yield* send(actor, { type: 'APPROVE' });
+ const snapshot = yield* waitFor(actor, (s) => s.matches('deployed'), {
+ timeout: '5 seconds'
+ });
+ return snapshot.context.url;
+});
+
+export const result = await Effect.runPromise(
+ program.pipe(
+ Effect.scoped,
+ Effect.provideService(Deployments, {
+ // Replace this demo service with your deployment API.
+ deploy: (release) => Effect.succeed(`https://example.com/${release}`)
+ })
+ )
+);
+console.log(result); // 'https://example.com/v1.2.0'
+```
+
+The service is a local demo, so the example runs without credentials. Replace `Deployments` with your API implementation when connecting it to your application.
+
+The machine makes the workflow rules visible:
+
+- `APPROVE` starts deployment only from `awaitingApproval`.
+- `after` expires an unanswered approval using Effect's clock.
+- Leaving `deploying` interrupts the invoked Effect. Your service can use Effect's interruption and cleanup support to release local resources.
+- `failed` accepts `RETRY`; completed and cancelled workflows are final.
+
+Effect provides the deployment service and owns the actor's lifetime. You can test the same machine with a different service and `TestClock`.
+
+
+Cancellation and external work
+
+Interrupting the local deployment Effect does not undo a deployment already accepted by an external API. If your API supports cancellation or rollback, model that operation explicitly.
+
+
+
+## Run Effect-backed logic
+
+Start Effect-backed logic with `createEffectActor`, inside an Effect scope.
+
+
+Why use createEffectActor?
+
+`createEffectActor` supplies the Effect runtime that hosts the actor's Effects. Starting Effect-backed logic with XState's `createActor` puts it in the `error` status because that host is missing.
+
+
+
+## How it runs
+
+- XState calculates the next snapshot and the actions to run from each event.
+- An Effect fiber processes the actor's mailbox in order.
+- Timers use Effect's `Clock`; declared Effect actions run without blocking the mailbox.
+- Child actors use the same Effect host and its services.
+
+Use `waitFor`, `join` or `snapshots` to read the result of a send. The actor processes events asynchronously.
+
+## Next steps
+
+- [Actors](actors.md): scopes, services and lifetime.
+- [Observing actors](observing-actors.md): snapshots, results and event streams.
+- [Effect actor logic](effect-logic.md): tasks, upload progress and deployment feeds.
+- [Testing and errors](testing-and-errors.md): deadlines, retries and typed failures.
diff --git a/xstate-effect/docs/schemas-and-actions.md b/xstate-effect/docs/schemas-and-actions.md
new file mode 100644
index 00000000..149bfcf3
--- /dev/null
+++ b/xstate-effect/docs/schemas-and-actions.md
@@ -0,0 +1,171 @@
+---
+title: "XState Effect: Schemas and actions"
+description: Type workflow data and run background work with setupEffect.
+---
+
+`setupEffect` is the Effect-aware form of XState's [`setup`](../../../docs/setup-and-provide.md).
+
+- Declare input, context, events and output with Effect schemas.
+- Register actions that return Effects.
+- Register actors, guards and delays as you would with `setup`.
+- Start the machine with `createEffectActor`.
+
+## Schemas and background actions
+
+This machine accepts a typed approval event and records an audit entry without blocking its transition:
+
+
+
+```ts
+import { Context, Effect, Latch, Schema } from 'effect';
+import { createEffectActor, send, setupEffect, waitFor } from '@xstate/effect';
+import { standardSchemaValidator } from 'xstate/validation';
+
+class Audit extends Context.Service<
+ Audit,
+ { readonly record: (reviewer: string) => Effect.Effect }
+>()('@app/Audit') {}
+
+const reviewMachine = setupEffect({
+ schemas: { events: { APPROVE: Schema.Struct({ reviewer: Schema.String }) } },
+ actions: {
+ audit: ({ event }) => Audit.use((audit) => audit.record(event.reviewer))
+ }
+}).createMachine({
+ validator: standardSchemaValidator(),
+ initial: 'pending',
+ states: {
+ pending: {
+ on: {
+ APPROVE: (args, enq) => {
+ enq(args.actions.audit, args);
+ return { target: 'approved' };
+ }
+ }
+ },
+ // Keep the actor alive while its background audit runs.
+ approved: {}
+ }
+});
+
+const program = Effect.gen(function* () {
+ const recorded = yield* Latch.make();
+ const actor = yield* createEffectActor(reviewMachine).pipe(
+ Effect.provideService(Audit, { record: () => Effect.asVoid(recorded.open) })
+ );
+ yield* send(actor, { type: 'APPROVE', reviewer: 'Ada' });
+ yield* waitFor(actor, (s) => s.matches('approved'));
+ // Wait for the demo audit before closing the scope.
+ yield* recorded.await;
+ return actor.getSnapshot().value;
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // 'approved'
+```
+
+The latch lets this demo wait for the audit before closing its scope. In an application, keep the actor alive for the workflow's lifetime.
+
+### Effect schemas
+
+`setupEffect` accepts Effect schemas in `schemas`, per-state `states` declarations and `extend`.
+
+- Types come from the decoded `Schema.Type`; no manual conversion is needed.
+- Per-state schemas narrow context with [`taggedState`](matching-states.md).
+- Standard Schemas can be mixed with Effect schemas. `EffectSchemaLike` represents either kind.
+- `fromEffect` also accepts Effect input and output schemas.
+
+### Runtime validation
+
+Add `standardSchemaValidator()` from `xstate/validation` to check values at runtime, as above. Without a validator, schemas provide types only.
+
+
+Runtime schema constraints
+
+XState checks values but does not replace them with decoded values. With runtime validation enabled, encoded and decoded types must match; transforming schemas such as `Schema.NumberFromString` are rejected by TypeScript. Schemas must decode synchronously, without service requirements.
+
+
+
+## Choose an action or an actor
+
+- Use an **Effect action** for background work: audit entries, logging, telemetry or notifications. The transition commits without waiting for it.
+- Use an **invoked Effect actor** when success or failure decides the next state. `fromEffect` gives `onDone` and `onError` typed results and interrupts the task when its invoking state exits.
+
+An Effect action runs in the actor's Effect context. Its failures and defects route to the current state's `onError`; stopping the actor interrupts it without reporting an error.
+
+
+Action execution and completion
+
+The action function is called synchronously during the transition. The returned Effect runs after the transition commits, in a forked fiber, without blocking subsequent events.
+
+- The transition enqueues the action with explicit arguments: `enq(args.actions.audit, args)`.
+- `EffectActionArgs` and `EffectAction` name the argument and action types.
+- An Effect action cannot use the transition's enqueue API after the transition. It can call `self.send` to send a new event.
+- A final state or a closing scope can interrupt pending background work. Invoke a task when the workflow must wait for completion.
+
+
+
+## Provide an action
+
+Use `machine.provide({ actions })` to replace an action for a particular environment. The provided machine requires the replacement's services. In this example, an audit implementation adds the `Audit` service:
+
+
+
+```ts
+import { Context, Effect, Latch } from 'effect';
+import { createEffectActor, send, setupEffect } from '@xstate/effect';
+
+class Audit extends Context.Service }>()(
+ 'Audit'
+) {}
+
+const recorded = Latch.makeUnsafe();
+const machine = setupEffect({
+ actions: { audit: (_args) => Effect.void }
+}).createMachine({
+ on: { APPROVE: (args, enq) => enq(args.actions.audit, args) }
+});
+
+const auditedMachine = machine.provide({
+ actions: { audit: () => Audit.use((audit) => audit.record) }
+});
+
+const program = Effect.gen(function* () {
+ // The override adds Audit to this machine's required services.
+ const actor = yield* createEffectActor(auditedMachine);
+ yield* send(actor, { type: 'APPROVE' });
+ yield* recorded.await;
+ return 'approval recorded';
+});
+
+export const result = await Effect.runPromise(
+ program.pipe(
+ Effect.scoped,
+ Effect.provideService(Audit, { record: Effect.asVoid(recorded.open) })
+ )
+);
+console.log(result); // approval recorded
+```
+
+- Other actions and their service requirements stay in place.
+- Replacing the audit with an action that requires a different service updates the required service type again.
+- A plain action can replace an Effect action and remove its service requirement.
+
+## Declared sources
+
+Declare Effect actions and spawned Effect actors so their services contribute to [requirement inference](actors.md#requirements).
+
+- Register actions with `setupEffect({ actions })`, then enqueue the named action.
+- Register spawned logic in `actors`, then use `enq.spawn(args.actors.worker)`.
+- Inline `invoke.src` logic is supported and contributes requirements; declaring it in `actors` also gives it a reusable name.
+
+
+Inline action and spawn pitfalls
+
+An inline callback such as `enq(() => Effect.log('saved'))` creates an Effect that is discarded. Inline Effect logic passed to `enq.spawn` is rejected at runtime because its service requirements cannot be inferred.
+
+The `xstate-effect/no-inline-effect` oxlint rule checks these two patterns. It recognizes the root identifier `Effect`; Effects returned by helper functions are outside that check.
+
+The rule is not published as a package. To use it, install `@oxlint/plugins`, copy [`oxlint-plugin-xstate-effect.ts`](https://github.com/statelyai/xstate/blob/next/scripts/oxlint-plugin-xstate-effect.ts) from the XState repository and configure it in `jsPlugins`. Loading the TypeScript source requires Node.js 22.18+ or a newer release with native TypeScript support.
+
+
diff --git a/xstate-effect/docs/testing-and-errors.md b/xstate-effect/docs/testing-and-errors.md
new file mode 100644
index 00000000..68d65b2d
--- /dev/null
+++ b/xstate-effect/docs/testing-and-errors.md
@@ -0,0 +1,198 @@
+---
+title: "XState Effect: Testing and errors"
+description: Test deadlines, recover from failures and supervise workflow actors.
+---
+
+Test the workflow with its real machine and provide local Effect services. Use `waitFor` for state assertions and `join` for final output.
+
+## TestClock
+
+A release approval expires after 30 seconds. `TestClock` drives the same `after` transition without waiting for real time:
+
+
+
+```ts
+import { Effect } from 'effect';
+import { TestClock } from 'effect/testing';
+import { createEffectActor, waitFor } from '@xstate/effect';
+import { createMachine } from 'xstate';
+
+const reviewMachine = createMachine({
+ initial: 'pending',
+ states: {
+ pending: {
+ after: { 30000: { target: 'expired' } },
+ on: { APPROVE: { target: 'approved' } }
+ },
+ approved: { type: 'final' },
+ expired: { type: 'final' }
+ }
+});
+
+const test = Effect.gen(function* () {
+ const actor = yield* createEffectActor(reviewMachine);
+ yield* TestClock.adjust('30 seconds');
+ const snapshot = yield* waitFor(actor, (s) => s.matches('expired'));
+ return snapshot.value;
+});
+
+export const result = await Effect.runPromise(
+ test.pipe(Effect.scoped, Effect.provide(TestClock.layer()))
+);
+console.log(result); // 'expired', with no 30-second wait
+```
+
+- Timers use Effect's `Clock`, including delayed sends.
+- `waitFor` and `join` fail if the actor stops before reaching the expected result.
+- Add `waitFor`'s `{ timeout }` to bound a wait. With `TestClock`, advance the clock to trigger that timeout too.
+- Use `inspect` for execution traces and `deadLetters` for delivery failures.
+
+XState's [path generation](../../../docs/model-based-testing.md) works on the machine itself. Execute generated paths against an actor from `createEffectActor`, or use `testPaths()` from `@xstate/test`.
+
+## Retry a task
+
+Use Effect's retry combinators inside `fromEffect` for transient failures within one task. This local publisher succeeds on its third attempt:
+
+
+
+```ts
+import { Effect, Schedule } from 'effect';
+import { createEffectActor, fromEffect, join } from '@xstate/effect';
+
+let attempts = 0;
+const publish = fromEffect(
+ Effect.suspend(() => {
+ attempts++;
+ return attempts < 3
+ ? Effect.fail(new Error('Publisher temporarily unavailable'))
+ : Effect.succeed('published');
+ }).pipe(
+ Effect.retry({ schedule: Schedule.exponential('10 millis'), times: 3 })
+ )
+);
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(publish);
+ return yield* join(actor);
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // 'published', on attempt 3
+```
+
+Use a machine state when retry requires a person or an event. The [quick start](quick-start.md) accepts `RETRY` only after deployment fails.
+
+## Supervise an actor
+
+Retry a scoped unit when a failure should create a fresh actor:
+
+
+
+```ts
+import { Effect, Schedule } from 'effect';
+import { createEffectActor, fromEffect, join } from '@xstate/effect';
+
+let attempts = 0;
+const worker = fromEffect(
+ Effect.suspend(() => {
+ attempts++;
+ return attempts < 3
+ ? Effect.fail(new Error('Worker disconnected'))
+ : Effect.succeed('complete');
+ })
+);
+
+const attempt = Effect.gen(function* () {
+ const actor = yield* createEffectActor(worker);
+ return yield* join(actor);
+});
+
+// Each failed attempt closes its scope before a new actor starts.
+const supervised = Effect.scoped(attempt).pipe(
+ Effect.retry({ schedule: Schedule.exponential('10 millis'), times: 3 })
+);
+
+export const result = await Effect.runPromise(supervised);
+console.log(result); // 'complete', from the third actor
+```
+
+Each attempt stops its actor and releases its resources before the next attempt starts.
+
+
+Choosing failures to retry
+
+`join` reports the actor's failure, so the retry policy sees that error. A machine's error type is `unknown`; narrow it if only some failures should be retried. Keep `Effect.scoped` inside the retry, so failed actors are released after each attempt.
+
+Retrying can repeat external operations. Use stable operation IDs or idempotent APIs when repetition could create duplicate work.
+
+
+
+## Handle typed failures
+
+A `fromEffect` actor preserves its Effect's error type. Handle a domain failure with `Effect.catchTag`:
+
+
+
+```ts
+import { Data, Effect } from 'effect';
+import { createEffectActor, fromEffect, join } from '@xstate/effect';
+
+class PublishFailed extends Data.TaggedError('PublishFailed')<{
+ readonly reason: string;
+}> {}
+
+const publish = fromEffect(
+ Effect.fail(new PublishFailed({ reason: 'Release needs approval' }))
+);
+
+const program = Effect.gen(function* () {
+ const actor = yield* createEffectActor(publish);
+ return yield* join(actor).pipe(
+ Effect.catchTag('PublishFailed', (error) => Effect.succeed(error.reason))
+ );
+});
+
+export const result = await Effect.runPromise(Effect.scoped(program));
+console.log(result); // 'Release needs approval'
+```
+
+For machine workflows, expected outcomes such as declined or expired can be final states with output. `join(machineActor)` has an `unknown` error channel for unexpected machine failures.
+
+## Error reference
+
+| Error | Raised by |
+| --- | --- |
+| `ActorStoppedError` | `waitFor` when the actor stops or errors before matching; `join` when it stops without output. |
+| `EffectInterruptedError` | Effect logic that interrupts itself. |
+| `Cause.TimeoutError` | `waitFor` with a timeout, or Effect's timeout combinators. |
+
+- `ActorStoppedError` includes `actorId` and `snapshot`.
+- `EffectInterruptedError` includes its interrupt `cause`.
+- Both package errors are `Data.TaggedError` classes.
+- An actor's own typed failure is available through `snapshot.error` and `join`; `ErrorFrom` names its type.
+
+
+Observe root actor errors
+
+A root Effect actor's error is a value. Read it with `join`, `waitFor`, `subscribe` or the `result` atom. An unobserved errored actor is silent, like a failed forked fiber.
+
+
+
+## Persistence
+
+`actor.getPersistedSnapshot()` records the actor's state. It does not record progress inside a running Effect: an Effect task or stream that was running when the snapshot was taken starts again from the beginning after a restore. See [persisting and restoring](actors.md#persisting-and-restoring).
+
+## Tracing
+
+Hosted Effects run inside spans:
+
+| Span | Work |
+| --- | --- |
+| `fromEffect` | A task actor's Effect. |
+| `fromEffectStream` | A stream of snapshot values. |
+| `fromEffectEventStream` | A stream of parent events. |
+| `action.` | A declared Effect action. |
+
+Spans carry `xstate.actor.id` and `xstate.actor.address`. The address is the actor's `/`-joined path from the root, identifying its place in the actor tree.
+
+Provide a `Tracer` to record and export spans.
diff --git a/xstate-effect/package.json b/xstate-effect/package.json
new file mode 100644
index 00000000..c4179485
--- /dev/null
+++ b/xstate-effect/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "@xstate/effect",
+ "version": "0.1.0-alpha.7",
+ "type": "module",
+ "description": "Effect integration for XState",
+ "keywords": [
+ "xstate",
+ "effect",
+ "state machine",
+ "statechart"
+ ],
+ "author": "David Khourshid ",
+ "homepage": "https://github.com/statelyai/xstate/tree/main/packages/xstate-effect#readme",
+ "license": "MIT",
+ "exports": {
+ "./atom": "./dist/xstate-effect-atom.js",
+ ".": "./dist/xstate-effect.js",
+ "./package.json": "./package.json"
+ },
+ "sideEffects": false,
+ "files": [
+ "dist"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git+ssh://git@github.com/statelyai/xstate.git"
+ },
+ "bugs": {
+ "url": "https://github.com/statelyai/xstate/issues"
+ },
+ "scripts": {},
+ "peerDependencies": {
+ "effect": "^4.0.0",
+ "xstate": "workspace:^"
+ },
+ "devDependencies": {
+ "effect": "4.0.0",
+ "fast-check": "4.10.2",
+ "xstate": "workspace:^"
+ },
+ "preconstruct": {
+ "entrypoints": [
+ "./index.ts",
+ "./atom.ts"
+ ]
+ }
+}
diff --git a/xstate-effect/src/actor.test.ts b/xstate-effect/src/actor.test.ts
new file mode 100644
index 00000000..fbad373f
--- /dev/null
+++ b/xstate-effect/src/actor.test.ts
@@ -0,0 +1,459 @@
+import { expectTypeOf } from 'vitest';
+import { Cause, Duration, Effect, Exit, Fiber, Scope, Stream } from 'effect';
+import {
+ createMachine,
+ types,
+ type AnyActorRef,
+ type SnapshotFrom
+} from 'xstate';
+import {
+ ActorStoppedError,
+ EffectActor,
+ createEffectActor,
+ emitted,
+ fromEffect,
+ inspect,
+ send,
+ snapshots,
+ join,
+ waitFor
+} from './index.ts';
+
+/**
+ * Polls until `predicate` holds. The actor processes events on its own fiber,
+ * so tests wait for the condition they assert on.
+ */
+const until = async (predicate: () => boolean, timeoutMs = 1000) => {
+ const deadline = Date.now() + timeoutMs;
+ while (!predicate()) {
+ if (Date.now() > deadline) {
+ throw new Error('Timed out waiting for condition');
+ }
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ }
+};
+
+let scopes: Scope.Closeable[] = [];
+
+afterEach(async () => {
+ const pending = scopes;
+ scopes = [];
+ for (const scope of pending) {
+ await Effect.runPromise(Scope.close(scope, Exit.void));
+ }
+});
+
+/** Runs a scoped Effect in a scope that stays open until the test ends. */
+const runScoped = async (
+ effect: Effect.Effect
+): Promise => {
+ const scope = await Effect.runPromise(Scope.make());
+ scopes.push(scope);
+ return Effect.runPromise(Scope.provide(effect, scope));
+};
+
+/**
+ * Runs `drive` right after the API under test subscribes to the actor, so
+ * tests never race the Effect scheduler with a timer.
+ */
+const afterSubscribe = (actor: AnyActorRef, drive: () => void): void => {
+ const actorSubscribe = actor.subscribe.bind(actor);
+ let driven = false;
+ actor.subscribe = ((...args: Parameters) => {
+ const subscription = actorSubscribe(...args);
+ if (!driven) {
+ driven = true;
+ queueMicrotask(drive);
+ }
+ return subscription;
+ }) as typeof actor.subscribe;
+};
+
+/** The `actor.inspect` counterpart of {@link afterSubscribe}. */
+const afterInspect = (actor: EffectActor, drive: () => void): void => {
+ const actorInspect = actor.inspect.bind(actor);
+ actor.inspect = ((observer: Parameters[0]) => {
+ const subscription = actorInspect(observer);
+ queueMicrotask(drive);
+ return subscription;
+ }) as typeof actor.inspect;
+};
+
+const counterMachine = createMachine({
+ schemas: {
+ events: {
+ INCREMENT: types<{}>(),
+ FINISH: types<{}>()
+ }
+ },
+ context: { count: 0 },
+ initial: 'counting',
+ states: {
+ counting: {
+ on: {
+ INCREMENT: ({ context }) => ({
+ context: { count: context.count + 1 }
+ }),
+ FINISH: { target: 'finished' }
+ }
+ },
+ finished: { type: 'final' }
+ },
+ output: ({ context }) => ({ count: context.count })
+});
+
+type CounterSnapshot = SnapshotFrom;
+type DoneCounterSnapshot = CounterSnapshot & { status: 'done' };
+
+/** A type-predicate predicate, so `waitFor` narrows what it resolves with. */
+const isDone = (snapshot: CounterSnapshot): snapshot is DoneCounterSnapshot =>
+ snapshot.status === 'done';
+
+const emitterMachine = createMachine({
+ initial: 'active',
+ states: {
+ active: {
+ on: {
+ PING: (_args, enq) => {
+ enq.emit({ type: 'pinged' });
+ }
+ }
+ }
+ }
+});
+
+describe('send', () => {
+ it('sends an event to the actor', async () => {
+ await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+
+ yield* send(actor, { type: 'INCREMENT' });
+ yield* send(actor, { type: 'INCREMENT' });
+ yield* waitFor(actor, (state) => state.context.count === 2);
+
+ expect(actor.getSnapshot().context).toEqual({ count: 2 });
+ })
+ );
+ });
+
+ it('accepts the data-last form', async () => {
+ await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+
+ yield* send({ type: 'INCREMENT' } as const)(actor);
+ yield* waitFor(actor, (state) => state.context.count === 1);
+
+ expect(actor.getSnapshot().context).toEqual({ count: 1 });
+ })
+ );
+ });
+
+ it('rejects events the actor cannot receive', async () => {
+ await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+
+ const sendUnknownEvent = () =>
+ // @ts-expect-error -- the event type is derived from the actor
+ send(actor, { type: 'UNKNOWN' });
+
+ void sendUnknownEvent;
+ })
+ );
+ });
+});
+
+describe('snapshots', () => {
+ it('emits the current snapshot, then every change, and ends on completion', async () => {
+ const collected = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+ afterSubscribe(actor, () => {
+ actor.send({ type: 'INCREMENT' });
+ actor.send({ type: 'FINISH' });
+ });
+
+ return yield* Stream.runCollect(snapshots(actor));
+ })
+ );
+
+ expect(collected.map((snapshot) => snapshot.context.count)).toEqual([
+ 0, 1, 1
+ ]);
+ expect(collected.map((snapshot) => snapshot.status)).toEqual([
+ 'active',
+ 'active',
+ 'done'
+ ]);
+ });
+
+ it('emits the error snapshot and ends when the actor errors', async () => {
+ const failure = { code: 'BOOM' as const };
+ const collected = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(
+ fromEffect(Effect.fail(failure).pipe(Effect.delay(10)))
+ );
+
+ return yield* Stream.runCollect(snapshots(actor));
+ })
+ );
+
+ expect(collected.map((snapshot) => snapshot.status)).toEqual([
+ 'active',
+ 'error'
+ ]);
+ expect(collected[1].error).toEqual(failure);
+ });
+
+ it('unsubscribes from the actor when the stream is interrupted', async () => {
+ let unsubscribed = 0;
+ const collected = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+ const actorSubscribe = actor.subscribe.bind(actor);
+ actor.subscribe = ((...args: Parameters) => {
+ const subscription = actorSubscribe(...args);
+ queueMicrotask(() => {
+ actor.send({ type: 'INCREMENT' });
+ actor.send({ type: 'INCREMENT' });
+ });
+ return {
+ unsubscribe: () => {
+ unsubscribed++;
+ subscription.unsubscribe();
+ }
+ };
+ }) as typeof actor.subscribe;
+
+ return yield* Stream.runCollect(snapshots(actor).pipe(Stream.take(2)));
+ })
+ );
+
+ expect(collected.map((snapshot) => snapshot.context.count)).toEqual([0, 1]);
+ expect(unsubscribed).toBe(1);
+ });
+});
+
+describe('emitted', () => {
+ it('streams emitted events and ends when the actor stops', async () => {
+ const collected: unknown[] = [];
+ await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(emitterMachine);
+ let listening = false;
+ const actorOn = actor.on.bind(actor);
+ actor.on = ((...args: Parameters) => {
+ listening = true;
+ return actorOn(...args);
+ }) as typeof actor.on;
+
+ const fiber = yield* Effect.forkScoped(
+ Stream.runForEach(emitted(actor), (event) =>
+ Effect.sync(() => {
+ collected.push(event);
+ })
+ )
+ );
+ yield* Effect.promise(() => until(() => listening));
+
+ actor.send({ type: 'PING' });
+ actor.send({ type: 'PING' });
+ yield* Effect.promise(() => until(() => collected.length === 2));
+
+ actor.stop();
+ yield* Fiber.join(fiber);
+ })
+ );
+
+ expect(collected).toEqual([{ type: 'pinged' }, { type: 'pinged' }]);
+ });
+});
+
+describe('waitFor', () => {
+ it('resolves immediately when the current snapshot matches', async () => {
+ const snapshot = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+
+ return yield* waitFor(actor, (state) => state.context.count === 0);
+ })
+ );
+
+ expect(snapshot.context).toEqual({ count: 0 });
+ });
+
+ it('resolves on the first later snapshot that matches', async () => {
+ const snapshot = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+ afterSubscribe(actor, () => {
+ actor.send({ type: 'INCREMENT' });
+ actor.send({ type: 'INCREMENT' });
+ });
+
+ return yield* waitFor(actor, (state) => state.context.count === 2);
+ })
+ );
+
+ expect(snapshot.context).toEqual({ count: 2 });
+ });
+
+ it('accepts the data-last form', async () => {
+ const snapshot = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+ afterSubscribe(actor, () => {
+ actor.send({ type: 'INCREMENT' });
+ });
+
+ return yield* waitFor(
+ (state: CounterSnapshot) => state.context.count === 1
+ )(actor);
+ })
+ );
+
+ expect(snapshot.context).toEqual({ count: 1 });
+ });
+
+ it('narrows the snapshot with a type-predicate predicate', async () => {
+ const snapshot = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+ afterSubscribe(actor, () => {
+ actor.send({ type: 'FINISH' });
+ });
+
+ return yield* waitFor(actor, isDone);
+ })
+ );
+
+ snapshot satisfies { status: 'done' };
+ expect(snapshot.output).toEqual({ count: 0 });
+ });
+
+ it('fails with ActorStoppedError when the actor stops first', async () => {
+ const error = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+ afterSubscribe(actor, () => {
+ actor.stop();
+ });
+
+ return yield* Effect.flip(
+ waitFor(actor, (state) => state.context.count === 10)
+ );
+ })
+ );
+
+ expect(error).toBeInstanceOf(ActorStoppedError);
+ expect(error.message).toMatch(/stopped before completing/);
+ });
+
+ it('fails with TimeoutError when the timeout elapses', async () => {
+ const error = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+
+ return yield* Effect.flip(
+ waitFor(actor, (state) => state.context.count === 10, {
+ timeout: Duration.millis(10)
+ })
+ );
+ })
+ );
+
+ expect(Cause.isTimeoutError(error)).toBe(true);
+ });
+});
+
+describe('join', () => {
+ it('succeeds with the actor output when it is done', async () => {
+ const output = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+ afterSubscribe(actor, () => {
+ actor.send({ type: 'INCREMENT' });
+ actor.send({ type: 'FINISH' });
+ });
+
+ return yield* join(actor);
+ })
+ );
+
+ expect(output).toEqual({ count: 1 });
+ });
+
+ it('fails with the typed actor error', async () => {
+ const failure = { code: 'X' as const };
+ const error = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(
+ fromEffect(Effect.fail(failure).pipe(Effect.delay(10)))
+ );
+
+ return yield* Effect.flip(join(actor));
+ })
+ );
+
+ error satisfies { code: 'X' } | ActorStoppedError;
+ expect(error).toEqual(failure);
+ });
+
+ it('exposes machine errors as unknown and preserves the thrown value', async () => {
+ const failure = { code: 'MACHINE_FAILURE' };
+ const machine = createMachine({
+ on: {
+ FAIL: () => {
+ throw failure;
+ }
+ }
+ });
+ const error = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(machine);
+ const result = join(actor);
+ expectTypeOf>().toEqualTypeOf();
+ afterSubscribe(actor, () => actor.send({ type: 'FAIL' }));
+ return yield* Effect.flip(result);
+ })
+ );
+
+ expect(error).toBe(failure);
+ });
+
+ it('fails with ActorStoppedError when the actor is stopped', async () => {
+ const error = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+ afterSubscribe(actor, () => {
+ actor.stop();
+ });
+
+ return yield* Effect.flip(join(actor));
+ })
+ );
+
+ expect(error).toBeInstanceOf(ActorStoppedError);
+ });
+});
+
+describe('inspect', () => {
+ it('streams inspection events from the actor system', async () => {
+ const events = await runScoped(
+ Effect.gen(function* () {
+ const actor = yield* createEffectActor(counterMachine);
+ afterInspect(actor, () => {
+ actor.send({ type: 'INCREMENT' });
+ });
+
+ return yield* Stream.runCollect(inspect(actor).pipe(Stream.take(1)));
+ })
+ );
+
+ expect(events.map((event) => event.type)).toEqual(['@xstate.transition']);
+ expect(events[0]).toMatchObject({ event: { type: 'INCREMENT' } });
+ });
+});
diff --git a/xstate-effect/src/actor.ts b/xstate-effect/src/actor.ts
new file mode 100644
index 00000000..77143cf9
--- /dev/null
+++ b/xstate-effect/src/actor.ts
@@ -0,0 +1,415 @@
+import { Cause, Duration, Effect, Queue, Stream } from 'effect';
+import { dual } from 'effect/Function';
+import type {
+ Actor,
+ ActorRef,
+ AnyActor,
+ AnyActorRef,
+ AnyEventObject,
+ EmittedFrom,
+ EventRejection,
+ ErrorFrom,
+ InspectionEvent,
+ OutputFrom,
+ Snapshot,
+ SnapshotFrom,
+ Subscription
+} from 'xstate';
+import type { EffectActor } from './effectActor.ts';
+import { ActorStoppedError } from './errors.ts';
+
+/** The event type accepted by an actor's `send` method. */
+export type SendableEventFrom = Parameters<
+ TActor['send']
+>[0];
+
+/** The event type an actor emits through `actor.on(...)`. */
+export type EmittedEventFrom =
+ TActor extends EffectActor
+ ? EmittedFrom
+ : TActor extends Actor
+ ? EmittedFrom
+ : TActor extends ActorRef
+ ? TEmitted
+ : AnyEventObject;
+
+/** Options for {@link waitFor}. */
+export interface WaitForOptions {
+ /**
+ * Fails with `Cause.TimeoutError` when no snapshot satisfies the predicate
+ * within this duration.
+ */
+ readonly timeout: Duration.Input;
+}
+
+const noopSubscription: Subscription = { unsubscribe: () => {} };
+
+function actorId(actor: AnyActorRef): string {
+ return (actor as Partial).id ?? '(unknown)';
+}
+
+/**
+ * Marks an already-errored actor's error as observed, so XState does not
+ * report it as unhandled: the caller consumes it as a typed failure.
+ */
+function observeError(actor: AnyActorRef): void {
+ actor.subscribe({ error: () => {} }).unsubscribe();
+}
+
+function stoppedError(actor: AnyActorRef): ActorStoppedError {
+ return new ActorStoppedError({
+ actorId: actorId(actor),
+ snapshot: actor.getSnapshot()
+ });
+}
+
+function isActorRef(value: unknown): value is AnyActorRef {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ typeof (value as AnyActorRef).send === 'function' &&
+ typeof (value as AnyActorRef).getSnapshot === 'function'
+ );
+}
+
+/**
+ * Sends an event to an actor. The returned Effect always succeeds: the event
+ * is enqueued, like `actor.send(event)`, and processed on the actor's own
+ * fiber. An event that cannot be delivered (for example to a stopped actor)
+ * is reported as a dead letter, observable with {@link deadLetters}.
+ */
+export const send: {
+ (
+ event: SendableEventFrom
+ ): (actor: TActor) => Effect.Effect;
+ (
+ actor: TActor,
+ event: SendableEventFrom
+ ): Effect.Effect;
+} = dual(
+ 2,
+ (
+ actor: TActor,
+ event: SendableEventFrom
+ ): Effect.Effect =>
+ Effect.sync(() => {
+ actor.send(event);
+ })
+);
+
+/**
+ * Streams an actor's snapshots, starting with the current one. The stream ends
+ * when the actor completes or stops, and emits the error snapshot before
+ * ending when the actor errors. Interrupting the stream unsubscribes from the
+ * actor.
+ */
+export function snapshots(
+ actor: TActor
+): Stream.Stream> {
+ return Stream.callback>((queue) =>
+ Effect.acquireRelease(
+ Effect.sync(() => {
+ const current = actor.getSnapshot();
+ Queue.offerUnsafe(queue, current);
+
+ if (current.status !== 'active') {
+ observeError(actor);
+ Queue.endUnsafe(queue);
+ return noopSubscription;
+ }
+
+ return actor.subscribe({
+ next: (snapshot) => {
+ Queue.offerUnsafe(queue, snapshot);
+ },
+ error: () => {
+ Queue.offerUnsafe(queue, actor.getSnapshot());
+ Queue.endUnsafe(queue);
+ },
+ complete: () => {
+ Queue.endUnsafe(queue);
+ }
+ }) as Subscription;
+ }),
+ (subscription) =>
+ Effect.sync(() => {
+ subscription.unsubscribe();
+ })
+ )
+ );
+}
+
+/**
+ * Streams every event an actor emits, as delivered to `actor.on('*', …)`. The
+ * stream ends when the actor completes, errors or stops. Interrupting the
+ * stream removes the listener.
+ */
+export function emitted(
+ actor: TActor
+): Stream.Stream> {
+ return Stream.callback>((queue) =>
+ Effect.acquireRelease(
+ Effect.sync(() => {
+ const listener = actor.on('*', (event) => {
+ Queue.offerUnsafe(queue, event as EmittedEventFrom);
+ });
+
+ if (actor.getSnapshot().status !== 'active') {
+ Queue.endUnsafe(queue);
+ return [listener, noopSubscription] as const;
+ }
+
+ const subscription = actor.subscribe({
+ error: () => {
+ Queue.endUnsafe(queue);
+ },
+ complete: () => {
+ Queue.endUnsafe(queue);
+ }
+ }) as Subscription;
+
+ return [listener, subscription] as const;
+ }),
+ ([listener, subscription]) =>
+ Effect.sync(() => {
+ listener.unsubscribe();
+ subscription.unsubscribe();
+ })
+ )
+ );
+}
+
+/**
+ * Waits for the first actor snapshot that satisfies `predicate`, succeeding
+ * immediately when the current snapshot already does. Fails with
+ * `ActorStoppedError` if the actor stops or errors first, and with
+ * `Cause.TimeoutError` when `options.timeout` elapses. Interrupting the Effect
+ * unsubscribes from the actor.
+ */
+export const waitFor: {
+ >(
+ predicate: (snapshot: SnapshotFrom) => snapshot is TNarrowed
+ ): (actor: TActor) => Effect.Effect;
+ (
+ predicate: (snapshot: SnapshotFrom) => boolean
+ ): (actor: TActor) => Effect.Effect, ActorStoppedError>;
+ >(
+ predicate: (snapshot: SnapshotFrom) => snapshot is TNarrowed,
+ options: WaitForOptions
+ ): (
+ actor: TActor
+ ) => Effect.Effect;
+ (
+ predicate: (snapshot: SnapshotFrom) => boolean,
+ options: WaitForOptions
+ ): (
+ actor: TActor
+ ) => Effect.Effect<
+ SnapshotFrom,
+ ActorStoppedError | Cause.TimeoutError
+ >;
+ >(
+ actor: TActor,
+ predicate: (snapshot: SnapshotFrom) => snapshot is TNarrowed
+ ): Effect.Effect;
+ (
+ actor: TActor,
+ predicate: (snapshot: SnapshotFrom) => boolean
+ ): Effect.Effect, ActorStoppedError>;
+ >(
+ actor: TActor,
+ predicate: (snapshot: SnapshotFrom) => snapshot is TNarrowed,
+ options: WaitForOptions
+ ): Effect.Effect;
+ (
+ actor: TActor,
+ predicate: (snapshot: SnapshotFrom) => boolean,
+ options: WaitForOptions
+ ): Effect.Effect<
+ SnapshotFrom,
+ ActorStoppedError | Cause.TimeoutError
+ >;
+} = dual(
+ (args) => isActorRef(args[0]),
+ (
+ actor: TActor,
+ predicate: (snapshot: SnapshotFrom) => boolean,
+ options?: WaitForOptions
+ ): Effect.Effect<
+ SnapshotFrom,
+ ActorStoppedError | Cause.TimeoutError
+ > => {
+ const waiting = Effect.callback, ActorStoppedError>(
+ (resume) => {
+ const current: Snapshot = actor.getSnapshot();
+
+ if (predicate(current as SnapshotFrom)) {
+ resume(Effect.succeed(current as SnapshotFrom));
+ return;
+ }
+
+ if (current.status !== 'active') {
+ observeError(actor);
+ resume(Effect.fail(stoppedError(actor)));
+ return;
+ }
+
+ let settled = false;
+ // oxlint-disable-next-line prefer-const
+ let subscription: Subscription | undefined; // avoid TDZ when settling synchronously
+ const dispose = () => {
+ settled = true;
+ subscription?.unsubscribe();
+ };
+
+ subscription = actor.subscribe({
+ next: (snapshot: SnapshotFrom) => {
+ if (settled || !predicate(snapshot)) {
+ return;
+ }
+ dispose();
+ resume(Effect.succeed(snapshot));
+ },
+ error: () => {
+ if (settled) {
+ return;
+ }
+ dispose();
+ resume(Effect.fail(stoppedError(actor)));
+ },
+ complete: () => {
+ if (settled) {
+ return;
+ }
+ dispose();
+ resume(Effect.fail(stoppedError(actor)));
+ }
+ }) as Subscription;
+
+ if (settled) {
+ subscription.unsubscribe();
+ }
+
+ return Effect.sync(dispose);
+ }
+ );
+
+ return options === undefined
+ ? waiting
+ : Effect.timeout(waiting, options.timeout);
+ }
+);
+
+/**
+ * Joins an actor's final result, like `Fiber.join`: succeeds with its `output`
+ * when it is done, fails with `snapshot.error` when it errors, and fails with
+ * `ActorStoppedError` when it stops without output. Waits for a still-active
+ * actor to settle.
+ */
+export function join(
+ actor: TActor
+): Effect.Effect, ErrorFrom | ActorStoppedError> {
+ return Effect.callback<
+ OutputFrom,
+ ErrorFrom | ActorStoppedError
+ >((resume) => {
+ const settle = () => {
+ const snapshot = actor.getSnapshot();
+ if (snapshot.status === 'done') {
+ resume(Effect.succeed(snapshot.output as OutputFrom));
+ } else if (snapshot.status === 'error') {
+ resume(Effect.fail(snapshot.error as ErrorFrom));
+ } else {
+ resume(Effect.fail(stoppedError(actor)));
+ }
+ };
+
+ if (actor.getSnapshot().status !== 'active') {
+ observeError(actor);
+ settle();
+ return;
+ }
+
+ let settled = false;
+ // oxlint-disable-next-line prefer-const
+ let subscription: Subscription | undefined; // avoid TDZ when settling synchronously
+ const dispose = () => {
+ settled = true;
+ subscription?.unsubscribe();
+ };
+ const onSettled = () => {
+ if (settled) {
+ return;
+ }
+ dispose();
+ settle();
+ };
+
+ subscription = actor.subscribe({
+ error: onSettled,
+ complete: onSettled
+ }) as Subscription;
+
+ if (settled) {
+ subscription.unsubscribe();
+ }
+
+ return Effect.sync(dispose);
+ });
+}
+
+/**
+ * Streams the inspection events of the actor's system, as delivered to
+ * `system.inspect(…)`. The stream runs until it is interrupted or its scope
+ * closes.
+ */
+export function inspect(actor: AnyActorRef): Stream.Stream {
+ return Stream.callback((queue) =>
+ Effect.acquireRelease(
+ Effect.sync(() => {
+ const observer: (inspectionEvent: InspectionEvent) => void = (
+ inspectionEvent
+ ) => {
+ Queue.offerUnsafe(queue, inspectionEvent);
+ };
+ const inspectable = actor as {
+ inspect?: (
+ observer: (inspectionEvent: InspectionEvent) => void
+ ) => Subscription;
+ };
+ return inspectable.inspect
+ ? inspectable.inspect(observer)
+ : (actor as unknown as AnyActor).system.inspect(observer);
+ }),
+ (subscription) =>
+ Effect.sync(() => {
+ subscription.unsubscribe();
+ })
+ )
+ );
+}
+
+/**
+ * Streams the events the actor's system could not deliver, as reported by
+ * `system.onRejectedEvent`: sends to a stopped actor, invalid external
+ * events and internal events sent from outside their owner. A dead letter is
+ * not an actor error. The stream runs until it is interrupted or its scope
+ * closes.
+ */
+export function deadLetters(actor: AnyActorRef): Stream.Stream {
+ return Stream.callback((queue) =>
+ Effect.acquireRelease(
+ Effect.sync(() =>
+ (actor as unknown as AnyActor).system.onRejectedEvent(
+ (rejection: EventRejection) => {
+ Queue.offerUnsafe(queue, rejection);
+ }
+ )
+ ),
+ (subscription) =>
+ Effect.sync(() => {
+ subscription.unsubscribe();
+ })
+ )
+ );
+}
diff --git a/xstate-effect/src/actorScope.ts b/xstate-effect/src/actorScope.ts
new file mode 100644
index 00000000..6892125f
--- /dev/null
+++ b/xstate-effect/src/actorScope.ts
@@ -0,0 +1,16 @@
+import { Context, Effect, Scope } from 'effect';
+
+/** The owning Effect actor's scope, supplied by `createEffectActor`. */
+export class ActorScope extends Context.Service()(
+ '@xstate/effect/ActorScope'
+) {}
+
+/**
+ * Acquires resources in the owning actor's scope. Their finalizers run when
+ * that actor stops, even if the invoking task finishes or is cancelled first.
+ */
+export function withActorScope(
+ effect: Effect.Effect
+): Effect.Effect | ActorScope> {
+ return ActorScope.use((scope) => Scope.provide(effect, scope));
+}
diff --git a/xstate-effect/src/atom.test.ts b/xstate-effect/src/atom.test.ts
new file mode 100644
index 00000000..35d5b3b9
--- /dev/null
+++ b/xstate-effect/src/atom.test.ts
@@ -0,0 +1,264 @@
+import { Cause, Context, Effect, Layer, Schema } from 'effect';
+import { AsyncResult, Atom, AtomRegistry } from 'effect/reactivity';
+import { createMachine, setup } from 'xstate';
+import { createActorAtoms } from './atom.ts';
+import { fromEffect, setupEffect, withActorScope } from './index.ts';
+import { NotReadyError } from './atom.ts';
+
+const until = async (predicate: () => boolean, timeoutMs = 1000) => {
+ const deadline = Date.now() + timeoutMs;
+ while (!predicate()) {
+ if (Date.now() > deadline) {
+ throw new Error('Timed out waiting for condition');
+ }
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ }
+};
+
+const counterMachine = createMachine({
+ context: { count: 0 },
+ on: {
+ INC: ({ context }) => ({ context: { count: context.count + 1 } })
+ }
+});
+
+describe('createActorAtoms', () => {
+ it.each(['invocation', 'actor'] as const)(
+ 'provides the %s resource scope',
+ async (lifetime) => {
+ let released = false;
+ const acquire = Effect.acquireRelease(Effect.succeed('resource'), () =>
+ Effect.sync(() => {
+ released = true;
+ })
+ );
+ const logic =
+ lifetime === 'actor'
+ ? fromEffect(acquire.pipe(withActorScope))
+ : fromEffect(acquire);
+ const registry = AtomRegistry.make();
+ const atoms = createActorAtoms(Atom.runtime(Layer.empty), logic);
+ const unmount = registry.mount(atoms.snapshot);
+ try {
+ await until(() => {
+ const snapshot = registry.get(atoms.snapshot);
+ return (
+ released &&
+ AsyncResult.isSuccess(snapshot) &&
+ snapshot.value.status === 'done'
+ );
+ });
+ const snapshot = registry.get(atoms.snapshot);
+ expect(AsyncResult.isSuccess(snapshot) && snapshot.value.output).toBe(
+ 'resource'
+ );
+ } finally {
+ unmount();
+ registry.dispose();
+ }
+ }
+ );
+
+ it('requires and passes the input declared by the logic', async () => {
+ const logic = fromEffect({
+ schemas: { input: Schema.Struct({ id: Schema.String }) },
+ effect: ({ input }) => Effect.succeed(input.id)
+ });
+ const runtime = Atom.runtime(Layer.empty);
+ const invalid = () => {
+ // @ts-expect-error -- required input cannot be omitted
+ createActorAtoms(runtime, logic);
+ // @ts-expect-error -- the options must contain input
+ createActorAtoms(runtime, logic, {});
+ // @ts-expect-error -- input must match the schema
+ createActorAtoms(runtime, logic, { input: { id: 1 } });
+ };
+ void invalid;
+ const registry = AtomRegistry.make();
+ const atoms = createActorAtoms(runtime, logic, {
+ input: { id: 'release' }
+ });
+ const unmount = registry.mount(atoms.snapshot);
+ try {
+ await until(() => {
+ const result = registry.get(atoms.snapshot);
+ return AsyncResult.isSuccess(result) && result.value.status === 'done';
+ });
+ const result = registry.get(atoms.snapshot);
+ expect(AsyncResult.isSuccess(result) && result.value.output).toBe(
+ 'release'
+ );
+ } finally {
+ unmount();
+ }
+ });
+
+ it('starts the actor on first read and exposes its snapshot', async () => {
+ const registry = AtomRegistry.make();
+ const runtime = Atom.runtime(Layer.empty);
+ const atoms = createActorAtoms(runtime, counterMachine);
+
+ const unmount = registry.mount(atoms.snapshot);
+ await until(() => AsyncResult.isSuccess(registry.get(atoms.snapshot)));
+
+ const snapshot = registry.get(atoms.snapshot);
+ expect(AsyncResult.isSuccess(snapshot) && snapshot.value.context).toEqual({
+ count: 0
+ });
+ unmount();
+ });
+
+ it('sends events through the send atom and updates the snapshot', async () => {
+ const registry = AtomRegistry.make();
+ const runtime = Atom.runtime(Layer.empty);
+ const atoms = createActorAtoms(runtime, counterMachine);
+ const counts: number[] = [];
+
+ const unsubscribe = registry.subscribe(
+ atoms.select((snapshot) => snapshot.context.count),
+ (result) => {
+ if (AsyncResult.isSuccess(result)) {
+ counts.push(result.value);
+ }
+ },
+ { immediate: true }
+ );
+ await until(() => counts.length > 0);
+
+ registry.set(atoms.send, { type: 'INC' });
+ registry.set(atoms.send, { type: 'INC' });
+ await until(() => counts.at(-1) === 2);
+
+ expect(counts).toEqual([0, 1, 2]);
+ unsubscribe();
+ });
+
+ it('runs Effect logic with services from the runtime layer', async () => {
+ class Greeting extends Context.Service()(
+ 'Greeting'
+ ) {}
+ const greet = fromEffect(
+ Greeting.use((greeting) => Effect.succeed(greeting.value))
+ );
+ const machine = setup({ actors: { greet } }).createMachine({
+ context: { greeting: '' },
+ initial: 'loading',
+ states: {
+ loading: {
+ invoke: {
+ src: 'greet',
+ onDone: {
+ target: 'done',
+ context: ({ event }) => ({ greeting: event.output })
+ }
+ }
+ },
+ done: {}
+ }
+ });
+ const registry = AtomRegistry.make();
+ const runtime = Atom.runtime(Layer.succeed(Greeting, { value: 'hello' }));
+ const atoms = createActorAtoms(runtime, machine);
+
+ const unmount = registry.mount(atoms.snapshot);
+ await until(() => {
+ const result = registry.get(atoms.snapshot);
+ return AsyncResult.isSuccess(result) && result.value.value === 'done';
+ });
+
+ const result = registry.get(atoms.snapshot);
+ expect(AsyncResult.isSuccess(result) && result.value.context).toEqual({
+ greeting: 'hello'
+ });
+ unmount();
+ });
+
+ it('rejects a runtime that does not provide a required service', () => {
+ class Greeting extends Context.Service()(
+ 'Greeting'
+ ) {}
+ const machine = setupEffect({
+ actions: {
+ greet: (_args) => Greeting.use(() => Effect.void)
+ }
+ }).createMachine({
+ on: { GREET: (args, enq) => enq(args.actions.greet, args) }
+ });
+ const runtime = Atom.runtime(Layer.empty);
+
+ const create = () => {
+ // @ts-expect-error -- the runtime layer does not provide Greeting
+ createActorAtoms(runtime, machine);
+ };
+ void create;
+ });
+
+ it('stops the actor when its atoms are released', async () => {
+ const registry = AtomRegistry.make();
+ const runtime = Atom.runtime(Layer.empty);
+ const atoms = createActorAtoms(runtime, counterMachine);
+
+ const unmount = registry.mount(atoms.snapshot);
+ await until(() => AsyncResult.isSuccess(registry.get(atoms.actor)));
+ const result = registry.get(atoms.actor);
+ const actor = AsyncResult.isSuccess(result) ? result.value : undefined;
+ expect(actor?.getSnapshot().status).toBe('active');
+
+ unmount();
+ await until(() => actor?.getSnapshot().status === 'stopped');
+
+ expect(actor?.getSnapshot().status).toBe('stopped');
+ });
+
+ it('reports NotReadyError when an event is sent before the runtime is ready', async () => {
+ class Slow extends Context.Service()('Slow') {}
+ const registry = AtomRegistry.make();
+ const runtime = Atom.runtime(
+ Layer.effect(
+ Slow,
+ Effect.delay(Effect.succeed({ ready: true as const }), '5 millis')
+ )
+ );
+ const atoms = createActorAtoms(runtime, counterMachine);
+
+ const unmount = registry.mount(atoms.send);
+ registry.set(atoms.send, { type: 'INC' });
+ const early = registry.get(atoms.send);
+ expect(AsyncResult.isFailure(early)).toBe(true);
+ expect(
+ AsyncResult.isFailure(early) && Cause.squash(early.cause)
+ ).toBeInstanceOf(NotReadyError);
+
+ await until(() => AsyncResult.isSuccess(registry.get(atoms.actor)));
+ registry.set(atoms.send, { type: 'INC' });
+ const late = registry.get(atoms.actor);
+ await until(
+ () =>
+ AsyncResult.isSuccess(late) &&
+ late.value.getSnapshot().context.count === 1
+ );
+ expect(
+ AsyncResult.isSuccess(late) && late.value.getSnapshot().context
+ ).toEqual({
+ count: 1
+ });
+ expect(AsyncResult.isSuccess(registry.get(atoms.send))).toBe(true);
+ unmount();
+ });
+
+ it('exposes an errored actor as a failed result', async () => {
+ const failure = { code: 'BOOM' as const };
+ const registry = AtomRegistry.make();
+ const runtime = Atom.runtime(Layer.empty);
+ const atoms = createActorAtoms(runtime, fromEffect(Effect.fail(failure)));
+
+ const unmount = registry.mount(atoms.result);
+ await until(() => AsyncResult.isFailure(registry.get(atoms.result)));
+
+ const result = registry.get(atoms.result);
+ expect(AsyncResult.isFailure(result) && Cause.squash(result.cause)).toEqual(
+ failure
+ );
+ unmount();
+ });
+});
diff --git a/xstate-effect/src/atom.ts b/xstate-effect/src/atom.ts
new file mode 100644
index 00000000..81acc61b
--- /dev/null
+++ b/xstate-effect/src/atom.ts
@@ -0,0 +1,176 @@
+import { Cause, type Effect } from 'effect';
+import { AsyncResult, Atom } from 'effect/reactivity';
+import type {
+ AnyActorLogic,
+ ErrorFrom,
+ EventFromLogic,
+ Snapshot,
+ SnapshotFrom
+} from 'xstate';
+import {
+ createEffectActor,
+ type EffectActorOptionsArgs
+} from './createEffectActor.ts';
+import type { EffectActor } from './effectActor.ts';
+import { NotReadyError } from './errors.ts';
+import { taggedState, type TaggedStateFrom } from './state.ts';
+import type { RequirementsFrom } from './types.ts';
+
+export { NotReadyError } from './errors.ts';
+
+/**
+ * Atoms that expose one actor to a reactive UI through
+ * `effect/reactivity`. Read them with the atom bindings for your
+ * framework, such as `@effect/atom-react`.
+ */
+export interface ActorAtoms {
+ /**
+ * The running actor. It starts when the atom is first read and stops when
+ * the atom is released, that is, when nothing reads or mounts it anymore.
+ */
+ readonly actor: Atom.Atom, ER>>;
+ /** The actor's current snapshot, updated on every transition. */
+ readonly snapshot: Atom.Atom<
+ AsyncResult.AsyncResult, ER>
+ >;
+ /**
+ * The snapshot as a result: a `Failure` carrying the actor's error once
+ * the actor's status is `error`, so an error boundary can handle it.
+ */
+ readonly result: Atom.Atom<
+ AsyncResult.AsyncResult, ER | ErrorFrom>
+ >;
+ /**
+ * Sends an event to the actor synchronously. Set it with the event, for
+ * example through `useAtomSet` in React. Its value reports the last send:
+ * a `NotReadyError` failure when the runtime is still building, otherwise
+ * success.
+ */
+ readonly send: Atom.Writable<
+ AsyncResult.AsyncResult,
+ EventFromLogic
+ >;
+ /** Derives an atom of a value selected from the snapshot. */
+ readonly select: (
+ selector: (snapshot: SnapshotFrom) => T
+ ) => Atom.Atom>;
+ /**
+ * The snapshot as a tagged union over the machine's states, for
+ * `Match.tag` or a `switch` on `_tag`. See `taggedState`.
+ */
+ readonly state: Atom.Atom<
+ AsyncResult.AsyncResult>, ER>
+ >;
+}
+
+interface MissingRequirements {
+ readonly 'The runtime does not provide services the logic requires': T;
+}
+
+/**
+ * Creates atoms for an actor that runs in an `Atom.runtime`. The runtime's
+ * Layer must provide every service the logic requires; a missing service is
+ * a type error on the `runtime` argument. Logic with required input also
+ * requires an options object containing that input.
+ *
+ * The actor is created with `createEffectActor` inside the `actor` atom's
+ * scope, so its lifetime follows the atom: it starts on first read and stops
+ * when the atom is released. Wrap the atoms with `Atom.keepAlive` to pin the
+ * actor for the registry's lifetime, or with `Atom.family` to create one
+ * actor per input.
+ */
+export function createActorAtoms(
+ runtime: Atom.AtomRuntime &
+ ([RequirementsFrom] extends [R]
+ ? unknown
+ : MissingRequirements, R>>),
+ logic: TLogic,
+ ...[options]: EffectActorOptionsArgs
+): ActorAtoms {
+ const host = runtime as Atom.AtomRuntime;
+
+ const actor = host.atom(
+ createEffectActor(logic, options as never) as unknown as Effect.Effect<
+ EffectActor,
+ never
+ >
+ );
+
+ const snapshot = Atom.make(
+ (get): AsyncResult.AsyncResult, ER> => {
+ const result = get(actor);
+ if (!AsyncResult.isSuccess(result)) {
+ return AsyncResult.map(result, (running) => running.getSnapshot());
+ }
+ const running = result.value;
+ const publish = () => {
+ get.setSelf(AsyncResult.success(running.getSnapshot()));
+ };
+ // The atom is the consumer of the actor's error: `result` reports it,
+ // so the observer handles `error` and XState does not report it as
+ // unhandled.
+ const subscription = running.subscribe({
+ next: publish,
+ error: publish,
+ complete: publish
+ });
+ get.addFinalizer(() => {
+ subscription.unsubscribe();
+ });
+ return AsyncResult.success(running.getSnapshot());
+ }
+ );
+
+ const result = Atom.make(
+ (
+ get
+ ): AsyncResult.AsyncResult<
+ SnapshotFrom,
+ ER | ErrorFrom
+ > => {
+ const current = get(snapshot);
+ if (!AsyncResult.isSuccess(current)) {
+ return current;
+ }
+ const value = current.value as Snapshot;
+ if (value.status === 'error') {
+ return AsyncResult.failureWithPrevious(
+ Cause.fail(value.error as ErrorFrom),
+ { previous: get.self() }
+ );
+ }
+ return current;
+ }
+ );
+
+ const sendAtom = Atom.writable<
+ AsyncResult.AsyncResult,
+ EventFromLogic
+ >(
+ (get) => AsyncResult.map(get(actor), () => undefined),
+ (ctx, event) => {
+ const current = ctx.get(actor);
+ if (AsyncResult.isInitial(current)) {
+ ctx.setSelf(AsyncResult.failure(Cause.fail(new NotReadyError())));
+ } else if (AsyncResult.isFailure(current)) {
+ ctx.setSelf(AsyncResult.map(current, () => undefined));
+ } else {
+ current.value.send(event);
+ ctx.setSelf(AsyncResult.success(undefined));
+ }
+ }
+ );
+
+ function select(
+ selector: (snapshot: SnapshotFrom) => T
+ ): Atom.Atom> {
+ return Atom.map(snapshot, (result) => AsyncResult.map(result, selector));
+ }
+
+ const state = select(
+ (current) =>
+ taggedState(current as never) as TaggedStateFrom>
+ );
+
+ return { actor, snapshot, result, send: sendAtom, select, state };
+}
diff --git a/xstate-effect/src/brands.ts b/xstate-effect/src/brands.ts
new file mode 100644
index 00000000..78ffb978
--- /dev/null
+++ b/xstate-effect/src/brands.ts
@@ -0,0 +1,3 @@
+export const effectActionBrand: unique symbol = Symbol.for(
+ '@xstate/effect/action'
+) as any;
diff --git a/xstate-effect/src/createEffectActor.ts b/xstate-effect/src/createEffectActor.ts
new file mode 100644
index 00000000..5c70e289
--- /dev/null
+++ b/xstate-effect/src/createEffectActor.ts
@@ -0,0 +1,407 @@
+import {
+ Clock,
+ Context,
+ Duration,
+ Effect,
+ Exit,
+ Fiber,
+ Queue,
+ Scope
+} from 'effect';
+import {
+ deliverEvent,
+ isMachineSnapshot,
+ stopActor,
+ terminateActor,
+ type ActorOptions,
+ type AnyActor,
+ type AnyActorLogic,
+ type AnyEventObject,
+ type EventFromLogic,
+ type InspectionEvent,
+ type InputFrom,
+ type RequiredActorOptionsFor,
+ type RequiredActorOptionsKeys,
+ type Snapshot,
+ type SnapshotFrom
+} from 'xstate';
+import { createDurable, type DurableEffect } from 'xstate/durable';
+import {
+ EffectActor,
+ actionFailure,
+ isActionFailure,
+ safeCall,
+ type MailboxItem
+} from './effectActor.ts';
+import {
+ bindEffectHost,
+ closeEffectHost,
+ createEffectHost,
+ withEffectHost,
+ type EffectHost
+} from './internal.ts';
+import type { RequirementsFrom } from './types.ts';
+import { ActorScope } from './actorScope.ts';
+
+const XSTATE_TIMER = 'xstate.timer';
+const XSTATE_INIT = '@xstate.init';
+
+/** Options for {@link createEffectActor}. */
+export type EffectActorOptions = {
+ readonly input?: InputFrom;
+ /**
+ * A snapshot from `actor.getPersistedSnapshot()`. The actor resumes in that
+ * state without re-running entry actions, and pending timers keep their
+ * original deadlines, as with XState's `createActor(logic, { snapshot })`.
+ * State-machine children resume their persisted state and completed
+ * children stay done. Effect tasks and streams that were running, at the
+ * root or as children, start again from the beginning. A restored actor
+ * does not need `input`.
+ */
+ readonly snapshot?: ActorOptions['snapshot'];
+} & RequiredActorOptionsFor;
+
+export type EffectActorOptionsArgs = [
+ RequiredActorOptionsKeys
+] extends [never]
+ ? [options?: EffectActorOptions]
+ : [options: EffectActorOptions];
+
+/**
+ * Creates and starts an actor as an Effect interpreter over pure transitions.
+ *
+ * Each step is `transition(snapshot, event)`, a pure function that returns
+ * the next snapshot and the actions to run. An Effect fiber owns the loop:
+ * the mailbox is a `Queue`, timers are `Effect.sleep` fibers on the Effect
+ * `Clock`, and declared Effect actions run as forked Effects in the actor's
+ * `Scope` with the services captured here. Child actors are started as live
+ * XState actors whose Effects run in the same host.
+ *
+ * The actor is a scoped resource: it stops, and every Effect it hosts is
+ * interrupted, when the enclosing `Scope` closes. The returned Effect never
+ * fails; the actor's own outcome is its snapshot status, read with `join`.
+ */
+export function createEffectActor(
+ logic: TLogic,
+ ...[options]: EffectActorOptionsArgs
+): Effect.Effect<
+ EffectActor,
+ never,
+ RequirementsFrom | Scope.Scope
+> {
+ return Effect.acquireRelease(
+ Effect.gen(function* () {
+ const parentScope = yield* Effect.scope;
+ const actorScope = yield* Scope.fork(parentScope);
+ const baseContext = yield* Effect.context();
+ const context = Context.add(
+ Context.add(baseContext, Scope.Scope, actorScope),
+ ActorScope,
+ actorScope
+ );
+ const host = createEffectHost(context, actorScope);
+ const runFork = Effect.runForkWith(context);
+ const runPromise = Effect.runPromiseWith(context);
+
+ const mailbox =
+ yield* Queue.unbounded>>();
+ const timers = new Map>();
+ // `root` and `actor` are declared after the adapter below; its
+ // callbacks only run once they are initialized.
+ let stopped = false;
+ const isRoot = (candidate: AnyActor) =>
+ candidate.address === durable.rootAddress;
+
+ const offer = (item: MailboxItem>) => {
+ if (!stopped) {
+ Queue.offerUnsafe(mailbox, item);
+ }
+ };
+ const timerKey = (source: AnyActor, id: string) =>
+ `${source.sessionId}:${id}`;
+
+ const inspectors = new Set<(event: InspectionEvent) => void>();
+ let rootAnnounced = false;
+ const clock = Context.get(context, Clock.Clock);
+ const durable = createDurable(
+ logic,
+ {
+ // Timer deadlines are measured on the same clock the timers sleep
+ // on, so a restored timer resumes with its remaining delay.
+ now: () => clock.currentTimeMillisUnsafe(),
+ executeAction: (action, _metadata, runtime) => {
+ // Fire-and-forget: the action starts now and the loop continues.
+ // A rejection reaches the machine as an execution error.
+ try {
+ const result = withEffectHost(host, () => action.exec(runtime));
+ if (
+ result &&
+ typeof (result as PromiseLike).then === 'function'
+ ) {
+ void Promise.resolve(result).catch((error: unknown) => {
+ offer({ [actionFailure]: true, error });
+ });
+ }
+ } catch (error) {
+ offer({ [actionFailure]: true, error });
+ }
+ },
+ spawnActor: (_source, child) => {
+ // Every actor of this execution hosts its Effects here.
+ bindEffectHost(child, host);
+ },
+ startActor: (child) => {
+ child.start();
+ },
+ stopActor: (child) => {
+ if (!isRoot(child)) {
+ stopActor(child);
+ }
+ },
+ terminateActor: (child, termination) => {
+ if (!isRoot(child)) {
+ terminateActor(child, termination);
+ }
+ },
+ sendEvent: (source, target, event) => {
+ if (isRoot(target)) {
+ offer(event as EventFromLogic);
+ return;
+ }
+ deliverEvent(source, target, event);
+ },
+ emitEvent: (source, event) => {
+ if (isRoot(source)) {
+ actor._emit(event as never);
+ return;
+ }
+ (source as AnyActor & { _emit(value: unknown): void })._emit(event);
+ },
+ scheduleTimer: (source, id, delay) => {
+ const key = timerKey(source, id);
+ timers.get(key)?.interruptUnsafe();
+ const fiber = Fiber.runIn(
+ runFork(
+ Effect.andThen(
+ Effect.sleep(Duration.millis(delay)),
+ Effect.sync(() => {
+ timers.delete(key);
+ const timerEvent: AnyEventObject = {
+ type: XSTATE_TIMER,
+ id
+ };
+ if (isRoot(source)) {
+ offer(timerEvent as EventFromLogic);
+ } else {
+ deliverEvent(source, source, timerEvent);
+ }
+ })
+ )
+ ),
+ actorScope
+ );
+ timers.set(key, fiber);
+ },
+ cancelTimer: (source, id) => {
+ const key = timerKey(source, id);
+ timers.get(key)?.interruptUnsafe();
+ timers.delete(key);
+ },
+ cancelAllTimers: (source) => {
+ for (const [key, fiber] of timers) {
+ if (key.startsWith(`${source.sessionId}:`)) {
+ fiber.interruptUnsafe();
+ timers.delete(key);
+ }
+ }
+ },
+ waitForEvent: () =>
+ runPromise(Queue.take(mailbox)) as Promise>
+ },
+ {
+ inspect: (event) => {
+ // The pure step scope re-materializes the root ref per step and
+ // announces it again; observers should see the root once.
+ if (
+ event.type === '@xstate.actor' &&
+ (event.actorRef as AnyActor).address === durable.rootAddress
+ ) {
+ if (rootAnnounced) {
+ return;
+ }
+ rootAnnounced = true;
+ }
+ for (const inspector of inspectors) {
+ safeCall(inspector, event);
+ }
+ }
+ }
+ );
+
+ const errorSnapshot = (
+ snapshot: SnapshotFrom,
+ error: unknown
+ ): SnapshotFrom =>
+ ({
+ ...(snapshot as Snapshot),
+ status: 'error',
+ error
+ }) as SnapshotFrom;
+
+ const stopChildren = (snapshot: SnapshotFrom) => {
+ const children = (
+ snapshot as { children?: Record }
+ ).children;
+ for (const child of Object.values(children ?? {})) {
+ if (child && !isRoot(child)) {
+ stopActor(child);
+ }
+ }
+ };
+
+ const stop = () => {
+ if (stopped) {
+ return;
+ }
+ stopped = true;
+ for (const fiber of timers.values()) {
+ fiber.interruptUnsafe();
+ }
+ timers.clear();
+ const current = actor.getSnapshot();
+ if (current) {
+ stopChildren(current);
+ }
+ runFork(Queue.shutdown(mailbox));
+ if (!actor._isSettled) {
+ actor._settle({
+ ...(actor.getSnapshot() as Snapshot),
+ status: 'stopped'
+ } as SnapshotFrom);
+ }
+ closeEffectHost(host);
+ };
+
+ // The first transition (or the restore) runs here so the handle is
+ // ready when this Effect succeeds, and the initial actions start before
+ // any send. Restoring runs no entry actions; its effects resume
+ // machine children, restart running Effect children and re-arm pending
+ // timers.
+ let [snapshot, effects] = options?.snapshot
+ ? durable.restore(options.snapshot)
+ : durable.initialTransition(options?.input as never);
+ const initial: Snapshot = snapshot;
+ if (
+ options?.snapshot &&
+ !isMachineSnapshot(initial) &&
+ initial.status === 'active'
+ ) {
+ // A restored machine resumes through the effects above. Other logic
+ // (an Effect task or stream at the root) reattaches its active work by
+ // replaying its init event, as its restored `start` does under
+ // `createActor`.
+ const [started, startEffects] = durable.transition(snapshot, {
+ type: XSTATE_INIT,
+ input: 'input' in initial ? initial.input : undefined
+ } as EventFromLogic);
+ snapshot = started;
+ effects = [...effects, ...startEffects];
+ }
+ const root = durable.getActorRef(snapshot)!;
+ // Restored children are created by the snapshot, not spawned through
+ // the adapter; they find this host through their parent chain.
+ bindEffectHost(root, host);
+ // The root exists from here on; later announcements are step
+ // re-materializations, not new actors.
+ rootAnnounced = true;
+ const actor = new EffectActor(
+ logic,
+ root!,
+ snapshot,
+ mailbox,
+ stop,
+ inspectors
+ );
+ bindEffectHost(actor, host);
+
+ const executeEffects = (
+ batch: DurableEffect[]
+ ): Effect.Effect =>
+ Effect.promise(() =>
+ durable.executeEffects(batch).then(
+ () => undefined,
+ (error: unknown) => {
+ offer({ [actionFailure]: true, error });
+ }
+ )
+ );
+
+ const loop = Effect.gen(function* () {
+ yield* executeEffects(effects);
+ while (
+ (snapshot as Snapshot).status === 'active' &&
+ !stopped
+ ) {
+ const item = yield* Effect.promise(() =>
+ durable.waitForEvent().then(
+ (event) => event as MailboxItem>,
+ () => undefined
+ )
+ );
+ if (item === undefined || stopped) {
+ break;
+ }
+ let event: EventFromLogic;
+ if (isActionFailure(item)) {
+ const errorEvent = (
+ logic as {
+ getExecutionErrorEvent?: (
+ snapshot: SnapshotFrom,
+ error: unknown
+ ) => EventFromLogic | undefined;
+ }
+ ).getExecutionErrorEvent?.(snapshot, item.error);
+ if (!errorEvent) {
+ snapshot = errorSnapshot(snapshot, item.error);
+ break;
+ }
+ event = errorEvent;
+ } else {
+ event = item;
+ }
+ try {
+ [snapshot, effects] = durable.transition(snapshot, event);
+ } catch (error) {
+ snapshot = errorSnapshot(snapshot, error);
+ break;
+ }
+ actor._publish(snapshot);
+ yield* executeEffects(effects);
+ }
+ if (!stopped) {
+ actor._publish(snapshot);
+ if ((snapshot as Snapshot).status !== 'active') {
+ stopChildren(snapshot);
+ closeEffectHost(host);
+ }
+ }
+ });
+
+ yield* Effect.forkIn(loop, actorScope);
+ return { actor, host };
+ }),
+ ({ actor, host }: { actor: EffectActor; host: EffectHost }) =>
+ Effect.gen(function* () {
+ actor.stop();
+ if (host.closing) {
+ yield* Fiber.join(host.closing);
+ } else {
+ yield* Scope.close(host.scope, Exit.void);
+ }
+ })
+ ).pipe(Effect.map(({ actor }) => actor)) as unknown as Effect.Effect<
+ EffectActor,
+ never,
+ RequirementsFrom | Scope.Scope
+ >;
+}
diff --git a/xstate-effect/src/effectActor.ts b/xstate-effect/src/effectActor.ts
new file mode 100644
index 00000000..2c1f365a
--- /dev/null
+++ b/xstate-effect/src/effectActor.ts
@@ -0,0 +1,265 @@
+import { Queue } from 'effect';
+import type {
+ ActorRef,
+ AnyActor,
+ AnyActorLogic,
+ EmittedFrom,
+ EventFromLogic,
+ InspectionEvent,
+ Observer,
+ Snapshot,
+ SnapshotFrom,
+ Subscription
+} from 'xstate';
+
+/** A mailbox item that reports a failed fire-and-forget action. */
+export interface ActionFailure {
+ readonly [actionFailure]: true;
+ readonly error: unknown;
+}
+
+export const actionFailure: unique symbol = Symbol.for(
+ '@xstate/effect/actionFailure'
+) as any;
+
+export function isActionFailure(value: unknown): value is ActionFailure {
+ return typeof value === 'object' && value !== null && actionFailure in value;
+}
+
+export type MailboxItem = TEvent | ActionFailure;
+
+const symbolObservable: typeof Symbol.observable = (() =>
+ (typeof Symbol === 'function' && Symbol.observable) ||
+ '@@observable')() as any;
+
+/**
+ * Calls a listener and reports an exception it throws without letting it
+ * escape into the interpreter, matching core's `safeCall`.
+ */
+export function safeCall(fn: ((arg: T) => void) | undefined, arg?: T) {
+ try {
+ fn?.(arg as T);
+ } catch (err) {
+ setTimeout(() => {
+ throw err;
+ });
+ }
+}
+
+function toObserver(
+ nextHandler?: Observer | ((value: T) => void),
+ errorHandler?: (error: any) => void,
+ completionHandler?: () => void
+): Observer {
+ if (typeof nextHandler === 'object') {
+ return nextHandler;
+ }
+ return {
+ next: nextHandler,
+ error: errorHandler,
+ complete: completionHandler
+ };
+}
+
+/**
+ * The handle `createEffectActor` returns. It implements XState's `ActorRef`
+ * contract (`send`, `getSnapshot`, `subscribe`, `on`), so it works with
+ * `useSelector`, this package's actor functions and the inspection APIs, while
+ * the actor itself is driven by an Effect fiber over pure transitions.
+ */
+export class EffectActor implements ActorRef<
+ SnapshotFrom,
+ EventFromLogic,
+ EmittedFrom
+> {
+ readonly id: string;
+ readonly address: string;
+ readonly sessionId: string | undefined;
+ /** The actor system that hosts this actor and its children. */
+ readonly system: AnyActor['system'];
+ /** @internal */
+ readonly _root: AnyActor;
+
+ private _snapshot: SnapshotFrom;
+ private readonly _observers = new Set>>();
+ private readonly _listeners = new Map<
+ string,
+ Set<(emitted: EmittedFrom) => void>
+ >();
+ private _settled = false;
+
+ constructor(
+ readonly logic: TLogic,
+ root: AnyActor,
+ snapshot: SnapshotFrom,
+ private readonly _mailbox: Queue.Queue>>,
+ private readonly _stopExecution: () => void,
+ private readonly _inspectors: Set<(event: InspectionEvent) => void>
+ ) {
+ this._root = root;
+ this.id = root.id;
+ this.address = root.address;
+ this.sessionId = root.sessionId;
+ this.system = root.system;
+ this._snapshot = snapshot;
+ }
+
+ getSnapshot(): SnapshotFrom {
+ return this._snapshot;
+ }
+
+ getPersistedSnapshot(): Snapshot {
+ return this.logic.getPersistedSnapshot(this._snapshot as never);
+ }
+
+ /** Sends an event; the actor processes it on its own fiber. */
+ send(event: EventFromLogic): void {
+ if (this._settled) {
+ this.system.deadLetter(undefined, this._root, event, 'stopped');
+ return;
+ }
+ Queue.offerUnsafe(this._mailbox, event);
+ }
+
+ /** Stops the actor, its children and every Effect it hosts. */
+ stop(): this {
+ this._stopExecution();
+ return this;
+ }
+
+ subscribe(observer: Observer>): Subscription;
+ subscribe(
+ nextListener?: (snapshot: SnapshotFrom) => void,
+ errorListener?: (error: any) => void,
+ completeListener?: () => void
+ ): Subscription;
+ subscribe(
+ nextListenerOrObserver?:
+ | ((snapshot: SnapshotFrom) => void)
+ | Observer>,
+ errorListener?: (error: any) => void,
+ completeListener?: () => void
+ ): Subscription {
+ const observer = toObserver(
+ nextListenerOrObserver,
+ errorListener,
+ completeListener
+ );
+ if (this._settled) {
+ const snapshot = this._snapshot as Snapshot;
+ if (snapshot.status === 'error') {
+ safeCall(observer.error, snapshot.error);
+ } else {
+ safeCall(observer.complete);
+ }
+ return { unsubscribe: () => {} };
+ }
+ this._observers.add(observer);
+ return {
+ unsubscribe: () => {
+ this._observers.delete(observer);
+ }
+ };
+ }
+
+ on['type'] | '*'>(
+ type: TType,
+ handler: (
+ emitted: EmittedFrom &
+ (TType extends '*' ? unknown : { type: TType })
+ ) => void
+ ): Subscription {
+ let listeners = this._listeners.get(type);
+ if (!listeners) {
+ listeners = new Set();
+ this._listeners.set(type, listeners);
+ }
+ const listener = handler as (emitted: EmittedFrom) => void;
+ listeners.add(listener);
+ return {
+ unsubscribe: () => {
+ listeners.delete(listener);
+ }
+ };
+ }
+
+ /** @internal Delivers an emitted event to `on` listeners. */
+ _emit(event: EmittedFrom): void {
+ const listeners = [
+ ...(this._listeners.get(event.type) ?? []),
+ ...(this._listeners.get('*') ?? [])
+ ];
+ for (const listener of listeners) {
+ safeCall(listener, event);
+ }
+ }
+
+ /**
+ * Observes the inspection events of this actor and its children: every
+ * actor creation and transition of the execution.
+ */
+ inspect(
+ observer: Observer | ((event: InspectionEvent) => void)
+ ): Subscription {
+ const handler =
+ typeof observer === 'function'
+ ? observer
+ : (event: InspectionEvent) => observer.next?.(event);
+ this._inspectors.add(handler);
+ return {
+ unsubscribe: () => {
+ this._inspectors.delete(handler);
+ }
+ };
+ }
+
+ [symbolObservable]() {
+ return this;
+ }
+
+ toJSON() {
+ return { xstate$$type: 1, id: this.id };
+ }
+
+ /** @internal Publishes a snapshot produced by the execution loop. */
+ _publish(snapshot: SnapshotFrom): void {
+ this._snapshot = snapshot;
+ const status = (snapshot as Snapshot).status;
+ if (status === 'active') {
+ for (const observer of this._observers) {
+ safeCall(observer.next, snapshot);
+ }
+ return;
+ }
+ this._settle(snapshot);
+ }
+
+ /** @internal Marks the actor stopped and notifies observers. */
+ _settle(snapshot: SnapshotFrom): void {
+ if (this._settled) {
+ return;
+ }
+ this._snapshot = snapshot;
+ this._settled = true;
+ const observers = [...this._observers];
+ this._observers.clear();
+ const status = (snapshot as Snapshot).status;
+ if (status === 'done') {
+ for (const observer of observers) {
+ safeCall(observer.next, snapshot);
+ }
+ }
+ for (const observer of observers) {
+ if (status === 'error') {
+ safeCall(observer.error, (snapshot as Snapshot).error);
+ } else {
+ safeCall(observer.complete);
+ }
+ }
+ }
+
+ /** @internal */
+ get _isSettled(): boolean {
+ return this._settled;
+ }
+}
diff --git a/xstate-effect/src/errors.ts b/xstate-effect/src/errors.ts
new file mode 100644
index 00000000..df35b319
--- /dev/null
+++ b/xstate-effect/src/errors.ts
@@ -0,0 +1,43 @@
+import { Cause, Data } from 'effect';
+import type { Snapshot } from 'xstate';
+
+/**
+ * The failure an Effect-backed actor reports when its Effect was interrupted
+ * by something other than the actor being stopped, such as `Effect.interrupt`,
+ * losing an `Effect.race`, or an `Effect.timeout` that interrupts.
+ */
+export class EffectInterruptedError extends Data.TaggedError(
+ 'EffectInterruptedError'
+)<{
+ readonly cause: Cause.Cause;
+}> {
+ override get message(): string {
+ return 'Effect was interrupted before the actor completed';
+ }
+}
+
+/**
+ * Reported by `waitFor` when the actor stops or errors before a snapshot
+ * matches, and by `join` when the actor stops without output. `join` reports
+ * an errored actor's own `snapshot.error` instead.
+ */
+export class ActorStoppedError extends Data.TaggedError('ActorStoppedError')<{
+ readonly actorId: string;
+ readonly snapshot: Snapshot;
+}> {
+ override get message(): string {
+ return `Actor "${this.actorId}" ${
+ this.snapshot.status === 'error' ? 'errored' : 'stopped'
+ } before completing`;
+ }
+}
+
+/**
+ * Reported by the `send` atom of `createActorAtoms` when an event is sent
+ * before the actor's runtime has finished building.
+ */
+export class NotReadyError extends Data.TaggedError('NotReadyError') {
+ override get message(): string {
+ return 'The actor is not ready yet';
+ }
+}
diff --git a/xstate-effect/src/fromEffect.ts b/xstate-effect/src/fromEffect.ts
new file mode 100644
index 00000000..8b19fec7
--- /dev/null
+++ b/xstate-effect/src/fromEffect.ts
@@ -0,0 +1,709 @@
+import { Cause, Effect, Exit, Stream } from 'effect';
+import {
+ createLogic,
+ type ActorLogicValidator,
+ type ActorLogic,
+ type AnyActorLogic,
+ type AnyActorRef,
+ type AnyActorSystem,
+ type AnyEventObject,
+ type EventObject,
+ type Snapshot,
+ type StandardSchemaV1
+} from 'xstate';
+import { EffectInterruptedError } from './errors.ts';
+import type { EffectRequirements } from './types.ts';
+import { relayToParent, startHostedEffect } from './internal.ts';
+import {
+ type EffectSchemaLike,
+ type ToStandardSchema,
+ type ValidateEffectActorSchemas,
+ toStandardSchema
+} from './schema.ts';
+
+const EFFECT_INIT = '@xstate.init';
+const EFFECT_RESOLVE = 'xstate.effect.resolve';
+const EFFECT_REJECT = 'xstate.effect.reject';
+const EFFECT_NEXT = 'xstate.effect.next';
+const EFFECT_COMPLETE = 'xstate.effect.complete';
+
+const effectLogicBrand: unique symbol = Symbol.for(
+ '@xstate/effect/logic'
+) as any;
+
+/**
+ * Type-level marker attached to logic created by `fromEffect`,
+ * `fromEffectStream` and `fromEffectEventStream`. It carries the logic's
+ * failure type and its Effect service requirements, which is how
+ * `RequirementsFrom` collects the `R` channel of `createEffectActor` without
+ * inspecting the logic at runtime.
+ */
+export interface EffectLogicBrand {
+ readonly [effectLogicBrand]: {
+ readonly error: TError;
+ readonly requirements: TRequirements;
+ };
+}
+
+/**
+ * Snapshot of a `fromEffect` actor. The actor holds no context of its own: it
+ * is `active` while the Effect runs, `done` with the Effect's success value as
+ * `output`, or `error` with the Effect's failure, defect or
+ * `EffectInterruptedError` as `error`.
+ */
+export type EffectSnapshot = Snapshot & {
+ readonly context: undefined;
+ readonly input: TInput | undefined;
+ readonly error: TError | undefined;
+};
+
+/**
+ * Argument passed to the function form of an Effect source. It gives the
+ * source the actor's `input`, its own reference (`self`), the actor `system`,
+ * and `emit` for publishing events that `actor.on(...)` and `emitted(actor)`
+ * observe.
+ */
+export type EffectSourceArgs = {
+ readonly input: TInput;
+ readonly self: AnyActorRef;
+ readonly system: AnyActorSystem;
+ /** Emits an event that can be observed with `actor.on(...)` or `emitted(actor)`. */
+ readonly emit: (event: AnyEventObject) => void;
+};
+
+/**
+ * What `fromEffect` accepts as its Effect: either an Effect value, or a
+ * function of {@link EffectSourceArgs} returning one. The function form is
+ * called once per actor start, so it sees that actor's input.
+ */
+export type EffectSource =
+ | Effect.Effect
+ | ((
+ args: EffectSourceArgs
+ ) => Effect.Effect);
+
+type EffectActorSchemas = {
+ readonly input?: EffectSchemaLike;
+ readonly output?: EffectSchemaLike;
+};
+
+type EffectSourceConfig<
+ TOutput,
+ TError,
+ TInput,
+ TRequirements,
+ TSchemas extends EffectActorSchemas = EffectActorSchemas,
+ TValidator extends ActorLogicValidator | undefined =
+ | ActorLogicValidator
+ | undefined
+> = {
+ readonly id?: string;
+ readonly validator?: TValidator;
+ readonly schemas?: TSchemas &
+ ([TValidator] extends [ActorLogicValidator]
+ ? ValidateEffectActorSchemas
+ : unknown);
+ readonly effect: EffectSource;
+};
+
+type SchemaOutput =
+ StandardSchemaV1.InferOutput>;
+
+type EffectSuccess = T extends Effect.Effect ? A : never;
+
+type EffectFailure = T extends Effect.Effect ? E : never;
+
+type EffectSchemaValidationConfig =
+ | {
+ readonly validator: ActorLogicValidator;
+ readonly schemas: TSchemas & ValidateEffectActorSchemas;
+ }
+ | {
+ readonly validator?: undefined;
+ readonly schemas: TSchemas;
+ };
+
+/**
+ * Actor logic produced by `fromEffect` and `fromEffectEventStream`. It is
+ * ordinary XState actor logic carrying {@link EffectLogicBrand}, so a machine
+ * can invoke or spawn it, and `createEffectActor` can collect its
+ * requirements.
+ */
+export type EffectActorLogic =
+ ActorLogic<
+ EffectSnapshot,
+ EventObject,
+ TInput,
+ AnyActorSystem
+ > & { readonly id?: string } & EffectLogicBrand;
+
+/**
+ * Snapshot of a `fromEffectStream` actor. `context` holds the most recent
+ * stream item, or `undefined` before the first one. The actor reaches `done`
+ * with no output when the stream completes, and `error` when it fails.
+ */
+export type EffectStreamSnapshot =
+ Snapshot & {
+ readonly context: TItem | undefined;
+ readonly input: TInput | undefined;
+ readonly error: TError | undefined;
+ };
+
+/**
+ * Actor logic produced by `fromEffectStream`. Its snapshot is an
+ * {@link EffectStreamSnapshot}, so the parent reads the latest item from the
+ * child's `context` rather than from events.
+ */
+export type EffectStreamActorLogic =
+ ActorLogic<
+ EffectStreamSnapshot,
+ EventObject,
+ TInput,
+ AnyActorSystem
+ > & { readonly id?: string } & EffectLogicBrand;
+
+function toError(exit: Exit.Exit): unknown {
+ if (Exit.isSuccess(exit)) {
+ return undefined;
+ }
+ if (Cause.hasInterruptsOnly(exit.cause)) {
+ return new EffectInterruptedError({
+ cause: exit.cause as Cause.Cause
+ });
+ }
+ return Cause.squash(exit.cause);
+}
+
+function createSourceArgs(
+ input: TInput,
+ self: AnyActorRef,
+ system: AnyActorSystem
+): EffectSourceArgs {
+ return {
+ input,
+ self,
+ system,
+ emit: (event) => {
+ void system.emitEvent(self as any, event);
+ }
+ };
+}
+
+function brandLogic(
+ logic: TLogic,
+ error: unknown,
+ requirements: unknown
+): TLogic {
+ Object.defineProperty(logic, effectLogicBrand, {
+ configurable: false,
+ enumerable: false,
+ value: { error, requirements }
+ });
+ return logic;
+}
+
+/**
+ * Creates actor logic that runs an Effect. The actor completes with the
+ * Effect's success value as its output and fails with the Effect's error, its
+ * squashed defect, or an `EffectInterruptedError` when the Effect interrupts
+ * itself. Stopping the actor interrupts the Effect without an error. Accepts
+ * an Effect, a function of {@link EffectSourceArgs} returning one, or a config
+ * object with `id`, `schemas`, `validator` and `effect`. The logic must be run
+ * under `createEffectActor`, which provides the Effect services it declares.
+ * Resources belong to this task's scope and close on completion, failure or
+ * interruption. Use `withActorScope` to retain a resource until the owning
+ * Effect actor stops.
+ */
+export function fromEffect<
+ const TInputSchema extends EffectSchemaLike,
+ const TOutputSchema extends EffectSchemaLike,
+ TError = unknown,
+ TRequirements = never
+>(
+ config: Omit<
+ EffectSourceConfig<
+ SchemaOutput,
+ TError,
+ SchemaOutput,
+ TRequirements
+ >,
+ 'schemas' | 'validator'
+ > &
+ EffectSchemaValidationConfig<{
+ input: TInputSchema;
+ output: TOutputSchema;
+ }>
+): EffectActorLogic<
+ SchemaOutput,
+ TError,
+ SchemaOutput,
+ TRequirements
+>;
+export function fromEffect<
+ const TInputSchema extends EffectSchemaLike,
+ TEffect extends Effect.Effect
+>(
+ config: Omit<
+ EffectSourceConfig<
+ EffectSuccess,
+ EffectFailure,
+ SchemaOutput,
+ EffectRequirements,
+ { input: TInputSchema }
+ >,
+ 'effect' | 'schemas' | 'validator'
+ > &
+ EffectSchemaValidationConfig<{
+ input: TInputSchema;
+ output?: never;
+ }> & {
+ effect:
+ | TEffect
+ | ((args: EffectSourceArgs>) => TEffect);
+ }
+): EffectActorLogic<
+ EffectSuccess,
+ EffectFailure,
+ SchemaOutput,
+ EffectRequirements
+>;
+export function fromEffect<
+ const TOutputSchema extends EffectSchemaLike,
+ TError = unknown,
+ TInput = undefined,
+ TRequirements = never
+>(
+ config: Omit<
+ EffectSourceConfig<
+ SchemaOutput,
+ TError,
+ TInput,
+ TRequirements
+ >,
+ 'schemas' | 'validator'
+ > &
+ EffectSchemaValidationConfig<{
+ input?: never;
+ output: TOutputSchema;
+ }>
+): EffectActorLogic, TError, TInput, TRequirements>;
+export function fromEffect<
+ TOutput,
+ TError = unknown,
+ TInput = undefined,
+ TRequirements = never
+>(
+ config: EffectSourceConfig & {
+ schemas?: undefined;
+ }
+): EffectActorLogic;
+
+export function fromEffect(
+ effect: Effect.Effect
+): EffectActorLogic