/** * Copyright (c) 2025 Elara AI Pty Ltd * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details. */ /** * Runtime implementation for the `Func.bind` platform function — calling * named package functions (`e3.function`) from East UI code, RPC-style. * * A tracked call is an un-awaited `FunctionApi.call` promise tagged with * the monotonic `launchSeq` it was issued under; whichever response still * holds the current seq writes the terminal state (latest-wins). A call is * the server's for its lifetime, and outlives the request that starts it: * `cancel`, and a call that supersedes another on its channel, bump the seq * and abort the in-flight call's signal, which asks the server to stop it. * So does its page going: the provider's teardown ({@link FuncRuntime.clear}) * and the page closing for good (`pagehide`, unless the page is kept for the * back button) stop every call in flight. e3's client names each call before * it sends it, so a call is asked to stop however soon its page goes. * * All handles bound to the same function name in the same workspace share * one registry entry, mirroring how `Data.bind` handles share the dataset * cache by path. Declared signatures are validated against the deployed * package's function list before any call is sent. * * State (registry, signature cache, tracking context) is encapsulated in * the {@link FuncRuntime} class. A process-global {@link defaultFuncRuntime} * powers the `FuncPlatform` export; tests construct their own runtime for * isolation. * * @packageDocumentation */ import { type EastType, type EastTypeValue, type ValueTypeOf } from "@elaraai/east"; import { type PlatformFunction } from "@elaraai/east/internal"; import { FuncStatusType, FuncErrorType } from "@elaraai/e3-ui/internal"; import { type ExecuteResult, type FunctionSignature, type RequestOptions } from "@elaraai/e3-api-client"; import { TrackedChannelStore } from "./tracked-channel.js"; /** Request shape for {@link FunctionApi.call} — beast2-encoded positional * args. Runner/limit overrides are deliberately not exposed (the deployed * function's runner is authoritative). */ export interface FunctionCallArgs { args: Uint8Array[]; } /** Options for {@link FunctionApi.call}. */ export interface FunctionCallOptions { /** Stops the call: the call stops waiting, and asks the server to stop it */ signal?: AbortSignal; } /** * Adapter for the workspace function endpoints. The default wraps * `@elaraai/e3-api-client`'s `workspaceFunctionList` / * `workspaceFunctionCall`. */ export interface FunctionApi { /** List the workspace's deployed functions with their signatures. */ list(workspace: string): Promise; /** * Call a function, returning its terminal ExecuteResult once it ends, * however long it runs. Aborting `options.signal` stops the call: its * promise rejects with the abort, and the server is asked to stop it. */ call(workspace: string, fn: string, req: FunctionCallArgs, options?: FunctionCallOptions): Promise; } /** Options for {@link createDefaultFunctionApi}. */ export interface DefaultFunctionApiOptions { /** * How long a call's start waits for it to end before it answers * `running`, in milliseconds: the server's window unless set. A call that * ends within it costs one request; one that runs on past it is polled. */ readonly startWaitMs?: number; } /** * Build the default {@link FunctionApi} that talks to a real e3 server via * `@elaraai/e3-api-client`. * * @param apiUrl - Base URL of the e3 API server * @param repo - Repository name * @param getOptions - Reads the current request options — the token, and the * `fetch` requests go through — so a rotated one is used at once * @param options - How long a call's start waits for it to end * @returns The adapter */ export declare function createDefaultFunctionApi(apiUrl: string, repo: string, getOptions: () => RequestOptions, options?: DefaultFunctionApiOptions): FunctionApi; type FuncError = ValueTypeOf; type FuncStatusTag = ValueTypeOf["type"]; /** A handle's signature, recovered from the instantiated handle type. */ interface FuncHandleSignature { readonly inputs: EastTypeValue[]; readonly output: EastTypeValue; } /** * Introspect the instantiated handle struct type `H`: the input types come * from the `call` field's FunctionType, the output type from the `read` * field's `Option(Output)` return. The handle's shape IS the signature — * there are no duplicate signature arguments to drift out of sync. */ export declare function signatureOfFuncHandleType(handleType: EastTypeValue): FuncHandleSignature; /** One tracked channel per `(workspace, name)`. */ interface FuncEntry { status: FuncStatusTag; /** Monotonic; a settling call whose seq is no longer current is * discarded (latest-wins, and `cancel` orphans by bumping it). */ launchSeq: number; /** Decoded Output of the last `succeeded` call. */ result?: unknown; /** Detail of the last `failed` call. */ error?: FuncError; /** Stops the call in flight, while one is: a call that supersedes it, and * `cancel`, abort it, which asks the server to stop it. */ inflight?: AbortController; } /** Tracked-channel key. */ export declare function funcChannelKey(workspace: string, name: string): string; /** What tells a runtime its page is going: a page's window, or a stand-in. */ export type FuncPage = Pick; /** Options for {@link FuncRuntime}. */ export interface FuncRuntimeOptions { /** * The page whose closing stops the calls in flight: its `pagehide`, unless * the page is kept for the back button (`persisted`). Default: the global * object where it has events, a browser's window; none elsewhere. */ readonly page?: FuncPage | null; } /** * Encapsulates all `Func.bind` runtime state. The module-level * {@link defaultFuncRuntime} instance backs the registered platform; tests * construct their own for isolation. */ export declare class FuncRuntime extends TrackedChannelStore { private api; private workspace; /** The page whose closing stops the calls in flight; none outside a browser. */ private readonly page; /** Stops watching the page, while an adapter is installed. */ private unwatchPage; /** * @param options - The page whose closing stops the calls in flight */ constructor(options?: FuncRuntimeOptions); private signatureLists; private readonly handleCache; protected createEntry(): FuncEntry; /** Install the API adapter + workspace — called by the React provider * (or a test, or the snapshot harness) before any handle is used. From * now until {@link clear}, the page closing for good stops the calls in * flight. */ initialize(api: FunctionApi, workspace: string): void; /** * Tear down the adapter and all call state. A call in flight is its * page's, and its page is going: each is asked to stop on the server. * * @param api - Clear only while this is the installed adapter, so a * provider tearing down after another installed its own leaves that one * in place */ clear(api?: FunctionApi): void; /** Stops the calls in flight once the page closes for good: a page kept * for the back button may come back, its calls with it. */ private watchPage; /** Cancels a channel's call in flight: the server is asked to stop it. */ private cancelCall; /** Cancels every call in flight, each asked to stop on the server. */ private stopInFlight; /** The deployed signature list for a workspace (fetched once). */ private signatures; /** Validate a declared signature against the deployed list. Returns a * FuncError when the name is unknown or the signature disagrees. */ private validate; private launch; /** * The 6 low-level primitives backing handle methods, bound to THIS runtime. * Registered globally (extension registry) and included by the scoped * platform (e3 `ui()` tasks) so a decoded handle re-binds to whatever runtime * resolves the primitives on the decode side. The host effects (launch / * channel reads + reactive tracking) live here, keyed only on the plain-data * function name; the output type rides as a type-arg. */ buildPrimitives(): PlatformFunction[]; /** * Build the handle value for one `Func.bind` evaluation. The methods are * thin IR-bearing `East.function`s over {@link buildPrimitives}, capturing * only the function name (and the signature types via type-args) — so the * handle is ordinary serializable East data (issue #106). */ buildHandle(handleType: EastTypeValue, name: string): Record; /** Build a `Func.bind` PlatformFunction bound to this runtime. Pass * `allowed=null` for an unscoped impl; pass a Set of function names * for manifest scoping. */ buildPlatform(allowed: ReadonlySet | null): PlatformFunction; } /** Process-global runtime backing the `FuncPlatform` export. */ export declare const defaultFuncRuntime: FuncRuntime; /** Install the function API adapter + workspace — called by the React * provider on mount (or by a test, or the snapshot harness). */ export declare function initializeFunctionApi(api: FunctionApi, workspace: string): void; /** * Tear down the function API adapter and all call state. * * @param api - Clear only while this is the installed adapter */ export declare function clearFunctionApi(api?: FunctionApi): void; /** Global, manifest-unscoped `Func.bind` impl + its backing primitives. * Registered on module load (powers the extension registry decode path). */ export declare const FuncPlatform: PlatformFunction[]; /** Build a manifest-scoped `Func.bind` implementation + its backing primitives. * * The `function_*` primitives MUST ship with the scoped platform: e3 `ui()` * tasks render through `createScoped*()` arrays (UITaskPreview), NOT the global * registry, so a serialized handle's methods would otherwise decode to * "Platform function 'function_call' is not available". */ export declare function createScopedFuncPlatform(functions: readonly string[]): PlatformFunction[]; /** One offline function implementation for {@link createInMemoryFunctionApi}. */ export interface InMemoryFunctionDef { /** Function name (what `Func.bind` is bound to). */ name: string; /** The argument types a caller passes. */ argTypes: (EastType | EastTypeValue)[]; /** Return type. */ outputType: EastType | EastTypeValue; /** The implementation — receives decoded args, returns the result * value (or a promise of it). */ fn: (...args: unknown[]) => unknown; } /** * Build an offline {@link FunctionApi} from local implementations — the * snapshot harness's stand-in for a deployed package. */ export declare function createInMemoryFunctionApi(functions: InMemoryFunctionDef[]): FunctionApi; export {}; //# sourceMappingURL=func-runtime.d.ts.map