import { AgencyProgram } from "../types.js";
import { AgencyConfig } from "../config.js";
import type { TsNode } from "../ir/tsIR.js";
import type { CompilationUnit } from "../compilationUnit.js";
export declare class TypeScriptBuilder {
    private generatedStatements;
    private generatedTypeAliases;
    /**
     * TypeAlias AST nodes whose declaration has been hoisted to the
     * containing function/node's outer scope (so it's visible to every
     * runner.step closure). When processNode sees one of these inside a
     * body, it returns ts.empty() to avoid a redeclaration.
     */
    private hoistedTypeAliasNodes;
    private importStatements;
    private toolRegistrations;
    private functionsUsed;
    private scopes;
    private steps;
    private names;
    private pipes;
    private assigns;
    private agencyConfig;
    private adjacentNodes;
    private currentAdjacentNodes;
    private isInsideGraphNode;
    private loopVars;
    private insideHandlerBody;
    private insideGlobalInit;
    private _asyncBranchCheckNeeded;
    private _sourceMapBuilder;
    private compilationUnit;
    private moduleId;
    private outputFile;
    /**
     * Optional per-module init plan + cross-module alias resolver produced
     * by `compileClosure`. When present, drives:
     *   - the order of local static/global assignments (topsort-ordered
     *     rather than source-ordered), and
     *   - the per-phase `await __awaitStaticInit(...)` /
     *     `__awaitGlobalsInit(...)` prelude emitted in this module's
     *     init functions, and
     *   - the PR-1 trap message: `__readStatic` is called with the
     *     SOURCE moduleId of an imported binding, not the placeholder
     *     "<unknown module>" used before.
     *
     * When absent (callers that haven't migrated to compileClosure, or
     * single-file unit tests), codegen falls back to source order and
     * omits the cross-module awaits — the lazy per-function
     * `isInitialized` guards plus the runtime trap remain the safety net.
     */
    private initPlan?;
    /**
     * @param config - Agency compiler configuration (model defaults, logging, etc.)
     * @param info - Pre-collected program metadata (function definitions, graph nodes, imports, type hints)
     * @param moduleId - Unique identifier for this module (e.g., "foo.agency"), used to
     *   namespace global variables in the GlobalStore so that different modules' globals
     *   don't collide. Must be consistent between the defining module and any importers.
     * @param outputFile - Absolute path where the generated code will be written.
     *   Used to compute relative import paths for stdlib. If not provided, falls
     *   back to resolving moduleId against cwd.
     * @param initPlan - Optional per-module init plan + resolver from
     *   `compileClosure`. See the field docstring above.
     */
    constructor(config: AgencyConfig | undefined, info: CompilationUnit, moduleId: string, outputFile?: string, initPlan?: TypeScriptBuilder["initPlan"]);
    private configDefaults;
    /** Convert a TsNode to string (for use in template-based methods) */
    private str;
    /** Returns the template opts for checkpoint creation (moduleId, scopeName, stepPath as JSON-quoted strings). */
    private checkpointOpts;
    private forkBranchSetup;
    /** Generate a TsNode for `hasInterrupts(x)` */
    private interruptCheck;
    /** Generate a raw string for `hasInterrupts(x)` */
    private interruptCheckRaw;
    private agencyFileToDefaultImportName;
    private needsParensLeft;
    private needsParensRight;
    build(program: AgencyProgram): TsNode;
    /** Process a function call argument, unwrapping NamedArgument and SplatExpression. */
    private processCallArg;
    /** Process resolved arguments into TsNodes, tracking function usage. */
    private processResolvedArgs;
    /**
     * Adjust call-site arguments to match the function's parameter list:
     * 1. Pad omitted optional args (those with defaults) with null
     * 2. Wrap extra args into an array for variadic params
     */
    private processNode;
    private processKeyword;
    /**
     * Walk a function/node body and collect every typeAlias declaration
     * that belongs to this body's scope. Used to hoist body-local type
     * aliases up to the enclosing function/node's outer scope so the
     * generated zod schemas are visible to every runner.step closure.
     *
     * Delegates body recursion to `walkNodes` so any new body-bearing
     * AST node (thread, parallelBlock, seqBlock, …) is automatically
     * handled. Aliases nested inside a function/graphNode/class method
     * are skipped — those defs hoist their own aliases when their bodies
     * are built.
     */
    private collectBodyTypeAliases;
    /**
     * Hoist body-local type aliases. Returns the generated TS declarations
     * (to be inserted at the top of the enclosing function/node body) and
     * marks each AST node so processNode skips its in-body emission.
     *
     * Coalesces duplicates by alias name: if the same name appears in
     * multiple branches/blocks, only the first declaration is emitted to
     * avoid redeclaration errors at the function scope. (The Agency
     * typechecker is responsible for diagnosing genuine name collisions.)
     */
    private hoistBodyTypeAliases;
    private processTypeAlias;
    /**
     * Build a zod validation schema string for a VariableType taken from user
     * source. Deep-resolves user-defined generic aliases first so that uses
     * like `Container<number>` become a concrete object/array/etc. before the
     * (alias-unaware) zod mapper runs.
     */
    private zodSchemaFor;
    /**
     * Build the validation expression for a `!` site. If the resolved type
     * carries no `@validate(...)` tag anywhere, return the existing
     * `__validateType(value, schema)` call (zero behavior change). Otherwise
     * return `await __validateChainRecursive(value, <descriptor>, __ctx)`,
     * which runs Zod parse + the validator chain at each level.
     */
    private validateExpr;
    private processComment;
    private processAgencyObject;
    private processAgencyArray;
    private generateLiteral;
    private generateStringLiteralNode;
    private processValueAccess;
    private awaitChainCall;
    private processBinOpExpression;
    private processRegexMatchExpression;
    private processCatchExpression;
    private processPipeExpression;
    private processTryExpression;
    private processNewExpression;
    private processSchemaExpression;
    /**
     * After the ALS migration AND the trailing-`state`-arg drop, every
     * Agency call site reads `ctx` / `stack` / `threads` / `callsite`
     * from the active `agencyStore` frame. `__call` / `__callMethod` no
     * longer accept a state-extras object, and the codegen never emits
     * one. This helper is kept as a stable seam in case future codegen
     * needs to attach per-call metadata, but for now it always returns
     * `undefined` — callers should simply omit the third positional.
     *
     * Async-fork sites that need to override the active branch stack
     * wrap their `__call(...)` invocation in an `agencyStore.run`
     * frame in codegen (see `emitRuntimeDispatchCall`) — not via this
     * helper.
     */
    private buildStateConfig;
    private processIfElseWithSteps;
    private processForLoopWithSteps;
    private processWhileLoopWithSteps;
    private processMatchBlockWithSteps;
    private processImportStatement;
    private processImportNodeStatement;
    /**
     * Process a block argument into a wrapped AgencyFunction TsNode.
     * Shared by generateFunctionCallExpression and buildCallDescriptor.
     */
    private processBlockArgument;
    /**
     * Compile a BlockArgument that appears as a standalone expression
     * (e.g. as a named arg value in .partial(), or assigned to a variable).
     * Uses type annotations on the block params if present, falls back to 'any'.
     */
    private processBlockAsExpression;
    /**
     * Build a tool definition TsNode for an Agency function.
     * Returns ts.id("null") if the function has no parameters (no schema needed for tools).
     */
    private buildToolDefinition;
    /**
     * Returns true if any function or graph node in the compilation unit
     * has a doc string with at least one interpolation segment.
     */
    private hasDocStringInterpolation;
    /**
     * Generate __toolRegistry as an empty object. AgencyFunction.create() calls
     * register local functions into it. Imported and builtin tools are registered
     * here directly. The reviver is bound at the end.
     */
    private generateToolRegistry;
    /**
     * For Result-returning functions: emit a pinned checkpoint at function entry
     * and a preamble that applies arg overrides on restore (for result.retry()).
     */
    private buildResultCheckpointSetup;
    /**
     * Build the body statements for an Agency function or class method.
     * Includes setup, runner, result checkpoint, try/catch/finally, hooks.
     * Shared between processFunctionDefinition and class method compilation.
     */
    private buildFunctionBody;
    private processFunctionDefinition;
    private processStatement;
    private interruptTemplateArgs;
    private buildInterruptReturnStructured;
    private extractInterruptFields;
    private isInterruptExpression;
    private processInterruptStatement;
    private processFunctionCallAsStatement;
    private processFunctionCall;
    private generateFunctionCallExpression;
    private emitRuntimeDispatchCall;
    /**
     * Emit a plain direct function call: `f(arg1, arg2, blockArg?)`.
     * Context-injected builtins reuse this with `prependArgs =
     * [__ctx]`; the registry lookup at the call site is what marks the
     * intent, no separate method needed.
     */
    private emitDirectFunctionCall;
    /**
     * Build a CallType descriptor TsNode for an Agency function call.
     * Determines whether to emit positional or named call type based on arguments.
     */
    private buildCallDescriptor;
    private processForkCall;
    private generateNodeCallExpression;
    private processGraphNode;
    /** If the enclosing function/node has returnTypeValidated, wrap value in __validateType */
    private maybeWrapReturnValidation;
    private processGotoStatement;
    private processReturnStatement;
    private processAssignment;
    private _processAssignmentInner;
    /**
     * Process an llm() function call. Generates a direct runPrompt() call
     * (no inner function wrapper). Handles async/sync, interrupt checking,
     * response format from type hints, and tools from config object.
     */
    private processLlmCall;
    private processDebuggerStatement;
    private processMessageThread;
    private processBlockPlain;
    /**
     * Compile the synthetic `__objectRest(source, ["a", "b", ...])` call emitted
     * by the pattern lowering pass for `let { a, b, ...rest } = obj` into a
     * native-JS IIFE. No runtime helper required.
     *
     *   __objectRest(source, ["a", "b"])
     *   → (({ a: __k0, b: __k1, ...__r }) => __r)(<resolved source>)
     *
     * For `let { ...rest } = obj` (no excluded keys), emits
     *   (({ ...__r }) => __r)(<resolved source>)
     */
    private buildObjectRestIIFE;
    private processNodeInGlobalInit;
    private buildHandlerArrow;
    private processHandleBlockWithSteps;
    private processWithModifier;
    /** In debugger mode, insert debuggerStatement nodes before each
     *  step-triggering statement so that debugStep() is called at every
     *  substep boundary, not just top-level steps. */
    private insertDebugSteps;
    private processBodyAsParts;
    private generateBuiltins;
    private generateImports;
    private preprocess;
    private postprocess;
}
