Skip to content

Internal

Implementation details explicitly marked Internal by their source. They remain available to browse here, but are not intended as entry points for code written in a Field box.

27 source file(s), 229 public symbol(s), 97 of them carrying KDoc. Everything below is the documentation that lives beside the code — the same text the completion documentation panel shows in the editor. A blank summary means the declaration has no KDoc yet, not that this page dropped it.

extensions.kt

Box actions: named commands a box registers in its actions map, which resync gathers from the box and its ancestors and sends to the UI.

An Action carries a short description, a detail line, optional HTML or JavaScript documentation, and a target callback that receives the boxes it was invoked on. action builds one with the callback as a trailing lambda.

src/jvmMain/kotlin/afield/app/commands/extensions.kt — read the source

Top-level functions

Declaration Summary
fun action(desc : String = "", detail: String, docHtml: String = "", docJs: String = "", payload : (List<Box>) -> Unit) Builds an Action with payload as its target.

Top-level values

Declaration Summary
val Box.actions: MutableMap<String, Action> This box's actions by key; reading it marks the box for resync so the UI picks up changes.

Action

data class Action(val desc: String, val detail: String, val docHtml: String = "", val docJs: String = "", val target: (List<Box>) -> Unit = {})

A named command shown for a box; target runs with the boxes it was invoked on.

Declaration Summary
val desc: String
val detail: String
val docHtml: String
val docJs: String
val target: (List<Box>) -> Unit

FieldBrowserHosts.kt

src/jvmMain/kotlin/afield/app/server/FieldBrowserHosts.kt — read the source

CudaInteropProof.kt

The proof that CudaDriver and Field's Vulkan renderer share memory on the same GPU with no copies, and the measurements behind dev_docs/graphics/CUDA_DRIVER_FFM.md.

Two proofs, each checked by reading the memory back from both sides:

  1. Native OIDN on CUDA, in place. A 1080p path trace accumulates with its accumulation buffer allocated exportable, and Field's own OIDN port accumulates its albedo and normal guides the same way. Native Open Image Denoise opens the CUDA device with the Vulkan device's UUID, imports those three buffers and an output buffer as fds, and denoises under a shared timeline semaphore: Vulkan signals, OIDN waits, filters and signals, Vulkan waits. The output is read back through Vulkan and through OIDN (they must agree bit for bit) and compared with Field's Vulkan port of the same network on the same inputs.
  2. A CUDA kernel writing a buffer Field displays. A PTX kernel shipped as text (and, when Nvrtc is found, a CUDA C kernel compiled at runtime) fills an exported Vulkan buffer; Field's path tracer then resolves its output texture from that buffer, and the texture is read back and compared with the values the kernel must have written.

Arguments: [--oidn <dir holding libOpenImageDenoise.so>] [--out <dir>] [--spp N]. Without CUDA (macOS, no NVIDIA driver, FIELD_CUDA_DISABLE=1) it prints the reason and exits 0; without OIDN it runs proof 2 alone.

src/jvmMain/kotlin/afield/cuda/CudaInteropProof.kt — read the source

CudaInteropProof

object CudaInteropProof

The proof that CudaDriver and Field's Vulkan renderer share memory on the same GPU with no copies, and the measurements behind dev_docs/graphics/CUDA_DRIVER_FFM.md.

Declaration Summary
val FILL_PTX field_fill(float4* out, uint width, uint height, float t): out[y*width+x] = (x/width, y/height, t, 1). Hand-written PTX, JIT-compiled by the driver.
val RINGS_CU The NVRTC kernel: a radial pattern, with FMA contraction off so the CPU can predict every bit.
fun main(args: Array<String>)

binding.kt

Binds a property or one-argument function to a source of values with the < operator: ::speed < { mouseX } or ::speed < sequenceOf(1.0, 2.0, 3.0).

The callable reference must be bound to a receiver implementing BoundContext; the binding is stored there under the callable's name, replacing any earlier one. Each BoundContext.bindNow pulls the next value from every source, type-checks it against the property or parameter type, and applies it only when it differs from the last value applied. A sequence that runs out removes its binding; clear() on the reference removes it by hand.

Nothing in src/ implements BoundContext or calls bindNow yet, so this is the mechanism without a host.

src/jvmMain/kotlin/afield/document/properties/binding.kt — read the source

Top-level functions

Declaration Summary
fun boundReceiverForCallable(k: Any): Any? Binds a property or one-argument function to a source of values with the < operator: ::speed < { mouseX } or ::speed < sequenceOf(1.0, 2.0, 3.0).
operator fun <A, B> KFunction1<A, B>.compareTo(other: Sequence<A>): Int+1 overload · also () -> A
operator fun <T> KMutableProperty0<T>.compareTo(other: Sequence<T>): Int+1 overload · also () -> T
fun KFunction1<*, *>.clear(): Boolean
fun KMutableProperty0<*>.clear(): Boolean

BoundContext

interface BoundContext

Declaration Summary
val bindings: MutableMap<String, BoundBinding>
val previousValues: MutableMap<String, Any?>
fun bindNow()
fun clearBinding(name: String): Boolean

BoundNext

sealed interface BoundNext

Declaration Summary
data class Value(val value: Any?) : BoundNext
object Done : BoundNext

BoundSource

sealed interface BoundSource

Declaration Summary
fun next(): BoundNext

FunctionSource

class FunctionSource(private val fn: () -> Any?) : BoundSource

Declaration Summary
override fun next(): BoundNext

SequenceSource

class SequenceSource(private val iterator: Iterator<Any?>) : BoundSource

Declaration Summary
override fun next(): BoundNext

BoundBinding

data class BoundBinding(val source: BoundSource, val check: (Any?) -> Any?, val apply: (Any?) -> Unit)

Declaration Summary
val source: BoundSource
val check: (Any?) -> Any?
val apply: (Any?) -> Unit

CollectionLiteralCompileAudit.kt

src/jvmMain/kotlin/afield/examples/CollectionLiteralCompileAudit.kt — read the source

CollectionLiteralCompileAudit

object CollectionLiteralCompileAudit

Compile the exact source bodies selected by tools/audit_collection_literals.py, without evaluating their bodies. Complete programs pass; a fragment needing other declarations retains its compiler diagnostics for review. This report never treats missing context as a pass.

Declaration Summary
fun main(args: Array<String>)

ManifoldNative.kt

The FFM binding to libmanifoldc that Solid and Section are built on, plus the small public enums they take.

Box code needs only ManifoldLibrary, to ask whether the native library is installed, and the option enums BooleanOp, JoinType and FillRule; the native entry points themselves are internal.

src/jvmMain/kotlin/afield/geometry/solid/manifold/ManifoldNative.kt — read the source

Used in: Solids that cannot fail: Manifold in Field

ManifoldLibrary

object ManifoldLibrary

Where libmanifoldc is, and what to do when it is not there.

Declaration Summary
val fileName: String libmanifoldc.dylib / .so / manifoldc.dll, chosen for the platform actually running.
val searchedPaths: List<Path> Every path resolvedPath tries, in order — quoted in the "not installed" error.
val resolvedPath: Path? The first path that exists, or null.
val isAvailable: Boolean true when Solid and Section will work. Cheap enough to branch on in a box.
val reportedVersion: String? The upstream version, read off the .dylib/.so filename that the SO-versioned symlink points at — libmanifoldc.3.5.2.dylib reports 3.5.2.
val HOW_TO_INSTALL: String What to tell someone who has not got it, in the package manager they are likely to have.
fun describe(): String One line for a box or a smoke test to print: what was found, or why not.

ManifoldStatus

enum class ManifoldStatus(val code: Int)

ManifoldError, the status a Solid carries when an operation could not produce a valid solid.

Constants: NO_ERROR, NON_FINITE_VERTEX, NOT_MANIFOLD, VERTEX_INDEX_OUT_OF_BOUNDS, PROPERTIES_WRONG_LENGTH, MISSING_POSITION_PROPERTIES, MERGE_VECTORS_DIFFERENT_LENGTHS, MERGE_INDEX_OUT_OF_BOUNDS, TRANSFORM_WRONG_LENGTH, RUN_INDEX_WRONG_LENGTH, FACE_ID_WRONG_LENGTH, INVALID_CONSTRUCTION, RESULT_TOO_LARGE, INVALID_TANGENTS, CANCELLED.

Declaration Summary
val isError: Boolean true for everything except NO_ERROR.
fun of(code: Int): ManifoldStatus The enum for a raw ManifoldError, or INVALID_CONSTRUCTION for a code from a newer Manifold.

BooleanOp

enum class BooleanOp(internal val code: Int)

ManifoldOpType, the operation Solid.batchBoolean and Section.batchBoolean apply.

Constants: UNION, DIFFERENCE, INTERSECTION.

JoinType

enum class JoinType(internal val code: Int)

ManifoldJoinType — how Section.offset treats a convex corner.

Constants: SQUARE, ROUND, MITER, BEVEL.

FillRule

enum class FillRule(internal val code: Int)

ManifoldFillRule — how a set of contours decides what is inside, when they overlap or nest.

Constants: EVEN_ODD, NON_ZERO, POSITIVE, NEGATIVE.

RayHit

data class RayHit(val faceId: Long, val distance: Double, val x: Double, val y: Double, val z: Double, val normalX: Double, val normalY: Double, val normalZ: Double)

One intersection from Solid.raycast.

Declaration Summary
val faceId: Long Which triangle of the solid was hit, as Manifold's face id.
val distance: Double Distance from the ray origin, in the units the solid is in.
val x: Double
val y: Double
val z: Double
val normalX: Double
val normalY: Double
val normalZ: Double

GestureReplayMain.kt

A command-line entry point that replays a recorded pen gesture through a brush and writes the painted PNG, so an agent can try a gesture without a browser.

GestureReplayMain reads a GestureReplayRequest (raw samples, or keyframe lanes in GestureReplayLanes) and prints a GestureReplayReport as JSON.

src/jvmMain/kotlin/afield/graphics/paint/GestureReplayMain.kt — read the source

GestureReplayMain

object GestureReplayMain

The gesture -> brush replay for an agent, without a browser: a take (or its keyframe lanes) in a JSON file, a painted PNG out. field_backdoor.py --command 'run-jvm-main afield.graphics.paint.GestureReplayMain --arg <request.json>', or the MCP tool field_paint_gesture.

Declaration Summary
fun main(args: Array<String>)
fun run(req: GestureReplayRequest): GestureReplayReport

GestureReplayRequest

data class GestureReplayRequest(val out: String, val samples: List<List<Double>> = emptyList(), val lanes: GestureReplayLanes? = null, val bake: Double? = null, val lanesOut: String? = null, val xRange: List<Double> = listOf(-1.0, 1.0), val yRange: List<Double> = listOf(-1.0, 1.0), val into: List<Double>? = null, val widthPx: Int = 800, val aspect: Double = 1.0, val sizeMm: Double = 200.0, val seed: Long = 1, val brush: String = "Round", val brushWidth: Double = 50.0, val dynamic: Boolean = true, val color: List<Double> = listOf(0.25, 0.15, 0.1), val pressure: Double = 0.6, val pressureScale: Double = 1.2, val tilt: Double = 30.0, val timeScale: Double = 1.0)

What GestureReplayMain reads. Ranges and into as in PaintCanvas.gesture; into is [x, y, w, h].

Declaration Summary
val out: String
val samples: List<List<Double>>
val lanes: GestureReplayLanes?
val bake: Double?
val lanesOut: String?
val xRange: List<Double>
val yRange: List<Double>
val into: List<Double>?
val widthPx: Int
val aspect: Double
val sizeMm: Double
val seed: Long
val brush: String
val brushWidth: Double
val dynamic: Boolean
val color: List<Double>
val pressure: Double
val pressureScale: Double
val tilt: Double
val timeScale: Double

GestureReplayLanes

data class GestureReplayLanes(val x: List<Keyframe>, val y: List<Keyframe>, val pressure: List<Keyframe>? = null, val tiltX: List<Keyframe>? = null, val tiltY: List<Keyframe>? = null, val twist: List<Keyframe>? = null)

Keyframe lanes as the keyframe editor stores them.

Declaration Summary
val x: List<Keyframe>, val y: List<Keyframe>
val pressure: List<Keyframe>?

GestureReplayReport

data class GestureReplayReport(val ok: Boolean, val error: String? = null, val out: String? = null, val samples: Int = 0, val seconds: Double = 0.0, val fromLanes: Boolean = false, val keys: Int? = null, val fit: String? = null, val brush: String? = null, val pressure: List<Double> = emptyList(), val tilt: List<Double> = emptyList())

What GestureReplayMain prints.

Declaration Summary
val ok: Boolean
val error: String?
val out: String?
val samples: Int
val seconds: Double
val fromLanes: Boolean
val keys: Int?
val fit: String?
val brush: String?
val pressure: List<Double>
val tilt: List<Double>

PaintNative.kt

The bindings to the native field-paint library: PaintLibrary finds the library file, and the internal FFM layer under PaintCanvas calls into it.

src/jvmMain/kotlin/afield/graphics/paint/PaintNative.kt — read the source

PaintLibrary

object PaintLibrary

Where native/field-paint is. Searched in order: -Dafield.paint.library, AFIELD_PAINT_LIBRARY, then build/field-paint/release in the working directory.

Declaration Summary
val fileName: String
val searchedPaths: List<Path>
val resolvedPath: Path? Not cached: building it during a live session is picked up by the next box run.
val isAvailable: Boolean
const val HOW_TO_BUILD
fun describe(): String

OpenDlssNrDiagnostics.kt

src/jvmMain/kotlin/afield/graphics/render/neural/OpenDlssNrDiagnostics.kt — read the source

OpenDlssNrNative.kt

src/jvmMain/kotlin/afield/graphics/render/neural/OpenDlssNrNative.kt — read the source

OpenDlssNrTemporalSmoke.kt

src/jvmMain/kotlin/afield/graphics/render/neural/OpenDlssNrTemporalSmoke.kt — read the source

SyphonNative.kt

The locator and foreign-function bindings for native/field-syphon, the optional macOS library under SyphonServer and SyphonClient.

The library is searched for in order: the afield.syphon.library system property, the AFIELD_SYPHON_LIBRARY environment variable, then build/field-syphon in the working directory.

src/jvmMain/kotlin/afield/io/syphon/SyphonNative.kt — read the source

SyphonLibrary

object SyphonLibrary

Locates libfield_syphon.dylib and reports whether it is available.

Declaration Summary
val isMac: Boolean
const val fileName
val searchedPaths: List<Path>
val resolvedPath: Path? Not cached: building it during a live session is picked up by the next box run.
val isAvailable: Boolean
val probePath: Path? The cross-process test peer built next to the library (field_syphon_probe).
const val HOW_TO_BUILD
fun describe(): String

FfmCeresBackend.kt

The Ceres solver backend that calls the native ken_ceres_jvm wrapper through the Java foreign-function API (java.lang.foreign), with no JNI glue.

FfmCeresBackend loads the library, binds its ken_ceres_* entry points as downcall handles and reports FfmCeresBackend.abiVersion; FfmCeresBackend.compile turns a seed PointCloud and a CeresProgram into a reusable compiled solver whose input, output and prior buffers are allocated once in a shared arena and reused across solves. CeresNativeLibrary says where the library is expected and how to build it.

src/jvmMain/kotlin/afield/math/optimization/ceres/FfmCeresBackend.kt — read the source

FfmCeresBackend

class FfmCeresBackend(libraryPath: Path = CeresNativeLibrary.defaultPath, private val reusableMetricCapacity: Int = 128) : CeresSolverBackend

A CeresSolverBackend backed by the native library at libraryPath, by default CeresNativeLibrary.defaultPath. Construction fails with UnsatisfiedLinkError when an expected symbol is missing, and with IllegalArgumentException when the library reports an ABI version other than the one Field needs.

Declaration Summary
val abiVersion: String The ken_ceres_jvm_abi_v* string the loaded library reports.
override fun compile(seedPoints: PointCloud, program: CeresProgram): CompiledCeresSolver

CeresNativeLibrary

object CeresNativeLibrary

Where to find the native wrapper.

Declaration Summary
val defaultPath: Path
val HOW_TO_BUILD: String What to tell someone whose defaultPath is not there, in the shell they are actually in.

PairedHeadsetInput.kt

src/jvmMain/kotlin/afield/media/browser/PairedHeadsetInput.kt — read the source

WiVRnEvdev.kt

src/jvmMain/kotlin/afield/media/browser/WiVRnEvdev.kt — read the source

WiVRnKeyboardMap.kt

src/jvmMain/kotlin/afield/media/browser/WiVRnKeyboardMap.kt — read the source

NgxNative.kt

src/jvmMain/kotlin/afield/media/reconstruction/NgxNative.kt — read the source

OidnCompute.kt

src/jvmMain/kotlin/afield/media/reconstruction/OidnCompute.kt — read the source

Used in: Progressive path tracing

OidnSource

interface OidnSource

What OidnComputeDenoiser reads: a linear-radiance image, one vec4 per pixel, and how to tell when it changes. PathTraceOidnSource wraps a path tracer; OidnImageSource holds any other image (a raster render, a texture, a file).

Declaration Summary
val renderer: Renderer
val width: Int
val height: Int
val name: String Names the denoiser's render-list slot ("<name>-denoise").
val radiance: VulkanBuffer Linear radiance, row-major vec4 per pixel, a storage buffer with a device address.
val samples: Int Samples averaged into radiance; zero while it holds nothing. An image reports 1 once it has one.
val samplesPerFrame: Int Samples added per frame, for averaging guides at the same rate.
val generation: Long Changes whenever radiance starts over; a denoised snapshot is current while this is unchanged.
val isClosed: Boolean
val guideFrames: VulkanBuffer? Per-pixel frame records in the PathTraceFrameOutput layout, from which the denoiser averages albedo and normal as samples arrive; null when the guides are set with OidnComputeDenoiser.setGuides instead.
fun showDenoised(denoised: VulkanBuffer?) Show denoised wherever the source's own image is shown, or the source's image again when null.

PathTraceOidnSource

class PathTraceOidnSource(val tracer: PathTracingRenderer) : OidnSource

A PathTracingRenderer as an OidnSource. Turns on the tracer's frame output, which resets accumulation once.

Declaration Summary
val frame: PathTraceFrameOutput
override val renderer: Renderer
override fun showDenoised(denoised: VulkanBuffer?)

OidnImageSource

class OidnImageSource(override val renderer: Renderer, override val width: Int, override val height: Int, override val name: String = "oidn-image") : OidnSource, AutoCloseable

Any image as an OidnSource: a device buffer you fill with upload from linear pixels, an sRGB BufferedImage, or a RenderToTexture (a raster render, a particle target). Each upload starts a new generation, so an installed denoiser runs once per upload; OidnComputeDenoiser.denoiseImage runs it now and returns the pixels.

Declaration Summary
override val name: String
override val radiance
override var samples
override var generation
override var isClosed
fun upload(linear: FloatArray): OidnImageSource Linear RGBA, row-major, width x height x 4.
fun upload(image: BufferedImage): OidnImageSource An 8-bit sRGB image of this size, decoded to linear.
fun upload(texture: RenderToTexture): OidnImageSource The current contents of texture (a float or half RGBA target of this size), read back and uploaded.
override fun close()
fun linearPixels(image: BufferedImage): FloatArray Decode an 8-bit sRGB image to linear RGBA floats, alpha 1.

OidnComputeDenoiser

class OidnComputeDenoiser(val source: OidnSource, weights: Path? = null, val name: String = "${source.name}-denoise", val exportGuides: Boolean = false) : Target, AutoCloseable

Denoises an OidnSource on the GPU with Open Image Denoise's network: a PathTracingRenderer's accumulated image, or any other image through OidnImageSource.

Declaration Summary
val exportGuides: Boolean Allocate albedo and normal exportable as opaque fds, for a CUDA consumer such as native OIDN (Linux).
val tracer: PathTracingRenderer? The tracer behind source, or null for an image.
val renderer: Renderer
val width
val height
var activationBytes: Long Device bytes held by the fp16 activations.
val albedo
val normal
val denoised
val scale
val cooperativeMatrix: Boolean Run the convolutions as cooperative-matrix multiplies (16x16x16 fp16 in, fp32 accumulate; tensor cores on NVIDIA) when the device has VK_KHR_cooperative_matrix. Otherwise, and with afield.oidn.portable=true (or AFIELD_OIDN_PORTABLE=1), the portable kernels run. Both give the same image to within fp16 rounding.
fun setGuides(albedo: FloatArray?, normal: FloatArray?) Guides for a source without OidnSource.guideFrames: linear albedo in [0, 1] and unit normals, RGBA per pixel like the colour. Null is flat: albedo 1 (nothing marks detail as texture) or normal +z.
val output Display texture: the denoised buffer copied into an RTT the same way PathTraceFrameOutput fills its images.
var accumulateGuides Average albedo and normal as samples arrive. Turning it off leaves the guides of the last run in place.
var denoiseAt Denoise once per accumulation run when the source reaches this many samples (64 for a tracer, 1 for an image: once per upload); zero waits for request.
var show Show the current denoised snapshot in the tracer's output (an image source shows it only in output).
fun request(n: Int = 1) Denoise on each of the next n frames. One is a still; more are for timing.
var pending
var denoiseCount How many times the network has run.
var denoisedSamples The source's sample count at the last denoise, or -1.
fun install(): OidnComputeDenoiser Schedule on the render list after the tracer. Reusing name retires the previous denoiser.
fun denoiseNow(perPass: Boolean = false): List<Pair<String, Double>> Timing only: record the network into its own command buffer, submit, and wait on a fence. KosmicKrisp's timestamps do not separate dispatches inside one encoder, so wall time around a fence is the measurement. perPass submits each pass alone (each figure then includes one submit+wait; see emptySubmitMs).
fun emptySubmitMs()
fun denoiseImage(): FloatArray Denoise the source's current image now and return it (linear RGBA, width x height). Each pass is its own fenced submit, so no command buffer nears the Metal watchdog at 4K. Blocking: call it from a box or a main, not from inside a frame.
var lastDenoiseMs Wall time of the last denoiseImage, summed over its passes, in milliseconds.
override fun render(command: CommandBuffer, index: Int)
fun read(source: VulkanBuffer): FloatArray Blocking diagnostic readback of one of this denoiser's buffers.
override fun close()
const val DEFAULT_WEIGHTS OIDN's rt_hdr_alb_nrm weights (Apache-2.0), as vendored with oidn-webgpu 0.6.0.

OidnComputeSpike.kt

src/jvmMain/kotlin/afield/media/reconstruction/OidnComputeSpike.kt — read the source

OidnComputeSpike

object OidnComputeSpike

Measurement harness for OidnComputeDenoiser: path-traces a 1080p scene, denoises it on the GPU at 8/32/128 samples, times the network with fenced submits, and compares it with native OIDN (CPU, through Oidn) on the same inputs. Arguments: <oidn lib dir> <weights .tza | default> <out dir> [--timing-only]. Results: OIDN_COMPUTE_PORT.md.

Declaration Summary
class Capture(val color: FloatArray,val albedo: FloatArray,val normal: FloatArray,val vulkan: FloatArray,val texture: FloatArray,val scale: Float)
fun main(args: Array<String>)

OidnImageSourceSmoke.kt

src/jvmMain/kotlin/afield/media/reconstruction/OidnImageSourceSmoke.kt — read the source

OidnImageSourceSmoke

object OidnImageSourceSmoke

OidnComputeDenoiser on an OidnImageSource, with no path tracer: a soft disc kept per pixel with probability equal to its opacity (stochastic transparency, one sample a pixel) must come back closer to the smooth disc than the noisy input was, both through OidnComputeDenoiser.denoiseImage and, installed, once per upload.

Declaration Summary
fun main(args: Array<String>)

OidnImageSpike.kt

src/jvmMain/kotlin/afield/media/reconstruction/OidnImageSpike.kt — read the source

OidnImageSpike

object OidnImageSpike

Study: OidnComputeDenoiser on images that are not path traced (sRGB screenshots), through OidnImageSource, and whether it keeps a wrapping (tileable) image wrapping. Each image is denoised with one of two guide sets: - flat: albedo 1, normal +z — the network has nothing that marks detail as real; - self: the image itself as albedo, normal +z. Tiling: an image treated as a torus should denoise the same whether or not it is rolled first. Each image is denoised as is and rolled by half its size (the rolled result rolled back is the wrap-aware answer at the original edges), both plain and with a PAD-pixel wrap-around pad cropped off afterwards. Arguments: <out dir> <image>... [--save-images]. Results: dev_docs/lighting/OIDN_ON_PARTICLE_IMAGES.md.

Declaration Summary
fun main(args: Array<String>)

OidnSpike.kt

src/jvmMain/kotlin/afield/media/reconstruction/OidnSpike.kt — read the source

OidnSpike

object OidnSpike

The first spike: native OIDN on CPU and Metal against readback of the path tracer. Results: OIDN_SPIKE.md.

Declaration Summary
fun main(args: Array<String>)

ReconstructionCapture.kt

src/jvmMain/kotlin/afield/media/reconstruction/ReconstructionCapture.kt — read the source

actors.kt

Typed messages between boxes: a box registers a handler with onMessage, and other code delivers to it with send (fire-and-forget) or sendAndAwait (suspend for a reply).

Messages are queued per box and delivered on the next RunLoop frame. Handlers run as coroutines on the RunLoop's dispatcher, so one can call MessageScope.frame to wait a frame or MessageScope.reply to answer. A box with no handler for a payload type passes it to its ancestors. go launches a suspendable block owned by a box, so stopping the box cancels it and its errors appear in the box's editor.

onMessage<String> { reply(payload.length) }
go { println(thisBox.sendAndAwait<String, Int>("hello")) }

src/jvmMain/kotlin/afield/runtime/execution/actors.kt — read the source

Used in: A Terminal in a Box

Top-level functions

Declaration Summary
inline fun <reified T : Any> Box.onMessage(noinline handler: suspend MessageScope<T>.() -> Unit) Register a typed, suspendable message handler on this box.
fun <T : Any> Box.onMessage(type: KClass<T>, handler: suspend MessageScope<T>.() -> Unit)
fun <T : Any> Box.send(payload: T) Enqueue payload for delivery to this box on the next RunLoop frame. The sender is inferred from Box.context (may be null if called outside a box execution context).
fun Box.go(block: suspend CoroutineScope.() -> Unit) Launch a suspendable block on the RunLoop's Framer dispatcher, owned by this box. Stopping the box cancels the block; uncaught errors appear in the editor.
suspend fun delay(ms: Number) Wait ms milliseconds inside go { } (or any coroutine) without holding the runloop.
suspend fun <T : Any, R> Box.sendAndAwait(payload: T): SendResult<R> Send payload and suspend until the handler finishes (or is not found).

Envelope

data class Envelope<T : Any>(val payload: T, val from: Box?, val to: Box, val time: Long = System.currentTimeMillis())

Envelope wrapping a user payload with sender/receiver metadata.

Declaration Summary
val payload: T
val from: Box?
val to: Box
val time: Long

MessageScope

class MessageScope<T : Any>(val envelope: Envelope<T>, private val deferred: CompletableDeferred<Any?>?, internal val handlerBox: Box?)

Receiver for suspend message handlers. Provides frame to suspend until the next RunLoop tick and reply to send a value back to a waiting sendAndAwait caller.

Declaration Summary
val payload: T
val from: Box?
val to: Box
val time: Long
suspend fun frame() Suspend until the next RunLoop frame. Because the handler coroutine is dispatched on Runloop.runLoop.main (the afield.runtime.lifecycle.Framer), calling kotlinx.coroutines.yield parks it until the Framer is pumped again.
fun reply(value: Any?) Provide a return value to a sendAndAwait caller. If the message was sent with plain send, this is a no-op. Can be called at most once; subsequent calls are ignored.

SendResult

sealed class SendResult<out T>

Declaration Summary
data class Ok<T>(val value: T?) : SendResult<T>() Handler ran to completion. value is whatever MessageScope.reply provided (null if reply was never called).
data object NoHandler : SendResult<Nothing>() No handler was found for this message type on the target box or any of its ancestors.
data class Error(val exception: Throwable) : SendResult<Nothing>() The handler threw an exception.
inline fun <R> map(transform: (T?) -> R): SendResult<R> Transform the value if Ok, otherwise pass through the failure unchanged.
fun getOrNull(): T? Return the value if Ok, otherwise null.
inline fun getOrElse(default: () -> @UnsafeVariance T?): T? Return the value if Ok, otherwise default.
inline fun onOk(action: (T?) -> Unit): SendResult<T> Run action if Ok, return this for chaining.
inline fun onFailure(action: (SendResult<@UnsafeVariance T>) -> Unit): SendResult<T> Run action if not Ok, return this for chaining.

scratch.kt

src/jvmMain/kotlin/afield/runtime/lifecycle/scratch.kt — read the source

Used in: Running code in a box, Why does this value resolve here?

Top-level values

Declaration Summary
val Box.once

Once

class Once(val inside : Box)

Property-delegate namespace bound to one Box; normally reached as box.once.

Onceing

class Onceing<T>()

Returns a lazy initializer for the generated property named by property.

Declaration Summary
operator fun getValue(f: Once, property: KProperty<*>): (() -> T) -> T

SourceBackedBlock.kt

A callable block that keeps the Kotlin source it was written as, and can be rebuilt from that source after it has been saved.

The sourceBlock macro makes a SourceBackedBlock holding both a live lambda and its source. A block restored from storage has only the source and rebuilds itself by evaluating it on its box's engine. Doing that while the same box's code is running would run that code again, so it is refused with SourceBackedBlockSelfBoxReentry or SourceBackedBlockDuringOwnBody, each of whose messages says where to invoke the block instead.

src/jvmMain/kotlin/afield/study/source/SourceBackedBlock.kt — read the source

Top-level functions

Declaration Summary
fun <T> sourceBackedBlock(boxId: String, source: String): SourceBackedBlock<T>
fun sourceBackedBlockBox(boxId: String): Box?

SourceBackedBlockSelfBoxReentry

class SourceBackedBlockSelfBoxReentry(box: Box, source: String) : IllegalStateException("This source-backed block is evaluating its stored source in box '${box.name}' (${box.id}) — the " + "box that is running it, whose body it therefore re-runs, once per invocation, until the stack " + "overflows. Source: '${source.take(80).replace('\n', ' ')}'. " + "Invoke it somewhere that is not this box's own body: " + "(1) from another box — construct it with that box's id, `SourceBackedBlock<Any?>(\"other_box\", source)`, " + "and invoke it there, which is the split `dev_docs/agents/transcripts/keyframe_code_blend.yaml` uses; " + "(2) from a frame loop or a control callback, after this body has finished; or " + "(3) not at all — a block the `sourceBlock { }` macro made in *this* execution carries a live " + "lambda, never hydrates, and is safe to call immediately. " + "See dev_docs/FN_REWRITE_SELF_BOX_REENTRY.md.")

Thrown when a rehydrating SourceBackedBlock would be evaluated in a box whose body is already running — the failure that was 327 nested body runs and 355 seconds before it was guarded.

SourceBackedBlockDuringOwnBody

class SourceBackedBlockDuringOwnBody(box: Box, source: String) : IllegalStateException("This saved block (source '${source.take(80).replace('\n', ' ')}') belongs to box '${box.name}', whose " + "code is running now, and hydrating it there would run that code again. Invoke it from a frame loop " + "or a control callback, after the box's code has finished, or from another box.")

A saved expression asked to hydrate on its own box's engine while that box's body is running. Evaluating it there would run the body again, so it is an error, raised before anything runs twice. A SourceBackedBlock no longer raises it (it hydrates on a side engine instead); the @{...} route of rewriteKotlin still does.

SourceBackedBlock

class SourceBackedBlock<out T>(val boxId: String, val source: String, private val block: (() -> T)? = null) : () -> T

A callable block that keeps the Kotlin source used to create it.

Declaration Summary
val boxId: String
val source: String
override fun invoke(): T
override fun toString(): String

PrettyStrings.kt

src/jvmMain/kotlin/afield/ui/output/PrettyStrings.kt — read the source