Skip to content

effect@4.2.0

Choose a tag to compare

@effect-bot effect-bot released this 02 Dec 04:14
b16fde2

Thanks to these issue reporters

Minor Changes

  • #10149 ad548eb - Add Toolkit.HandlerContext.modelOutput so tool handlers can set the model-facing output for their final result.

    Manually constructed Toolkit.HandlerContext values must now include modelOutput (e.g. () => Effect.void).

  • #10149 33352ec - Support passing numeric file descriptors in ChildProcess (stdin, stdout, stderr, and additionalFds) and add ChildProcessHandle.exitStatus (ExitStatus) for structured exit codes and terminating signals.

    Custom ChildProcessSpawner.makeHandle implementations must now provide exitStatus.

  • #11289 c97eaa9 - Add Context.isServiceNotFoundError to recognize missing-service defects and read the missing service's key without parsing the error message.

  • #10149 ac4eb36 - Cookies now identifies cookies by name, domain and path, so HttpClientResponse.cookies, HttpClient.withCookiesRef and HttpServerResponse keep same-name cookies set for a different domain or path.

    • Cookies.cookies and the Schema.Cookies isomorphic encoding are now a ReadonlyArray<Cookie> in the order cookies were last set. Replace cookies.cookies[name] with Cookies.get or Cookies.getValue.
    • On cookies.cookies, in and Object.hasOwn check array properties rather than cookie names, while Object.keys and Object.entries enumerate array indices rather than names. Use Option.isSome(Cookies.get(cookies, name)) for name-based membership, or enumerate Cookies.toRecord(cookies) for names and decoded string values (the last cookie set for each name).
    • Cookies constructors and combinators that add a cookie, and the HttpServerResponse cookie helpers, replace an existing cookie only when its name, domain and path match. Pass the same domain and path to override or expire a cookie.
  • #11082 d056634 - Add captureStackTrace: false to Effect.fn to skip call-site stack capture while retaining the definition location and, for named functions, the tracing span.

  • #11076 1bd72dd - Add EventLog.replay and a replay option for EventLog.layer, which rebuild projections by running the registered handlers over the local journal.

  • #11075 21b678d - Fix FileSystem.remove failing on empty directories on Node and Bun, and report non-empty directories with the new DirectoryNotEmpty tag. Exhaustive SystemErrorTag handlers must add a DirectoryNotEmpty case.

  • #10149 36a5e5f - Add Filter.map to transform passing values while preserving failures.

  • #11273 b65551a - HttpApiClient client spans now record the endpoint path as url.template and are named like GET /users/:id instead of GET. Provide HttpClient.SpanNameGenerator with (request) => request.method to restore method-only names.

  • #10149 d055e9f - Add failsWith to HttpClient.withRateLimiter to report limiter failures as either raw limiter errors or HTTP transport errors.

    Omitting the option still returns raw limiter errors at runtime. Calls with an omitted, hidden, or union-valued mode now add both RateLimiterError and HttpClientError to the inferred error type. Specify failsWith: "RateLimiterError" to retain the previous narrow type, or failsWith: "HttpClientError" to add only the HTTP error.

  • #10149 96596ea - Build HttpRouter.toHttpEffect apps with their own router, so sub-app routes and middleware no longer register on the outer server's router when built inside HttpRouter.serve or HttpRouter.toWebHandler. The sub-app's router also stands in for HttpRouter.layer within the app, so apps that provide it themselves are isolated too.

    HttpRouter.serve likewise always builds its own router, instead of reusing an HttpRouter.layer already built outside it. Its routerConfig option now always applies.

    Layer.forkMemoMap, Layer.forkMemoMapUnsafe and Layer.CurrentMemoMap.forkOrCreate accept a fresh option listing layers that the child memo map builds again instead of reusing from its parent.

  • #10149 e29869a - Add Match.whenFilter, a case that runs a Filter once and passes its extracted value to the handler, falling through with the original input when the filter fails.

  • #10149 847e605 - McpSchema.InputRequired is now a schema class and McpSchema.McpInputRequest is now a schema, so a toolkit tool can declare failure: McpSchema.InputRequired.

    Migration

    • The McpSchema.InputRequired constructor now validates its fields and throws when they are invalid, for example for an unknown input request method.
    • A Schema.instanceOf(McpSchema.InputRequired) failure schema has no JSON codec, so in failureMode: "return" it fails with ToolResultEncodingError. Declare failure: McpSchema.InputRequired instead.
  • #11256 6c6ea9f - McpServer now classifies server-generated tool error results as failure (with an optional tag), invalidInput, or internal in _meta["website.effect/toolError"], decoded with McpSchema.ToolErrorInfo. Undeclared failures in "return" mode now produce a generic error message, as in "error" mode.

  • #10149 d211297 - McpServer.toolkit and McpServer.registerToolkit return a declared McpSchema.InputRequired failure as an input_required result, so toolkit tools can request client input.

  • #11179 50c5327 - MCP Toolkit tools whose success JSON Schema has a top-level type: "string" now omit outputSchema and structuredContent, returning plain text by default or toModelOutput content when configured.
    On 2026-07-28, clients of these tools must omit schema from McpClient.callTool and read content instead; see the client migration guide.

  • #10149 f6075de - Add trace sampling to the OTLP tracer.

  • #10149 a366aea - Add the unstable PathFilter module, make FileSystem.glob take a single PathFilter.Input instead of a pattern and options, and add experimental IgnoreFile parsers that build PathFilters from .gitignore and .dockerignore sources.

  • #10149 4fcd9ac - Add acquiring to Pool.stats and PgClient.poolStats to count in-flight acquisitions independently of waiting borrowers.

    Manually constructed Pool.Stats snapshots must include acquiring (use 0 when no acquisition is running).

  • #11118 4641c9c - Fix RPC and MCP stdio servers to skip lines containing only spaces or tabs and reply with -32600 Invalid Request for JSON values that are not JSON-RPC messages.

  • #10149 c1bbe62 - Add the module function Semaphore.withPermitsTraced(limit, permits, spanName, options?) to trace time spent waiting for permits without tracing the guarded effect.

  • #11083 3504edd - effect/crypto can now sign and verify ML-DSA (FIPS 204) with Signature.mlDsa44, Signature.mlDsa65 and Signature.mlDsa87, and KeyFormat reads and writes ML-DSA keys as SPKI and PKCS#8.

  • #10149 a154d06 - Add SqlClient.batch, which returns each statement's rows as a typed tuple and runs as one atomic round trip on PostgreSQL (also via the new PgConnection.batch) and libSQL, or one statement at a time on drivers without the new optional Connection.executeBatch hook.

  • #10149 f22c052 - Add onStdinEnd: "interrupt" to McpServer.layerStdio and RpcServer.layerProtocolStdio to stop the server when stdin closes, interrupting active requests without remote cancellation.

    Breaking changes

    • RpcServer.layerProtocolStdio and RpcServer.makeProtocolStdio are now functions: replace RpcServer.layerProtocolStdio with RpcServer.layerProtocolStdio() and RpcServer.makeProtocolStdio with RpcServer.makeProtocolStdio().
  • #11251 d1667dc - Add data-first forms to String.replace, replaceAll, slice, substring, includes, startsWith, endsWith, indexOf, lastIndexOf, localeCompare, match, matchAll, padStart, padEnd, and repeat.

    When passing these helpers as callbacks, use a unary wrapper to avoid type errors or unintended data-first calls, for example counts.map((n) => String.repeat(n)).

  • #10149 603e1ef - Add String.hasNonWhitespace, which checks whether a string contains at least one non-whitespace character.

  • #11147 7f2cc86 - String.indexOf and String.lastIndexOf now accept an optional position argument to start the search at an offset.

  • #10149 30a8fbf - Add a blockedOn option to Effect.callback, which tells a Supervisor what the waiting fiber is blocked on; existing calls are unchanged.

    Also add the experimental Supervisor module for observing fiber lifecycles. A Supervisor is called when each fiber starts, blocks, unblocks and ends, and is told what a blocked fiber waits on. Install one with Effect.withSupervisor or Supervisor.layer, and combine several with Supervisor.combine. This release also adds TestClock.stateUnsafe for reading the pending test sleeps, and the guards Latch.isLatch, Semaphore.isSemaphore, PartitionedSemaphore.isPartitionedSemaphore, TxRef.isTxRef and PubSub.isSubscription.

  • #11256 6c6ea9f - Add Tar.encode({ omitEndOfArchive: true }) to omit the end-of-archive marker from intermediate fragments of a concatenated archive. Use Tar.encode() for the final fragment to write the marker.

  • #10149 5fea4eb - Support TOML 1.1 syntax in Toml.parse: multiline inline tables with comments and trailing commas, the \e and \xHH escapes, and times without seconds. Times without seconds are normalized to :00, so 13:37 parses as "13:37:00".

  • #11256 6c6ea9f - Add page scroll and viewport resize events to HtmlSubscription.onWindow, carrying page offsets and viewport dimensions. TestGlobalEvents.fire and HtmlScene.fireWindow support both events with payload fields defaulting to zero.

  • #10149 3fae6ad - Add Yaml.parseAll for YAML document streams, with anchors scoped to each document and support for the %YAML 1.2 directive.

    Yaml.parse now fails on input it used to misread instead of skipping or dropping it: %YAML versions other than 1.2, %TAG and other directives, a directive without a following ---, and plain scalars starting with %. Input with more than one document still fails, with a message pointing to Yaml.parseAll.

  • #10149 ddd3e73 - Yaml.parse now returns a Result instead of throwing, failing with an EncodingError on invalid input.

  • #10149 24e1b04 - Add Yaml.stringify and Yaml.stringifyAll for block-style YAML output, and extend parsing with YAML 1.2 core tags and more collection and multiline scalar syntax.

    Breaking changes

    • Yaml.parse and Yaml.parseAll now use YAML 1.2 core scalar, tag and key resolution. Quote values and keys to preserve literal text.
    • Unsupported tags, key properties and invalid or ambiguous collection syntax now fail instead of becoming text. Quote literals or use supported YAML syntax.
    • Non-YAML whitespace is preserved, and parsing enforces nesting and merge-expansion limits. Remove unintended whitespace or byte order marks, and reduce excessive nesting or merge expansion.

Patch Changes

  • #11291 45cbe18 - Fix Schema.toType(SchemaBinary.toCodec(schema)) accepting invalid values when encoding.

  • #11214 d65c927 - Allow rel="external" on links and GET forms to trigger full page loads in BrowserRouter.

  • #11209 d0c4ccb - Pass restore: false to BrowserRouter.layer, BrowserRouter.layerHash, or Router.memory to disable saving and restoring component state and query results for the whole router.

  • #11051 ddc5b58 - In browsers without setImmediate, fibers now yield through scheduler.postTask when it is available, avoiding the 4ms clamp on nested setTimeout calls. Forks, waits, onExit finalizers, Queue.offer, Queue.take and Pool lease returns take fewer fiber steps, so returned leases are available sooner and automatic yields can land at different points.

  • #11035 28232de - Reduce allocation when a failure passes through exit handlers inside a traced call such as Effect.fn. Cause.annotate and the runtime no longer call a reason's own annotate method, so overriding it is not supported.

  • #11306 c89bd42 - Reduce allocation in Cause.combine when merging causes with distinct reasons.

  • #11074 981d2b4 - Fix cluster entities retired by the idle reaper interrupting requests that arrived while they were being removed; those requests now complete on the existing entity or its successor.

  • #10991 8dfec63 - Fix ClusterWorkflowEngine waking a polling parent before a discarded child workflow's result is saved, by deferring the parent's resume wake with DeliverAt until the child's terminal reply is stored.

  • #11030 0aec37c - Context.add reuses an existing overlay slot when replacing a service, avoiding a full service-map copy even at the overlay limit.

  • #11031 4d6ba15 - Context.merge, Effect.provideContext and Effect.provide(context) can avoid copying a large context when adding a few services to it.

  • #11065 201e714 - Reduce allocations in Effect.all over a struct.

  • #11180 855acf5 - Add effect/ui, a UI library built on Effect, moved here from the Effect-TS/ui repository. Its API is unstable and may change in minor releases.

    • effect/ui: components, views, commands, queries and routing.
    • effect/ui/html: the DOM host, server rendering, hydration and Vite plugins.
    • effect/ui/kit: headless, accessible components such as Dialog, Menu, Select and Tabs.
    • effect/ui/testing and effect/ui/html/testing: test hosts and helpers.

    Add three packages alongside it:

    • @effect/ui-devtools: an inspector, overlay and MCP server for an app's message log.
    • @effect/ui-native (experimental): a React Native host, without React.
    • @effect/ui-opentui (experimental): an OpenTUI terminal host.
  • #11087 3674d15 - EventJournal.layerIndexedDb now announces committed entries to other tabs on the same database, so their EventLog invalidates groupReactivity keys without a server round trip.

  • #11268 27b090b - effect/ui/MessageLog now shows whether a fetch started without a cached success (empty) and which component's watch or $.loadMore started it (watcher). Watch fetches retain their render's causedBy when updates are batched.

  • #11013 546da96 - Resume fibers whose captured async context can no longer be entered, such as a context from an ended Cloudflare Workers request, instead of leaving them suspended.

  • #11069 e9d5f83 - Effect.fn and Effect.withSpan calls allocate less, because the fiber cache is no longer rebuilt when only the span or stack frame changes.

  • #11212 e8d9fae - QueryPersistence.layerKvs now skips the one-second write delay when the app becomes hidden and for subsequent saves while hidden, including while offline.

  • #11067 371aa23 - Reduce allocations in sequential Effect.forEach and Effect.all over arrays.

  • #11036 9c88614 - Reduce memory allocated per call by Formatter.formatJson and the JSON loggers built on it.

  • #11112 6807aac - Add HttpApiClient.fromGroup to build a typed client for an HttpApiGroup without declaring an HttpApi.

  • #11290 65199a4 - Add HttpApiMiddleware.layerClientSecurity and HttpApiClient.securityEncode so HTTP API clients send credentials where the middleware's security scheme declares them.

  • #11114 df4258d - Validate explicit closed params schemas in HttpApiEndpoint against encoded wire keys for segment-leading :param placeholders at compile time and runtime (including .prefix()), while preserving literal action suffixes and omitted params for raw HttpRouter.RouteContext handlers.

  • #11301 1a1cb48 - Add opt-in W3C baggage parsing with HttpMiddleware.baggage and forwarding with HttpClient.withBaggage. HttpClient.followRedirects strips baggage on cross-origin redirects.

  • #11120 c1c81fa - Add HttpClient.retryAfterAtMost(max) for use with Schedule.while to stop retryTransient before sleeping when the server's Retry-After delay exceeds max.

  • #11037 945fe8f - Reduce allocations in Headers.isRedactedName and HTTP client response headers, which are now read from the source once per response.

  • #11287 dc1ebd4 - Add HttpMiddleware.rateLimit to enforce a RateLimiter quota with customizable 429 responses, quota headers, and Retry-After for finite delays. Fix HttpEffect.toHandled to run pre-response handlers when middleware returns a response without running the app.

  • #11177 f4d1d82 - Add ready() to HttpEffect.toWebHandlerLayer, HttpEffect.toWebHandlerLayerWith, and HttpRouter.toWebHandler. Its promise resolves once the handler is installed or rejects with the build error, so callers can await initialization before accepting requests.

  • #11203 aa0be5a - Restrict hydration's submit handling to HTML forms so it no longer cancels submit events on SVG or MathML elements named form.

  • #11249 eb38445 - Fix Ini.parse to replace earlier scalar or array values with sections when their names match, including empty sections. Repeated sections continue to merge.

  • #10940 8245e5a - Add an unstable onReference option to JsonSchema.fromSchemaOpenApi3_1 and JsonSchema.fromSchemaOpenApi3_0 to report each visited reference with its original value and keyword.

  • #11007 7c99faa - Include the build error in LayerRef.make and LayerRef.Service layer types whenever preload can be true.

  • #11310 2f31adb - Add McpServer.layerHttp's maxSessions option (default 10_000, "unbounded" to disable eviction) to evict the least recently used idle sessions, whose ids then receive 404. Active POSTs protect their sessions through response completion, allowing temporary overflow that later initialization trims as sessions become idle.

  • #11010 a2d31c4 - Fix McpServer omitting $defs from tool input schemas on MCP protocol revisions 2024-11-05 and 2025-03-26, which left nested $refs dangling.

  • #11274 32ee528 - McpServer wrappers made with object spread or Object.create now support global middleware, skills, and transports. Override the new addToolSource service member to intercept tool source registrations.

  • #11078 7dc82f5 - Stopping McpServer.layerStdio no longer answers interrupted in-flight requests with a JSON-RPC Internal error.

  • #11018 b1d15a7 - Add McpServer.toolSource and McpServer.registerToolSource for per-request MCP tool resolution and dispatch.

  • #11161 04a5000 - Omit outputSchema from McpServer.registerToolkit tool listings when the success schema encodes only absent results, such as Schema.Void or Schema.Undefined. This prevents MCP clients from rejecting successful calls that return no structuredContent.

  • #11012 3b50fb3 - Preserve frequency counts returned by Metric.value, Metric.snapshot, and Metric.snapshotUnsafe when later updates record more observations.

  • #11032 3260f0d - Reduce allocations when a metric is updated with several attribute sets in turn, such as alternating Metric.withAttributes wrappers.

  • #11057 e4541d4 - Reduce the per-call allocation and run-loop cost of Metric.update, Metric.modify, Metric.value and Metric.remove.

  • #11280 12c9c65 - Add PersistedQueue.migrationsSql and layerMigrationsSql to run SQL queue migrations during deployment, and makeStorageSql and layerStorageSql to start workers without migrating. Existing makeStoreSql and layerStoreSql callers still migrate on startup.

  • #11038 3727adf - Pool no longer starts another acquisition after a failed checkout when no borrower is still waiting.

  • #11257 9e39a91 - Fix BrowserHost creating h.el descendants such as title, a, and feDropShadow in the HTML namespace under <svg>. Preserve SVG namespaces during updates, including when placing bound children again.

  • #11108 fff554d - Preserve an explicitly provided empty string delimiter in Prompt.List instead of falling back to ",".

  • #11063 6da66ca - Reduce allocations in data-first and data-last Effect.provideService calls.

  • #11299 9a8167f - Export Query.makeSignal and Query.SettableSignal from effect/ui for custom connectivity and visibility sources. makeSignal now delivers changes to the remaining listeners when one throws and rethrows the error in a microtask.

  • #11215 df99cfb - Make Route.union in effect/ui resolve malformed path escapes to the "/*" catch-all under the route base, preserving malformed segments in params["*"].

  • #11275 4b77125 - Router.page accepts a Component.lazy page: link intent starts its load, then prefetches its queries.

  • #11261 83ea661 - Add Router.unsettled to effect/ui to defer navigation settlement, including scrolling, focus and announcements, while a component holds the subscription. URL and history updates continue as usual.

  • #11130 e307b4b - Keep sibling RPC requests running when server middleware throws synchronously and disableFatalDefects is enabled.

  • #11282 9fc56a0 - Add onInvalidRequest to RpcServer.make and its layer and HTTP helpers to observe requests rejected before dispatch for unknown tags or invalid payloads, headers or ids.

  • #11207 358dcaf - Add spanPrefix and spanAttributes options to RpcTest.makeClient, applying them to both the in-memory RPC client and server spans.

  • #11201 0927cc2 - Preserve existing compiled decoders for dependencies when installing a parent decoder generated by SchemaAOTCompiler.compile.

  • #11006 684c691 - Fix SchemaBinary decoding so that reusing a Node.js Buffer leaves previously decoded byte fields intact.

  • #11229 efedd8f - When a keyed Component.provide supplies Query.layer(), changing the key now disposes the old cache and interrupts its in-flight fetches. Queries in that subtree use a new, empty cache, so unchanged query arguments no longer reuse results from the previous key.

  • #11259 cb78062 - Query.StreamService now accepts persist: true with QueryPersistence to show the latest saved stream value as a stale Success while reconnecting, until the first live value replaces it. Optimistic patches are not persisted.

  • #11281 e0a1505 - Add TestTerminal to effect/testing for scripting terminal input and capturing displayed text. By default, Prompt.run fails with Terminal.QuitError if it still needs input when the script runs out.

  • #11258 b42d21d - Add swipeDistance and swipeVelocity props to ToastProvider to configure swipe dismissal thresholds, defaulting to 40 px and 0.5 px/ms.

  • #11307 fe45cb3 - Reduce per-call memory allocations for named Effect.fn functions and Effect.withSpan.

  • #10710 f09b12c - Add TranscriptionModel to effect/ai for speech-to-text on recordings and live audio, with OpenAiTranscriptionModel and OpenRouterTranscriptionModel.

    Hand-built OpenAiClient and OpenRouterClient services must add createTranscription.

  • #11302 4872d93 - Use MessageLog.fanout to register mounted browser roots with each layer's BrowserHost.Controllables; attached DevTools also receives roots and log entries alongside your app's registries and logs. In tests, look up a mounted child by its logged instance number with TestHost.Root.instance (or Renderer.instance), then run the returned handle's dispatch effect to send it a message without a DOM.

  • #11198 faa3783 - Fix unbounded memory growth in MessageLog.socket while disconnected from the DevTools server or after the sender stops on a defect.

  • #11180 855acf5 - In development, effect/ui warns with Command.InterruptedByRemount when a view remounts the same component and key in one flush, losing Command runs or undelivered results. TestHost.settle and Play tests fail on this problem unless it is consumed with expectProblem.

  • #11217 e4a4959 - Combobox and Autocomplete in effect/ui/kit now emit RequestedClose with reason "focus-out" when focus leaves the widget even if no other element receives focus, such as after calling blur().

  • #11298 353f3a7 - Return focus to the Menu, Select, or Combobox trigger when a modal Dialog opened by an item selection closes. This includes returning to the root menu's trigger after a submenu selection and to triggers inside shadow roots.

  • #11227 3b4f9aa - Prevent unwanted focus rings in Chrome when using a pointer to open, navigate, or close a Menu, Select, or follow-up Dialog. Keep focus rings for keyboard navigation and text fields.

  • #11296 6e2d8a4 - Prevent drags from controls or data-swipe-ignore elements inside open shadow roots from starting swipes in Toast, Swipe and mouse-driven Drawer gestures. Drawer touch gestures still allow drags from controls, but now respect data-swipe-ignore, scroll containers and text selection in fields inside open shadow roots.

  • #11286 cc0db8b - Tapping a toast in a ToastProvider stack of two or more visible, non-closing toasts now expands the stack and pauses dismissal timers. Tap expansion ends when a touch lands outside the viewport or fewer than two non-closing toasts fit within the provider's limit.

  • #11284 9fa1911 - Add MarkdownParser.parseMarkdownLenient to effect/ui/html to recover unsupported Markdown as text and return line diagnostics. Support GFM task lists through ListItem.checked, rendered as disabled checkboxes by the default view.

  • #11197 d3fc293 - Publish updated effect/ui Mount arguments after the host commits, or after rendering but before the host commits with beforeCommit: true. New changes subscribers start with the latest published arguments.

  • #11288 be64268 - Query args callbacks can now access shared values through $.reads. Queries follow changes to those values even when the reader's model and props stay unchanged, without requiring onChange.

  • #11228 88f3dc2 - Allow router.replace(route) and router.navigate(href, { replace: true }) in effect/ui to remove undeclared search parameters omitted from the target URL, even when the route is unchanged. This updates the current history entry and router location without starting a navigation; a pending navigation for that entry settles with the updated URL.

  • #11263 124881f - Allow Scene.expectMount, Scene.mounted, and Play.expectMount to take a leading Locator to disambiguate identical mounts on different elements.

  • #11260 0498d4d - Allow Story.fromLog in effect/ui/testing to replay a mounted log entry's component without a cast. Calls with concrete components retain their inferred types.

  • #11230 0a65a4d - Test headless components with Story.make, Story.start, Story.explore, and Story.check without casts, with inferred model and message types. Story.fromLog now preserves those types when replaying a headless component's message log.

  • #11213 d08c75a - Make VirtualList use its viewport part's scroll limit for End(), atEnd and followEnd, including padding and content after the list. With scrollContainer or page scrolling, keep the list's end as the boundary and prevent followEnd from pulling users back after they scroll past it.

  • #11265 458dad1 - Add schedule support to Activity.retry, using DurableClock to suspend workflows during long retry delays.