Octomind
Same model as opencode, same endpoint, same prices — octomind solved 24/25 to its 19/25, at half the cost. Open-source agent runtime: one binary, any model, runs unattended in CI. Apache 2.0.
翻譯準備中
Powerful, joyful building blocks for modern cloud-native applications.
翻譯準備中
取自儲存庫 README
正在載入完整 README。
檢視完整 README ↗Modular building blocks for modern Scala applications—no effect system required.
ZIO Blocks is a family of type-safe, modular building blocks for Scala applications. Each block is a standalone library with zero or minimal dependencies, designed to work with any Scala stack—ZIO, Cats Effect, Kyo, Ox, Akka, or plain Scala.
The philosophy is simple: use what you need, nothing more. Each block is independently useful and designed to compose with other blocks or your existing code.
To call ZIO Blocks from a ZIO or cats-effect application, see How to Use ZIO Blocks in a ZIO or cats-effect Application.
Add a block and use it. Nothing else to wire up—no runtime to install, no effect type to adopt:
libraryDependencies += "dev.zio" %% "zio-blocks-schema" % "0.0.56"
That line is for Scala 2.13 and Scala 3.3 to 3.8. On Scala 3.9 and newer, use zio-blocks-next-schema and add scalacOptions += "-experimental". See How to Add ZIO Blocks to Your Build for Scala.js, scala-cli, and cross-building.
import zio.blocks.schema._
case class Person(name: String, age: Int)
object Person {
implicit val schema: Schema[Person] = Schema.derived
}
val alice = Person("Alice", 30)
// One schema, every format
val jsonStr = alice.toJsonString // {"name":"Alice","age":30}
val parsed = """{"name":"Bob","age":25}""".fromJson[Person]
New to ZIO Blocks? Getting Started is a short tour of the core ideas, and the Your First Schema tutorial is the first hands-on lesson.
The four blocks below get a full walkthrough because they have no close equivalent elsewhere in Scala. Every other block is one row away in the catalog, and each row links to its own reference page.
Every block is published under the dev.zio organization. Most cross-build for
Scala 2.13 and 3.x on both JVM and Scala.js with full source compatibility —
adopt Scala 3 on your timeline, not ours. The handful of modules that are narrower
say so in their own row.
JSON support is built into zio-blocks-schema; the modules below add further formats.
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| Schema | zio-blocks-schema | JVM · JS | 2.13 · 3.x | Type-safe schemas with automatic codec, optic, and validator derivation |
| Avro Codec | zio-blocks-schema-avro | JVM | 2.13 · 3.x | Apache Avro binary serialization with automatic schema generation |
| BSON Codec | zio-blocks-schema-bson | JVM | 2.13 · 3.x | MongoDB-compatible BSON serialization with native type support |
| CSV Codec | zio-blocks-schema-csv | JVM · JS | 2.13 · 3.x | RFC 4180-compliant CSV serialization |
| MessagePack Codec | zio-blocks-schema-messagepack | JVM · JS | 2.13 · 3.x | Compact binary serialization with optimized streaming |
| Thrift Codec | zio-blocks-schema-thrift | JVM | 2.13 · 3.x | Apache Thrift binary serialization with TBinaryProtocol |
| TOON Codec | zio-blocks-schema-toon | JVM · JS | 2.13 · 3.x | Token-oriented notation 30–60% smaller than JSON, tuned for LLM prompts |
All of these ship in zio-blocks-scope.
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| Scope | zio-blocks-scope | JVM · JS | 2.13 · 3.x | Compile-time safe resource boundaries that keep values from escaping their lifetime |
| Resource | zio-blocks-scope | JVM · JS | 2.13 · 3.x | Lazy recipes that pair acquisition with finalization, composable with map, flatMap, and zip |
| Unscoped | zio-blocks-scope | JVM · JS | 2.13 · 3.x | Marker typeclass for plain data that can safely leave a scope |
| DeferHandle | zio-blocks-scope | JVM · JS | 2.13 · 3.x | Handle returned by Scope.defer for cancelling a registered finalizer |
| Finalizer | zio-blocks-scope | JVM · JS | 2.13 · 3.x | Minimal capability interface for registering cleanup actions |
| Finalization | zio-blocks-scope | JVM · JS | 2.13 · 3.x | Result of running a scope's finalizers, including any cleanup errors |
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| Wire | zio-blocks-scope | JVM · JS | 2.13 · 3.x | Compile-time safe recipes for constructing a service and its dependencies |
| Context | zio-blocks-context | JVM · JS | 2.13 · 3.x | Type-indexed heterogeneous collections |
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| Configuration | zio-blocks-config | JVM · JS | 2.13 · 3.x | Typed configuration loading, feature flags, and rollout rules |
| Config YAML | zio-blocks-config-yaml | JVM · JS | 2.13 · 3.x | YAML source adapter for ConfigSource |
| Config JSON | zio-blocks-config-json | JVM · JS | 2.13 · 3.x | JSON source adapter for ConfigSource |
| Config HOCON | zio-blocks-config-hocon | JVM · JS | 2.13 · 3.x | HOCON source adapter for ConfigSource |
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| MediaType | zio-blocks-mediatype | JVM · JS | 2.13 · 3.x | Type-safe IANA media types with 2,600+ predefined types |
| HTTP Model | zio-blocks-http-model | JVM · JS | 2.13 · 3.x | Pure HTTP data model with URL parsing, headers, cookies, and forms |
| HTTP Model Schema | zio-blocks-http-model-schema | JVM · JS | 2.13 · 3.x | Schema-based typed access to the HTTP model |
| Endpoint | zio-blocks-endpoint | JVM · JS | 2.13 · 3.x | Type-safe HTTP endpoint descriptors with composable codecs and typed auth |
| OpenAPI | zio-blocks-openapi | JVM · JS | 2.13 · 3.x | Type-safe OpenAPI 3.1 specification generation and rendering |
| JWT | zio-blocks-jwt | JVM · JS | 2.13 · 3.x | Zero-dependency JWT signing and verification with HMAC, RSA, ECDSA and EdDSA support |
| HTML | zio-blocks-html | JVM · JS | 2.13 · 3.x | Type-safe HTML templating with XSS protection |
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| Chunk | zio-blocks-chunk | JVM · JS | 2.13 · 3.x | High-performance immutable indexed sequences with zero-boxing builders |
| Maybe | zio-blocks-maybe | JVM · JS | 2.13 · 3.x | Optional values that store a present reference as is, without a wrapper object (Scala 3) |
| Combinators | zio-blocks-combinators | JVM · JS | 2.13 · 3.x | Compile-time composition and decomposition of tuples, eithers, and unions |
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| Async | zio-blocks-async | JVM · JS | 2.13 · 3.x | Zero-allocation asynchronous effect type with direct-style await |
| Mux | zio-blocks-mux | JVM · JS | 2.13 · 3.x | Thread-safe multiplexer for HTTP/2, QUIC, and WebSocket-style protocols |
| RingBuffer | zio-blocks-ringbuffer | JVM · JS | 2.13 · 3.x | Lock-free bounded ring buffers (SPSC, SPMC, MPSC, MPMC) |
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| Streams | zio-blocks-streams | JVM · JS | 2.13 · 3.x | Pull-based streaming with typed errors, zero boxing, and synchronous or asynchronous execution |
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| Telemetry | zio-blocks-telemetry | JVM · JS | 2.13 · 3.x | Zero-dependency OpenTelemetry-aligned tracing, logging, and metrics |
| OTLP Export | zio-blocks-telemetry-otel | JVM | 2.13 · 3.x | OTLP exporters bridging telemetry signals to an OpenTelemetry collector |
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| SQL Module | zio-blocks-sql | JVM · JS | 3.x | Type-safe JDBC wrapper with schema-derived codecs and a CRUD repository |
| ZIO Integration | zio-blocks-sql-zio | JVM | 3.x | ZIO integration with ZIO.attemptBlocking and ZLayer |
| Data Migration | zio-blocks-data-migration | JVM · JS | 3.x | Typed, online database schema migrations in three execution models, with no hand-written SQL |
| Projection | zio-blocks-projection | JVM | 3.x | Event-sourced projections with per-entity SQLite storage |
| Block | Artifact | Platform | Scala | Description |
|---|---|---|---|---|
| Code Generation | zio-blocks-codegen | JVM | 2.13 · 3.x | Generic Scala code generation IR and emitter |
| Docs | zio-blocks-markdown | JVM · JS | 2.13 · 3.x | GitHub Flavored Markdown parsing, rendering, and programmatic construction |
| Smithy | zio-blocks-smithy | JVM | 2.13 · 3.x | Smithy IDL parser and AST library for API modeling |
The Schema block brings dynamic-language productivity to statically-typed Scala. Define your data types once, and derive codecs, validators, optics, and more automatically.
In statically-typed languages, you often maintain separate codec implementations for each data format (JSON, Avro, Protobuf, etc.). Meanwhile, dynamic languages handle data effortlessly:
// JavaScript: one line and done
const data = await res.json();
In Scala, you'd typically need separate codecs for each format—a significant productivity gap.
ZIO Blocks Schema derives everything from a single schema definition:
case class Person(name: String, age: Int)
object Person {
implicit val schema: Schema[Person] = Schema.derived
}
// Derive codecs for any format:
val jsonCodec = Schema[Person].derive(JsonFormat) // JSON
val avroCodec = Schema[Person].derive(AvroFormat) // Avro
val toonCodec = Schema[Person].derive(ToonFormat) // TOON (LLM-optimized)
val msgpackCodec = Schema[Person].derive(MessagePackFormat) // MessagePack
val thriftCodec = Schema[Person].derive(ThriftFormat) // Thrift
libraryDependencies += "dev.zio" %% "zio-blocks-schema" % "0.0.56"
See the Meta Programming rows above for the optional format modules.
import zio.blocks.schema._
case class Address(street: String, city: String)
case class Person(name: String, age: Int, address: Address)
object Person extends CompanionOptics[Person] {
implicit val schema: Schema[Person] = Schema.derived
val name: Lens[Person, String] = $(_.name)
val age: Lens[Person, Int] = $(_.age)
val streetName: Lens[Person, String] = $(_.address.street)
}
val person = Person("Alice", 30, Address("123 Main St", "Springfield"))
val updated = Person.age.replace(person, 31)
Into, converts between versions with As, and renames a stored field with a compile-checked Migration.avsc schema for a sealed trait, streams Avro records, maps each Scala type to its Avro type, and reads the bytes with Apache AvroObjectId as the _id, chooses how sealed traits and options are stored, and inserts and queries tickets with the MongoDB Java driverReflect and Binding through optics, validation, and schema evolutionSchema, keeping field names, discriminators and custom formatsCompile-time verified resource safety for synchronous Scala code. Scope prevents resource leaks at compile time by tagging values with an unnameable type-level identity—values allocated in a scope can only be used within that scope. Child scope values cannot escape to parent scopes, enforced by both the abstract scope-tagged type and the Unscoped constraint on scoped.
Resource management in Scala is error-prone:
// Classic try/finally - verbose and easy to get wrong
val db = openDatabase()
try {
val tx = db.beginTransaction()
try {
doWork(tx)
tx.commit()
} finally tx.close() // What if commit() throws?
} finally db.close()
// Using - better, but doesn't prevent returning resources
Using(openDatabase()) { db =>
db // Oops! Returned the resource - use after close!
}
Scope makes resource leaks a compile error, not a runtime bug:
import zio.blocks.scope.*
Scope.global.scoped { scope =>
import scope.*
val db: $[Database] = allocate(Resource(openDatabase()))
// Methods are hidden - can't call db.query() directly
// Must use $ to access:
val result: String = $(db)(_.query("SELECT 1"))
// Trying to return `db` would be a compile error!
result // Only pure data (String) escapes
}
// db.close() called automatically
scope.$[A] are opaque and unique to each scope instance. Returning a scoped value from its scope is a type error.$[A] erases to A at runtime—zero allocation overhead.Resource.from[T](wires*) for automatic constructor-based DI.AutoCloseable have close() registered automatically.scoped method requires Unscoped[A] evidence on the return type, ensuring only pure data (not resources or closures) can escape.allocate, open(), and $ throw IllegalStateException with a detailed message explaining what went wrong, the common causes, and how to fix it—no silent null returns.libraryDependencies += "dev.zio" %% "zio-blocks-scope" % "0.0.56"
import zio.blocks.scope.*
final class Database extends AutoCloseable:
def query(sql: String): String = s"Result: $sql"
def close(): Unit = println("Database closed")
Scope.global.scoped { scope =>
import scope.*
// Allocate returns $[Database] (scoped value)
val db: $[Database] = allocate(Resource(new Database))
// Access via $ - result (String) escapes, db does not
val result: String = $(db)(_.query("SELECT * FROM users"))
println(result)
}
// Output: Result: SELECT * FROM users
// Database closed
Resource.from error message, with its cause and its fixScope, Resource, Wire, Unscoped, and finalization orderResource, ZLayer, macwire or Using code to Scope, Resource and WireAsync and streams from ZIO or cats-effect, with cancellation and cleanup carried acrossA lightweight, zero-dependency asynchronous effect type. A ready Async[A] is
an A, so synchronous code composed with map / flatMap allocates nothing on
the happy path while still suspending on genuinely asynchronous work.
Asynchronous Scala forces a choice between two costs. Future allocates for
every combinator and needs an ExecutionContext threaded everywhere, even when
the value is already available. Full effect systems avoid that but ask you to
adopt a runtime, a set of type classes, and a programming model across your
whole codebase—a heavy price for a library that only occasionally suspends.
Async[A] is a value, not a wrapper. When the result is already known, the
representation is the result, so composing ready values costs nothing:
import zio.blocks.async._
// Constructors collapse to bare values; transformers inline with no allocation
val computed: Int =
Async.succeed(20).map(_ + 1).flatMap(n => Async.succeed(n * 2)).block
// computed: Int = 42
Async[A] is represented as the A itself; map and flatMap over ready values allocate nothing.await: Async.async { ... } rewrites .await calls at compile time into a non-blocking flatMap chain—straight-line code, asynchronous execution.ExecutionContext to thread, no type class hierarchy, no effect system dependency.Future and CompletionStage, plus Async.promise for callback-based APIs.libraryDependencies += "dev.zio" %% "zio-blocks-async" % "0.0.56"
Write straight-line asynchronous code with Async.async and .await, rewritten
at compile time into a non-blocking flatMap chain:
import zio.blocks.async._
def fetch(id: Int): Async[String] = Async.succeed(s"item-$id")
val program: Async[Int] =
Async.async {
val a = fetch(1).await
val b = fetch(2).await
(a + b).length
}
zip, catchAll, collectAll, the Async.promise callback bridge, and Future / CompletionStage interopAsync from ZIO or cats-effect, with cancellation carried acrossasync-examples — a single-file order-fulfillment demo (cd async-examples && sbt run)A thin, type-safe JDBC wrapper that maps Scala case classes to database tables using the same Schema you use for JSON and Avro codecs. No ORM runtime, no code generation — just composable SQL fragments, a derived repository abstraction, and a direct ZIO integration.
JDBC is powerful but tedious: manual ResultSet traversal, index-based parameter binding, and repetitive CRUD boilerplate make even simple database access error-prone. ORMs solve the boilerplate but add heavy runtimes, hidden queries, and opaque magic.
ZIO Blocks SQL derives everything from a single Schema[A]:
case class User(id: Long, name: String, email: String)
object User:
given Schema[User] = Schema.derived
// Derive the table, codec, and repository in one line
val repo = Repo.derived[User, Long]
// Use the sql"..." interpolator for custom queries
val frag = sql"SELECT * FROM user WHERE email = ${"[email protected]"}"
DbCodec[A] is auto-derived from Schema[A] — column names, types, and nullability come for free.sql"..." interpolator creates Frag values that compose safely with ++. SQL injection is structurally impossible.Repo[E, ID] provides all, find, findAll, insert, insertAll, update, delete, deleteAll, and clear out of the box.Table.createTable(dialect) generates type-accurate CREATE TABLE IF NOT EXISTS SQL from the schema.TransactorZIO lifts blocking JDBC calls into Task (or ZIO) with proper bracketing and rollback.zio-blocks-sql module has no ZIO dependency — use it with any effect system or plain Scala.libraryDependencies += "dev.zio" %% "zio-blocks-sql" % "0.0.56"
// Optional ZIO integration
libraryDependencies += "dev.zio" %% "zio-blocks-sql-zio" % "0.0.56"
import zio.blocks.schema._
import zio.blocks.sql._
import zio.blocks.sql.zio._
case class Product(id: Long, name: String, price: Double)
object Product:
given Schema[Product] = Schema.derived
given DbCodec[Product] = summon[Schema[Product]].deriving(DbCodecDeriver).derive
val repo = Repo.derived[Product, Long]
val transactor = TransactorZIO.fromUrl("jdbc:postgresql://localhost/shop", SqlDialect.PostgreSQL)
// Batch insert, then query with a custom filter
val program = transactor.transact:
repo.insertAll(List(
Product(1L, "Widget", 9.99),
Product(2L, "Gadget", 29.99)
))
sql"SELECT * FROM product WHERE price < ${15.0}".query[Product]
DbCodec, Frag, Table, Repo, Transactor, dialects, and DDL generationZIO Blocks works with any Scala stack:
| Stack | Compatible |
|---|---|
| ZIO 2.x | ✅ |
| Cats Effect 3.x | ✅ |
| Kyo | ✅ |
| Ox | ✅ |
| Akka | ✅ |
| Plain Scala | ✅ |
Each block has zero dependencies on effect systems. Use the blocks directly, or integrate them with your effect system of choice.
Schema, then encode, decode, and read errorsStream, parse, filter and batch it, sum it with a Sink, and recover from a bad lineRepo from one schema, write your own queries, and roll back a transactionThese six follow the learning path, from installing the library to a small working backend. The guides index on the website lists every tutorial, how-to guide, migration guide and deep dive.
Every block in the catalog above links to its own reference page. The blocks large enough to have several pages start from an overview:
Projection[A], ProjectionEngine, and per-entity SQLite storesScope, Resource, Wire, Unscoped, and finalizationStream, Pipeline, Sink, and the low-level readers and writersLearn more on the ZIO Blocks homepage!
For the general guidelines, see ZIO contributor's guide.
See the Code of Conduct
| XML Codec | zio-blocks-schema-xml | JVM · JS | 2.13 · 3.x | Zero-dependency XML serialization with fluent navigation and patching |
| YAML Codec | zio-blocks-schema-yaml | JVM · JS | 2.13 · 3.x | Human-readable YAML serialization with JSON interop |
| TypeId | zio-blocks-typeid | JVM · JS | 2.13 · 3.x | Compile-time type identity with rich metadata |
zio-blocks-datastar |
| JVM · JS |
| 3.x |
| Typed Datastar attribute and signal DSL, plus the SSE events that patch a live page |
| HTMX | zio-blocks-http-htmx | JVM · JS | 3.x | Typed HTMX DSL for compile-time-checked HTMX attributes |