type Canceler = () => void; type CancelToken = { /** true si ya fue cancelado */ readonly isCancelled: () => boolean; /** * Registra un callback que se ejecuta cuando se cancela. * Si ya estaba cancelado, lo ejecuta inmediatamente. * Devuelve un "unsubscribe" para desregistrar. */ readonly onCancel: (f: Canceler) => Canceler; }; /** Implementación simple de CancelToken */ declare function makeCancelToken(): CancelToken & { cancel: Canceler; }; /** * Helper: conecta un AbortController a un CancelToken. * Devuelve una función para desenganchar (unsubscribe). */ declare function linkAbortController(token: CancelToken, ac: AbortController): Canceler; type RuntimeCapabilities = { wasmAvailable: boolean; wasmFiberEngine: boolean; wasmRingBuffer: boolean; wasmScheduler: boolean; wasmFiberRegistry: boolean; wasmFiberReadyQueue: boolean; wasmBinaryAbi: boolean; wasmStreamChunks: boolean; }; declare function runtimeCapabilities(): RuntimeCapabilities; declare const enum PushStatus { Ok = 0, Grew = 1, Dropped = 2 } declare class RingBuffer { private buf; private head; private tail; private size_; private readonly maxCap; constructor(initialCapacity?: number, maxCapacity?: number); get length(): number; get capacity(): number; isEmpty(): boolean; push(value: T): PushStatus; shift(): T | undefined; clear(): void; private grow; } type EngineKind = "ts" | "wasm"; type EngineStats = { engine: EngineKind; data: T; fallbackUsed: false; }; type EngineSelectionMode = EngineKind; type EngineSelection = EngineStats & { requested: EngineSelectionMode; }; declare function engineStats(engine: EngineKind, data: T): EngineStats; declare function selectedEngineStats(requested: EngineSelectionMode, engine: EngineKind, data: T): EngineSelection; type RingBufferStatsData = { len: number; capacity: number; pushes: number; shifts: number; clears: number; dropped: number; }; type RingLike = { readonly length: number; readonly capacity: number; readonly engine: "ts" | "wasm"; readonly fallbackUsed: boolean; isEmpty(): boolean; push(value: T): PushStatus; shift(): T | undefined; clear(): void; stats(): EngineStats; }; type RingBufferEngine = "ts" | "wasm"; type RingBufferOptions = { engine?: RingBufferEngine; }; declare function makeBoundedRingBuffer(initialCapacity: number, maxCapacity?: number, options?: RingBufferOptions): RingLike; type Task = () => void; type ScheduleResult = "accepted" | "dropped"; type SchedulerLaneMode = "fair" | "single"; type SchedulerEngine = "ts" | "wasm"; type LaneStatsData = { key: string; len: number; capacity: number; enqueuedTasks: number; executedTasks: number; droppedTasks: number; }; type SchedulerStatsData = { len: number; capacity?: number; phase?: string; scheduledFlushes?: number; completedFlushes?: number; enqueuedTasks?: number; executedTasks?: number; droppedTasks?: number; yieldedByBudget?: number; lanes?: LaneStatsData[]; }; type SchedulerStats = EngineStats; type SchedulerOptions = RingBufferOptions & { engine?: SchedulerEngine; /** fair keeps per-lane round-robin scheduling; single uses one direct TS queue for maximum throughput. */ laneMode?: SchedulerLaneMode; initialCapacity?: number; maxCapacity?: number; flushBudget?: number; microThreshold?: number; /** Capacity per inferred caller lane. Overflow drops the newly enqueued task in that lane. */ laneCapacity?: number; /** Max tasks a single lane can run before rotating to the next lane. */ laneBudget?: number; /** Safety cap for distinct lanes. New lanes past this limit go to `overflow`. */ maxLanes?: number; }; declare function sanitizeLaneKey(value: string): string; declare function laneTag(lane: string, tag?: string): string; /** * Infers a logical caller lane from the first non-Brass frame in the stack. * This keeps Brass implementation-agnostic: the first task/fiber gets a stable * key derived from the upper layer that invoked the runtime, and children inherit it. */ declare function inferCallerLaneFromStack(stack?: string | undefined, fallback?: string): string; declare class Scheduler { private readonly engine; private readonly js?; private readonly jsSingle?; private readonly wasm?; private readonly flushBudget; private readonly microThreshold; private readonly laneCapacity; private readonly laneBudget; private readonly maxLanes; private readonly fallbackUsed; private readonly boundFlush; private shiftedTag; constructor(options?: SchedulerOptions); schedule(task: Task, tag?: string): ScheduleResult; scheduleBatch(tasks: Array<{ fn: Task; tag: string; }>): ScheduleResult[]; stats(): SchedulerStats; private scheduleWasm; private scheduleBatchWasm; private getOrCreateLane; private createLane; private scheduleJsSingle; private scheduleBatchJsSingle; private scheduleJs; private requestFlush; private flush; private flushWasm; private flushJsSingle; private shiftFromNextLane; private flushJs; } declare const globalScheduler: Scheduler; type RuntimeEvent = { type: "fiber.start"; fiberId: number; parentFiberId?: number; scopeId?: number; name?: string; } | { type: "fiber.end"; fiberId: number; status: "success" | "failure" | "interrupted"; error?: unknown; } | { type: "fiber.suspend"; fiberId: number; reason?: string; } | { type: "fiber.resume"; fiberId: number; } | { type: "scope.open"; scopeId: number; parentScopeId?: number; } | { type: "scope.close"; scopeId: number; status: "success" | "failure" | "interrupted"; error?: unknown; } | { type: "supervisor.child.start"; supervisorId: number; childId: number; name?: string; restartCount: number; } | { type: "supervisor.child.end"; supervisorId: number; childId: number; name?: string; status: "success" | "failure" | "interrupted"; error?: unknown; } | { type: "supervisor.child.restart"; supervisorId: number; childId: number; name?: string; restartCount: number; delayMs: number; reason?: string; } | { type: "supervisor.child.escalate"; supervisorId: number; childId: number; name?: string; reason?: string; error?: unknown; } | { type: "supervisor.shutdown"; supervisorId: number; } | { type: "schedule.decision"; name?: string; attempt: number; elapsedMs: number; delayMs: number; continue: boolean; reason?: string; input?: unknown; output?: unknown; } | { type: "log"; level: "debug" | "info" | "warn" | "error"; message: string; fields?: Record; } | { type: "span.start"; name: string; attributes?: Record; links?: RuntimeSpanLink[]; } | { type: "span.event"; name: string; attributes?: Record; } | { type: "span.end"; name?: string; status: "success" | "failure" | "interrupted"; error?: unknown; attributes?: Record; }; type RuntimeEmitContext = { fiberId?: number; scopeId?: number; traceId?: string; spanId?: string; parentSpanId?: string; traceState?: string; baggage?: Record; sampled?: boolean; }; type RuntimeSpanLink = { traceId: string; spanId: string; traceState?: string; attributes?: Record; }; interface RuntimeHooks { emit(ev: RuntimeEvent, ctx: RuntimeEmitContext): void; } type RuntimeEventRecord = RuntimeEvent & RuntimeEmitContext & { seq: number; wallTs: number; ts: number; /** * The ambient fiber/scope from RuntimeEmitContext. Event payload fields * keep priority in the merged record, so these preserve the context when * an event also has a fiberId/scopeId of its own. */ contextFiberId?: number; contextScopeId?: number; /** * Convenience fields for generic event consumers. They are present for * log events and absent for fiber/scope events, but keeping them optional * lets subscribers inspect records without narrowing the RuntimeEvent * union first. */ level?: "debug" | "info" | "warn" | "error"; message?: string; fields?: Record; }; declare function makeRuntimeEventRecord(ev: RuntimeEvent, ctx: RuntimeEmitContext, seq: number): RuntimeEventRecord; declare function runtimeEventRecordContext(record: RuntimeEventRecord): RuntimeEmitContext; type FiberRunState = "Queued" | "Running" | "Suspended" | "Done"; type FiberInfo = { fiberId: number; parentFiberId?: number; name?: string; runState: FiberRunState; status: "Running" | "Done" | "Interrupted"; createdAt: number; lastActiveAt: number; scopeId?: number; traceId?: string; spanId?: string; awaiting?: { reason: string; detail?: string; }; lastEnd?: { status: string; error?: string; }; }; type ScopeInfo = { scopeId: number; parentScopeId?: number; ownerFiberId?: number; openAt: number; closedAt?: number; finalizers: Array<{ id: number; label?: string; status: "added" | "running" | "done"; }>; }; declare class RuntimeRegistry implements RuntimeHooks { fibers: Map; scopes: Map; private seq; private recent; private recentCap; emit(ev: RuntimeEvent, ctx: RuntimeEmitContext): void; getRecentEvents(): RuntimeEventRecord[]; } type HostActionKind = "http" | "db" | "queue" | "custom"; type HttpHostAction = { readonly kind: "http"; readonly actionId?: string; readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD"; readonly target: string; readonly path?: string; readonly headers?: Record; readonly body?: Uint8Array; readonly timeoutMs?: number; readonly responseLimitBytes?: number; readonly idempotencyKey?: string; }; type DbHostAction = { readonly kind: "db"; readonly actionId?: string; readonly operation: "get" | "put" | "query" | "delete"; readonly target: string; readonly payload: Uint8Array; readonly timeoutMs?: number; readonly idempotencyKey?: string; }; type QueueHostAction = { readonly kind: "queue"; readonly actionId?: string; readonly target: string; readonly payload: Uint8Array; readonly timeoutMs?: number; readonly idempotencyKey?: string; }; type CustomHostAction = { readonly kind: "custom"; readonly actionId?: string; readonly target: string; readonly payload?: Uint8Array; readonly timeoutMs?: number; readonly idempotencyKey?: string; }; type HostAction = HttpHostAction | DbHostAction | QueueHostAction | CustomHostAction; type HostActionResult = { readonly kind: "ok"; readonly actionId?: string; readonly value: A; readonly metadata?: Record; } | { readonly kind: "error"; readonly actionId?: string; readonly error: unknown; readonly metadata?: Record; }; type HostExecutionContext = { readonly fiberId: number; readonly env: R; readonly signal: AbortSignal; readonly deadlineAt?: number; }; interface HostExecutor { execute(action: HostAction, context: HostExecutionContext): Promise; } declare const DefaultHostExecutor: HostExecutor; type NodeId = number; type RefId = number; type FiberId$1 = number; type OpcodeNode = { readonly tag: "Succeed"; readonly valueRef: RefId; } | { readonly tag: "Fail"; readonly errorRef: RefId; } | { readonly tag: "Sync"; readonly fnRef: RefId; } | { readonly tag: "Async"; readonly registerRef: RefId; } | { readonly tag: "FlatMap"; readonly first: NodeId; readonly fnRef: RefId; } | { readonly tag: "Fold"; readonly first: NodeId; readonly onFailureRef: RefId; readonly onSuccessRef: RefId; } | { readonly tag: "Fork"; readonly effectRef: RefId; readonly scopeId?: number; } | { readonly tag: "HostAction"; readonly actionRef: RefId; readonly decodeRef?: RefId; }; type OpcodeProgram = { readonly version: 1; readonly root: NodeId; readonly nodes: OpcodeNode[]; }; type ProgramPatch = { readonly root: NodeId; readonly nodes: OpcodeNode[]; }; type SyncRef = (env: R) => unknown; type AsyncRegisterRef = (env: R, cb: (exit: unknown) => void) => void | (() => void); type FlatMapRef = (value: unknown) => Async; type FoldFailureRef = (error: unknown) => Async; type FoldSuccessRef = (value: unknown) => Async; type DecodeRef = (result: HostActionResult) => unknown; type HostRegistryStats = { readonly live: number; readonly capacity: number; readonly allocated: number; readonly released: number; readonly reused: number; readonly staleReads: number; }; /** * Slab-backed registry for JS values referenced by the WASM VM. * * Refs are generational u32 handles: stale refs fail fast after a slot is * released/reused. clear() releases all live slots, which is called when a * fiber completes so callbacks, errors, decoders and intermediate values do not * stay retained by the engine. */ declare class HostRegistry { private readonly slots; private readonly free; private live; private allocated; private released; private reused; private staleReads; register(value: T): RefId; get(ref: RefId): T; set(ref: RefId, value: unknown): void; delete(ref: RefId): void; clear(): void; size(): number; stats(): HostRegistryStats; } type CompiledProgram = { readonly program: OpcodeProgram; readonly registry: HostRegistry; }; declare class ProgramBuilder { private readonly nodes; private readonly registry; compile(effect: Async): CompiledProgram; append(effect: Async): ProgramPatch; private add; private visit; } type FiberEngineKind = "ts" | "wasm"; type RuntimeEngineMode = FiberEngineKind; type FiberEngineStats = { readonly engine: string; readonly startedFibers: number; readonly runningFibers: number; readonly suspendedFibers: number; readonly queuedFibers: number; readonly completedFibers: number; readonly failedFibers: number; readonly interruptedFibers: number; readonly pendingHostEffects: number; readonly hostRegistryRefs?: number; readonly hostRegistryStats?: unknown; readonly wasm?: unknown; readonly fiberRegistry?: unknown; readonly readyQueue?: unknown; readonly timerWheel?: unknown; }; interface FiberEngine { readonly kind: FiberEngineKind; fork(effect: Async, scopeId?: number): Fiber & { schedule?: (tag?: string) => void; }; stats(): FiberEngineStats; shutdown?(): Promise | void; } type WasmEngineRuntime = { readonly env: R; readonly hostExecutor: HostExecutor; readonly scheduler: { schedule(task: () => void, label?: string): unknown; }; readonly hooks: { emit(ev: any, ctx: any): void; }; fork(effect: Async, scopeId?: number): Fiber; }; type EngineEvent = { readonly kind: "Continue"; readonly fiberId: FiberId$1; } | { readonly kind: "Done"; readonly fiberId: FiberId$1; readonly valueRef: RefId; } | { readonly kind: "Failed"; readonly fiberId: FiberId$1; readonly errorRef: RefId; } | { readonly kind: "Interrupted"; readonly fiberId: FiberId$1; readonly reasonRef: RefId; } | { readonly kind: "InvokeSync"; readonly fiberId: FiberId$1; readonly fnRef: RefId; } | { readonly kind: "InvokeAsync"; readonly fiberId: FiberId$1; readonly registerRef: RefId; } | { readonly kind: "InvokeFlatMap"; readonly fiberId: FiberId$1; readonly fnRef: RefId; readonly valueRef: RefId; } | { readonly kind: "InvokeFoldFailure"; readonly fiberId: FiberId$1; readonly fnRef: RefId; readonly errorRef: RefId; } | { readonly kind: "InvokeFoldSuccess"; readonly fiberId: FiberId$1; readonly fnRef: RefId; readonly valueRef: RefId; } | { readonly kind: "InvokeFork"; readonly fiberId: FiberId$1; readonly effectRef: RefId; readonly scopeId?: number; } | { readonly kind: "InvokeHostAction"; readonly fiberId: FiberId$1; readonly actionRef: RefId; readonly decodeRef?: RefId; }; interface WasmBridge { readonly kind: "wasm"; readonly supportsBinary?: boolean; readonly supportsZeroCopy?: boolean; readonly supportsNoJsonMetrics?: boolean; createFiber(program: OpcodeProgram): FiberId$1; poll(fiberId: FiberId$1): EngineEvent; driveBatch?(fiberId: FiberId$1, budget: number): readonly EngineEvent[]; provideValue(fiberId: FiberId$1, valueRef: RefId): EngineEvent; provideValueBatch?(fiberId: FiberId$1, valueRef: RefId, budget: number): readonly EngineEvent[]; provideError(fiberId: FiberId$1, errorRef: RefId): EngineEvent; provideErrorBatch?(fiberId: FiberId$1, errorRef: RefId, budget: number): readonly EngineEvent[]; provideEffect(fiberId: FiberId$1, root: NodeId, nodes: OpcodeNode[]): EngineEvent; provideEffectBatch?(fiberId: FiberId$1, root: NodeId, nodes: OpcodeNode[], budget: number): readonly EngineEvent[]; interrupt(fiberId: FiberId$1, reasonRef: RefId): EngineEvent; interruptBatch?(fiberId: FiberId$1, reasonRef: RefId, budget: number): readonly EngineEvent[]; dropFiber(fiberId: FiberId$1): void; stats(): unknown; } type Joiner = (exit: Exit) => void; type ReadyQueueScheduleKind = "micro" | "macro" | "none" | "dropped"; type FiberReadyQueueStats = { readonly engine: "ts" | "wasm"; readonly fallbackUsed: boolean; readonly data: unknown; }; interface FiberReadyQueue { readonly engine: "ts" | "wasm"; enqueue(fiberId: FiberId$1, tag: string): ReadyQueueScheduleKind; beginFlush(): number; shift(): FiberId$1 | undefined; endFlush(ran: number): ReadyQueueScheduleKind; len(): number; clear(): void; stats(): FiberReadyQueueStats; } type FiberReadyQueueOptions = { readonly engine?: "ts" | "wasm"; readonly flushBudget?: number; readonly microThreshold?: number; readonly laneCapacity?: number; readonly laneBudget?: number; readonly maxLanes?: number; }; declare function makeFiberReadyQueue(options?: FiberReadyQueueOptions): FiberReadyQueue; type WasmFiberEngineOptions = { readonly bridge?: WasmBridge; readonly modulePath?: string; readonly readyQueue?: Omit; }; declare class WasmFiberEngine implements FiberEngine { private readonly runtime; readonly kind: FiberEngineKind; private readonly bridge; private readonly readyQueue; private startedFibers; private runningFibers; private suspendedFibers; private completedFibers; private failedFibers; private interruptedFibers; private pendingHostEffects; private readyDrainScheduled; private readyDraining; private readonly states; private readonly pendingResumes; private readonly fiberRegistry?; private readonly timerWheel?; constructor(runtime: WasmEngineRuntime & any, options?: WasmFiberEngineOptions); fork(effect: Async, scopeId?: number): Fiber & { schedule?: (tag?: string) => void; }; stats(): FiberEngineStats; shutdown(): Promise; private scheduleWakeup; private drainWakeups; private enqueueFiber; private enqueueFiberById; private requestReadyDrain; private drainReadyQueue; private driveById; private consumePendingResume; private drive; private scheduleAsync; private scheduleHostAction; private onTimerExpired; private resumeWithExit; private completeCause; private resumeWithValue; private resumeWithError; private schedulerTag; private schedulerDropped; private interruptById; private interruptState; private markSuspended; private markRunning; private completeSuccess; private completeFailure; private completeDie; private completeInterrupted; private cleanupState; } declare const NoopHooks: RuntimeHooks; /** * --- Runtime como objeto único (ZIO-style) --- * Un valor que representa "cómo" se ejecutan los efectos: scheduler + environment + hooks. */ type RuntimeOptions = { env: R; scheduler?: Scheduler; /** Logical caller/lane. When set, every fiber forked by this runtime is scheduled inside this lane. */ lane?: string; /** Infer a caller lane from the top-level callsite when no explicit lane/parent lane exists. Defaults to true. */ inferLane?: boolean; hooks?: RuntimeHooks; /** * Selects the fiber interpreter used by fork(). * * Strict mode only accepts: * - ts: TypeScript RuntimeFiber interpreter. * - wasm: wasm-pack backed interpreter from wasm/pkg. * * There is no auto mode and no TS fallback when wasm is requested. */ engine?: RuntimeEngineMode; /** Executor used by HostAction opcodes when running on the WASM engine. */ hostExecutor?: HostExecutor; /** Optional low-level WASM bridge options, mostly for tests and local experiments. */ wasm?: WasmFiberEngineOptions; }; declare class Runtime { readonly env: R; readonly scheduler: Scheduler; readonly hooks: RuntimeHooks; readonly hostExecutor: HostExecutor; readonly engineMode: RuntimeEngineMode; readonly wasmOptions?: WasmFiberEngineOptions; readonly fiberEngine: FiberEngine; readonly fallbackUsed: boolean; readonly forkPolicy: { initChild(fiber: RuntimeFiber & any, parent?: (RuntimeFiber & any) | null, scopeId?: number): void; }; readonly lane?: string; readonly inferLane: boolean; registry?: RuntimeRegistry; constructor(args: RuntimeOptions); private readonly staticFastPathOk; private makeFiberEngine; /** Returns true when the runtime has real hooks (not the no-op singleton). */ hasActiveHooks(): boolean; /** Deriva un runtime con env extendido (estilo provide/locally) */ provide(env: R2): Runtime; /** * Returns a derived runtime that schedules all work in a caller/lane. * Brass does not need to know the caller implementation; it only sees this stable key. */ withLane(lane: string): Runtime; private resolveFiberLane; emit(ev: RuntimeEvent): void; /** * ✅ CAMBIO: fork(effect, scopeId?) y pasa scopeId a forkPolicy */ fork(effect: Async, scopeId?: number): Fiber; stats(): EngineStats["stats"]>>; capabilities(): RuntimeCapabilities; shutdown(): Promise | void; unsafeRunAsync(effect: Async, cb: (exit: Exit) => void): void; private static exitToError; toPromise(effect: Async): Promise; private tryRunNativeTopLevel; unsafeRun(effect: Async): void; delay(ms: number, eff: Async): Async; static make(env: R, scheduler?: Scheduler): Runtime; static makeWithEngine(env: R, engine: RuntimeEngineMode, options?: Omit, "env" | "engine">): Runtime; /** Convenience logger: emits a RuntimeEvent of type "log". */ log(level: "debug" | "info" | "warn" | "error", message: string, fields?: Record): void; } /** Create a runtime from `env` and fork the given effect. */ declare function fork(effect: Async, env?: R): Fiber; /** Create a runtime with a stable lane/caller key. */ declare function runtimeForCaller(caller: string, env?: R): Runtime; /** Run an effect in a caller lane without exposing scheduler internals to the caller. */ declare function toPromiseByCaller(caller: string, effect: Async, env?: R): Promise; /** Run an effect with `env` and invoke `cb` with the final Exit. */ declare function unsafeRunAsync(effect: Async, env: R | undefined, cb: (exit: Exit) => void): void; /** Run an effect with `env` and return a Promise of its success value. */ declare function toPromise(effect: Async, env?: R): Promise; type AbortablePromiseOutcome = "success" | "failure" | "interrupt" | "timeout"; type AbortablePromiseFinish = { readonly label: string; readonly outcome: AbortablePromiseOutcome; readonly durationMs: number; readonly error?: unknown; }; /** * Duck-typed timer wheel interface for use in AbortablePromiseOptions. * Avoids importing from `src/http/timerWheel.ts` to prevent circular dependencies. * Any object with a compatible `schedule` method can be used. */ interface AbortablePromiseTimerWheel { schedule(timeoutMs: number, cb: () => void): { cancel(): void; }; } type AbortablePromiseOptions = { /** Logical label used by diagnostics. Keep it low-cardinality: e.g. `http:GET:https://api.foo.com`. */ readonly label?: string; /** Fails the effect after this budget and aborts the underlying signal. Disabled when omitted or <= 0. */ readonly timeoutMs?: number; /** Custom reason passed to `onReject` when the timeout fires. */ readonly timeoutReason?: () => unknown; readonly onStart?: (label: string) => void; readonly onFinish?: (finish: AbortablePromiseFinish) => void; /** Optional timer wheel for efficient timeout scheduling. When provided, uses wheel.schedule() instead of setTimeout. */ readonly timerWheel?: AbortablePromiseTimerWheel; }; type AbortablePromiseLabelStats = { readonly label: string; readonly active: number; readonly started: number; readonly succeeded: number; readonly failed: number; readonly interrupted: number; readonly timedOut: number; readonly lateSettlements: number; }; type AbortablePromiseStats = { readonly active: number; readonly started: number; readonly succeeded: number; readonly failed: number; readonly interrupted: number; readonly timedOut: number; readonly lateSettlements: number; readonly byLabel: AbortablePromiseLabelStats[]; }; /** * Enable or disable per-label tracking for abortable promise diagnostics. * When disabled (default), only global integer counters are incremented on the hot path, * avoiding Map allocations entirely. Returns the previous enabled state. */ declare function setAbortablePromisePerLabelTracking(enabled: boolean): boolean; declare const recordAbortablePromiseStart: (label: string) => void; declare const recordAbortablePromiseFinish: (label: string, outcome: AbortablePromiseOutcome) => void; declare function abortablePromiseStats(): AbortablePromiseStats; declare function resetAbortablePromiseStats(): void; /** * Create an Async from an abortable Promise. * * Improvements over the original helper: * - optional timeout budget; * - global active/late-settlement diagnostics; * - explicit start/finish hooks for transport metrics; * - cleanup on every completion path, so timers/listeners do not retain fibers. * * Type params are ordered as `` to match call-sites. */ declare function fromPromiseAbortable(make: (signal: AbortSignal, env: R) => Promise, onReject: (u: unknown) => E, options?: AbortablePromiseOptions): Async; declare function unsafeRunFoldWithEnv(eff: Async, env: R, onFailure: (cause: Cause) => void, onSuccess: (value: A) => void): void; type JSONValue = null | boolean | number | string | JSONValue[] | { [k: string]: JSONValue; }; type ContextNode = { parent: ContextNode | null; patch: Record; }; declare const emptyContext: ContextNode; declare function ctxExtend(parent: ContextNode, patch: Record): ContextNode; declare function ctxToObject(ctx: ContextNode): Record; type Baggage = Record; type TraceContext = { traceId: string; spanId: string; parentSpanId?: string; sampled?: boolean; traceState?: string; baggage?: Baggage; }; type FiberContext = { log: ContextNode; trace: TraceContext | null; fiberRefs?: Map; }; type FiberId = number; type FiberStatus = "Running" | "Done" | "Interrupted"; type Interrupted = { readonly _tag: "Interrupt"; }; type Fiber = { readonly id: FiberId; readonly status: () => FiberStatus; readonly join: (cb: (exit: Exit) => void) => void; readonly interrupt: () => void; readonly addFinalizer: (f: (exit: Exit) => void) => void; }; declare function setBenchmarkBudget(budget: number | undefined): void; declare function getBenchmarkBudget(): number | undefined; declare class RuntimeFiber implements Fiber { readonly id: FiberId; readonly runtime: Runtime; private closing; private finishing; private runState; private interrupted; private result; private readonly joiners; private current; private readonly stack; private readonly fiberFinalizers; private finalizersDrained; private interruptibilityDepth; fiberContext: FiberContext; name?: string; scopeId?: number; lane?: string; /** * Cached closure for the scheduler callback — avoids creating a new * closure on every `schedule()` call. The tag parameter used by the * scheduler is only part of the label string, not the callback logic, * so a single cached closure is sufficient. */ private readonly boundStep; private _syncResolved; private _syncExit; private _asyncRegistered; private _asyncDetach; private readonly _asyncCb; constructor(runtime: Runtime, effect: Async); private get env(); private get scheduler(); private emit; addFinalizer(f: (exit: Exit) => void): void; /** * Internal finalizers used for suspend cancelers. They are detached as soon * as the async operation completes, so completed HTTP/promises do not keep * canceler closures alive until the fiber itself finishes. */ private addTransientFinalizer; status(): FiberStatus; join(cb: (exit: Exit) => void): void; interrupt(): void; schedule(tag?: string): void; private runFinalizersOnce; private notify; private isInterruptible; private shouldInterruptNow; private enterInterruptibility; private restoreInterruptibility; private fiberRefs; private restoreFiberRef; private onSuccess; private onFailure; private onCause; private budget; private step; /** * Sync trampoline: processes FlatMap chains in a tight loop without the * overhead of the general switch/case. Handles: * - FlatMap(Async(sync), k) — the queue/stream hot path * - FlatMap(Succeed(v), k) — pure value chains * - FlatMap(Sync(f), k) — synchronous thunks * - FlatMap(FlatMap(...), k) — left-associated chains (reassociates inline) * - FlatMap(Fold(...), k) — pushes fold frame and continues * * Returns TRAMPOLINE.CONTINUE when it hits a node it can't handle, * leaving this.current set to that node for the normal switch to process. */ private syncTrampoline; } declare function getCurrentFiber(): RuntimeFiber | null; /** * Unsafe (but convenient) access to the runtime that is currently executing. * Throws if called outside of a running fiber. */ declare function unsafeGetCurrentRuntime(): Runtime; declare function withCurrentFiber(fiber: RuntimeFiber, f: () => T): T; /** * Direct setter for the current fiber. Used by NativeTopLevelRunner to avoid * the closure allocation of withCurrentFiber when running tight loops. * Caller MUST restore the previous value via setCurrentFiber to maintain invariants. */ declare function setCurrentFiber(fiber: RuntimeFiber | null): RuntimeFiber | null; type ScopeId = number; type CloseOptions = { awaitChildren?: boolean; }; declare class Scope { private readonly runtime; private readonly parentScopeId?; readonly id: ScopeId; private closed; private readonly children; private readonly subScopes; private readonly finalizers; constructor(runtime: Runtime, parentScopeId?: ScopeId | undefined); /** registra un finalizer (LIFO) */ addFinalizer(f: (exit: Exit) => Async): void; /** crea un sub scope (mismo runtime) */ subScope(): Scope; /** ✅ fork en este scope */ fork(eff: Async): Fiber; /** close fire-and-forget (no bloquea) */ close(exit?: Exit): void; /** Emit the scope.close event if hooks are active. */ private emitCloseEvent; /** * Build an effect that executes finalizers in LIFO order. * * Optimization over the original: instead of wrapping every finalizer in * `asyncFold(fin(exit), () => unit(), () => unit())` which creates 3 effect * nodes per finalizer (Fold + 2 Succeed), we use a single Sync thunk per * finalizer that catches errors inline. When the finalizer returns a * Succeed effect (like `unit()`), the Sync thunk completes without creating * additional effect nodes. */ private buildFinalizerEffect; closeAsync(exit?: Exit, opts?: CloseOptions): Async; } declare function withScopeAsync(runtime: Runtime, f: (scope: Scope) => Async): Async; declare function withScope(runtime: Runtime, f: (scope: Scope) => void): Async; declare function withScope(runtime: Runtime, f: (scope: Scope) => Async): Async; type InterruptibilityMode = "uninterruptible" | "interruptible"; type RestoreInterruptibility = (effect: Async) => Async; type Async = { readonly _tag: "Succeed"; readonly value: A; } | { readonly _tag: "Fail"; readonly error: E; } | { readonly _tag: "Sync"; readonly thunk: (env: R) => A; } | { readonly _tag: "Async"; readonly register: (env: R, cb: (exit: Exit) => void) => void | (() => void); } | { readonly _tag: "FlatMap"; readonly first: Async; readonly andThen: (a: any) => Async; } | { readonly _tag: "Fold"; readonly first: Async; readonly onFailure: (e: any) => Async; readonly onSuccess: (a: any) => Async; } | { readonly _tag: "Fork"; readonly effect: Async; readonly scopeId?: number; } | { readonly _tag: "Interruptibility"; readonly mode: InterruptibilityMode; readonly effect: Async; } | { readonly _tag: "InterruptibilityMask"; readonly body: (restore: RestoreInterruptibility) => Async; } | { readonly _tag: "InterruptibilityRestore"; readonly depth: number; readonly effect: Async; } | { readonly _tag: "FiberRefLocally"; readonly refId: number; readonly value: unknown; readonly effect: Async; }; declare const Async: { succeed: (value: A) => Async; fail: (error: E) => Async; sync: (thunk: (env: R) => A) => Async; async: (register: (env: R, cb: (exit: Exit) => void) => void | (() => void)) => Async; interruptibility: (mode: InterruptibilityMode, effect: Async) => Async; }; declare function asyncFold(fa: Async, onFailure: (e: E) => Async, onSuccess: (a: A) => Async): Async; declare function asyncCatchAll(fa: Async, handler: (e: E) => Async): Async; declare function asyncMapError(fa: Async, f: (e: E) => E2): Async; declare const unit: () => Async; declare const asyncSucceed: (value: A) => Async; declare const asyncFail: (error: E) => Async; declare const asyncSync: (thunk: (env: R) => A) => Async; declare const asyncTotal: (thunk: () => A) => Async; declare const asyncEffect: (register: (env: R, cb: (exit: Exit) => void) => void | Canceler) => Async; declare function asyncMap(fa: Async, f: (a: A) => B): Async; declare function asyncFlatMap(fa: Async, f: (a: A) => Async): Async; declare function acquireRelease(acquire: Async, release: (res: A, exit: Exit) => Async, scope: Scope): Async; declare function asyncInterruptible(register: (env: R, cb: (exit: Exit) => void) => void | Canceler): Async; type AsyncWithPromise = Async & { toPromise: (env: R) => Promise; unsafeRunPromise: () => Promise; }; declare const withAsyncPromise: (run: (eff: Async, env: R) => Promise) => (eff: Async) => AsyncWithPromise; declare const mapAsync: (fa: Async, f: (a: A) => B) => Async; declare const mapTryAsync: (fa: Async, f: (a: A) => B) => Async; type None = { readonly _tag: "None"; }; type Some = { readonly _tag: "Some"; readonly value: A; }; type Option = None | Some; declare const none: Option; declare const some: (value: A) => Option; type CausePrettyOptions = { readonly renderError?: (error: E) => string; readonly renderDefect?: (defect: unknown) => string; readonly indent?: string; readonly singleLine?: boolean; }; type Cause = { readonly _tag: "Fail"; readonly error: E; } | { readonly _tag: "Interrupt"; } | { readonly _tag: "Die"; readonly defect: unknown; } | { readonly _tag: "Then"; readonly left: Cause; readonly right: Cause; } | { readonly _tag: "Both"; readonly left: Cause; readonly right: Cause; }; declare const Cause: { fail: (error: E) => Cause; interrupt: () => Cause; die: (defect: unknown) => Cause; then: (left: Cause, right: Cause) => Cause; both: (left: Cause, right: Cause) => Cause; isCause: typeof isCauseValue; failures: typeof causeFailures; defects: typeof causeDefects; firstFailure: typeof firstCauseFailure; firstDefect: typeof firstCauseDefect; containsFailure: typeof causeContainsFailure; containsDefect: typeof causeContainsDefect; containsInterrupt: typeof causeContainsInterrupt; isInterruptedOnly: typeof causeIsInterruptedOnly; isFailureOnly: typeof causeIsFailureOnly; squash: typeof squashCause; toError: typeof causeToError; pretty: typeof prettyCause; format: typeof prettyCause; }; declare function isCause(value: unknown): value is Cause; declare function prettyCause(cause: Cause, options?: CausePrettyOptions): string; declare const formatCause: typeof prettyCause; declare function isCauseValue(value: unknown): value is Cause; declare function causeFailures(cause: Cause): readonly E[]; declare function causeDefects(cause: Cause): readonly unknown[]; declare function firstCauseFailure(cause: Cause): Option; declare function firstCauseDefect(cause: Cause): Option; declare function causeContainsFailure(cause: Cause): boolean; declare function causeContainsDefect(cause: Cause): boolean; declare function causeContainsInterrupt(cause: Cause): boolean; declare function causeIsInterruptedOnly(cause: Cause): boolean; declare function causeIsFailureOnly(cause: Cause): boolean; declare function squashCause(cause: Cause): unknown; declare function causeToError(cause: Cause): Error; type Exit = { _tag: "Success"; value: A; } | { _tag: "Failure"; cause: Cause; }; declare const Exit: { succeed: (value: A) => Exit; failCause: (cause: Cause) => Exit; }; type ZIO = Async; declare const succeed: (value: A) => ZIO; declare const fail: (error: E) => ZIO; declare const sync: (thunk: (env: R) => A) => ZIO; declare const map: (fa: ZIO, f: (a: A) => B) => Async; declare const flatMap: (fa: ZIO, f: (a: A) => ZIO) => ZIO; declare const mapError: (fa: ZIO, f: (e: E) => E2) => ZIO; declare const catchAll: (fa: ZIO, handler: (e: E) => ZIO) => ZIO; declare const uninterruptible: (effect: ZIO) => ZIO; declare const interruptible: (effect: ZIO) => ZIO; declare function uninterruptibleMask(body: (restore: RestoreInterruptibility) => ZIO): ZIO; declare function orElseOptional(fa: ZIO, A>, that: () => ZIO, A2>): ZIO, A | A2>; declare const end: () => ZIO, never>; export { type FiberContext as $, Async as A, type Baggage as B, type AsyncRegisterRef as C, type AsyncWithPromise as D, Exit as E, type FiberEngine as F, type RingLike as G, type CancelToken as H, type Canceler as I, type JSONValue as J, Cause as K, type CausePrettyOptions as L, type ContextNode as M, type NodeId as N, type Option as O, type CustomHostAction as P, type DbHostAction as Q, type RuntimeHooks as R, Scope as S, type TraceContext as T, type DecodeRef as U, DefaultHostExecutor as V, type WasmEngineRuntime as W, type EngineKind as X, type EngineSelection as Y, type ZIO as Z, type EngineSelectionMode as _, type RuntimeOptions as a, ctxToObject as a$, type FiberEngineKind as a0, type FiberInfo as a1, type FiberReadyQueue as a2, type FiberReadyQueueOptions as a3, type FiberReadyQueueStats as a4, type FiberRunState as a5, type FlatMapRef as a6, type FoldFailureRef as a7, type FoldSuccessRef as a8, type HostAction as a9, type SchedulerEngine as aA, type SchedulerLaneMode as aB, type SchedulerOptions as aC, type SchedulerStats as aD, type SchedulerStatsData as aE, type ScopeId as aF, type ScopeInfo as aG, type Some as aH, type SyncRef as aI, type Task as aJ, WasmFiberEngine as aK, type WasmFiberEngineOptions as aL, abortablePromiseStats as aM, acquireRelease as aN, asyncEffect as aO, asyncCatchAll as aP, asyncFail as aQ, asyncFlatMap as aR, asyncFold as aS, asyncInterruptible as aT, asyncMap as aU, asyncMapError as aV, asyncSucceed as aW, asyncSync as aX, asyncTotal as aY, catchAll as aZ, ctxExtend as a_, type HostActionKind as aa, type HostActionResult as ab, type HostExecutionContext as ac, type HostExecutor as ad, HostRegistry as ae, type HostRegistryStats as af, type HttpHostAction as ag, type Interrupted as ah, type InterruptibilityMode as ai, type Joiner as aj, type LaneStatsData as ak, type None as al, NoopHooks as am, ProgramBuilder as an, type ProgramPatch as ao, PushStatus as ap, type QueueHostAction as aq, type ReadyQueueScheduleKind as ar, type RestoreInterruptibility as as, RingBuffer as at, type RingBufferEngine as au, type RingBufferStatsData as av, type RuntimeCapabilities as aw, type RuntimeEngineMode as ax, type ScheduleResult as ay, Scheduler as az, Runtime as b, emptyContext as b0, end as b1, engineStats as b2, fail as b3, flatMap as b4, fork as b5, formatCause as b6, fromPromiseAbortable as b7, getBenchmarkBudget as b8, getCurrentFiber as b9, setBenchmarkBudget as bA, setCurrentFiber as bB, some as bC, succeed as bD, sync as bE, toPromise as bF, toPromiseByCaller as bG, uninterruptible as bH, uninterruptibleMask as bI, unit as bJ, unsafeGetCurrentRuntime as bK, unsafeRunAsync as bL, unsafeRunFoldWithEnv as bM, withAsyncPromise as bN, withCurrentFiber as bO, withScope as bP, withScopeAsync as bQ, globalScheduler as ba, inferCallerLaneFromStack as bb, interruptible as bc, isCause as bd, laneTag as be, linkAbortController as bf, makeBoundedRingBuffer as bg, makeCancelToken as bh, makeFiberReadyQueue as bi, makeRuntimeEventRecord as bj, map as bk, mapAsync as bl, mapError as bm, mapTryAsync as bn, none as bo, orElseOptional as bp, prettyCause as bq, recordAbortablePromiseFinish as br, recordAbortablePromiseStart as bs, resetAbortablePromiseStats as bt, runtimeCapabilities as bu, runtimeEventRecordContext as bv, runtimeForCaller as bw, sanitizeLaneKey as bx, selectedEngineStats as by, setAbortablePromisePerLabelTracking as bz, type RingBufferOptions as c, type RuntimeEvent as d, type RuntimeEmitContext as e, type RuntimeEventRecord as f, type RuntimeSpanLink as g, RuntimeRegistry as h, RuntimeFiber as i, type FiberEngineStats as j, type Fiber as k, type FiberId as l, type FiberStatus as m, type WasmBridge as n, type OpcodeProgram as o, type FiberId$1 as p, type EngineEvent as q, type RefId as r, type OpcodeNode as s, type EngineStats as t, type AbortablePromiseFinish as u, type AbortablePromiseLabelStats as v, type AbortablePromiseOptions as w, type AbortablePromiseOutcome as x, type AbortablePromiseStats as y, type AbortablePromiseTimerWheel as z };