microfoom

@microfoom/core

@microfoom/core

@microfoom/core — typed building blocks for coordination engineering: coordination a single prompt can't express. Your TypeScript owns the control flow; the model is invoked only for the genuinely fuzzy parts.

Write a program by extending Program and driving this.agent (AgentRun: do / prose / value); expose methods to the agent with foom; run it with runProgram. Failures surface as the FoomtimeError taxonomy.

Classes

ClassDescription
FoomtimeAbortErrorRun ended early.
FoomtimeBudgetExceededErrorExceeded maxBudgetUsd.
FoomtimeCallDepthErrorExceeded maxCallDepth.
FoomtimeCancelledErrorAborted via signal / .abort().
FoomtimeConcurrencyErrorOverlapping turns on one session — a programming error, not repairable/retryable.
FoomtimeConfigErrorBad config (no such model, invalid thinking, unenforceable cap, ...).
FoomtimeDispatchErrorAn exposed method has no callable implementation on the program instance — contradictory program state (a defect), not an agent-repairable miss, so it fails fast rather than entering the repair loop. A call to an unexposed method is repairable and is handled in-band (see the header note); it never reaches here.
FoomtimeErrorBase for the whole taxonomy. Each subclass reports its own class name.
FoomtimeHarnessErrorThe harness (or its backend) failed to fulfill a turn. foomtime runs inside the harness and delegates turns to it, so this is the boundary-failure class — origin (provider vs harness internals) is often indistinguishable from here.
FoomtimeHarnessRejectedErrorNon-transient: permission denied, model not allowed, context overflow, content filtered.
FoomtimeHarnessUnavailableErrorTransient: harness disconnected, model 5xx, rate-limited. Safe to retry.
FoomtimeInputError/run input failed the program's input schema.
FoomtimeProgramThe program base class. Extend via Program(schema) for a typed input.
FoomtimeRepairExhaustedErrorThe repair loop gave up after repairAttempts consecutive invalid attempts. channel names the fault: "args" (bad foom_call arguments), "return" (a foom_return value that failed its schema, or a turn that never returned), or "dispatch" (a call to an unexposed method).
FoomtimeThrowErrorRaised ONLY by a deliberate foom_throw in a prompt. ALWAYS carries the user-defined code from foom_throw (the caller's namespace, e.g. "123" / "E_TOO_LOW"); it has no runtime meaning. Runtime-caught failures are FoomtimeRepairExhaustedError, NOT this — they have no code.
FoomtimeTimeoutErrorExceeded maxTurnDuration (turn) or maxProgramDuration (program).
FoomtimeTokenLimitExceededErrorExceeded maxOutputTokens.

Interfaces

InterfaceDescription
AgentCancellationPer-call cancellation.
AgentConfigScoped agent configuration. Every field optional; absence means "inherit".
AgentDecoratorsThe module-level decorator namespace.
AgentExposeOptionsExposure options. Three tiers by context cost (F3): bare (silent), { announcement } (named in the system prompt), { tool } (native tool with full param schema upfront).
AgentProgramContextPer-instance run context, injected as this.agent. Stateless text/value.
AgentResultThe awaitable result of an agent turn. Awaiting yields the value; abort() cancels an in-flight run (the awaiter then rejects with FoomtimeCancelledError). An un-awaited result self-handles its own cancellation rejection, so abort() never surfaces an unhandledRejection.
AgentRunThe output modes available wherever prompts run: act (do), prose, value.
AgentRuntimeHooksPer-call runtime hooks (not part of the inheritable config cascade).
AgentSessionA stateful conversation (shared transcript). Single-flight; fork() to branch.
AgentTextStreamA streaming text result. for await yields chunks; awaiting resolves to the full joined message (chunks are buffered and replayed even after iterating).
AgentToolOptionsStructured tool advertisement — the value of @foom.expose({ tool }).
AgentTurnMetaPer-call display metadata.
AgentUsageCumulative usage, as read by a consumer. A live sync snapshot — grows as turns settle, final once the run/session/turn ends. Optional fields are absent when the provider does not report them; costUsd is absent when pricing is underivable (and then a cost cap fails fast at setup — F5).
DerivedParametersThe derived parameter schema for one method.
FoomtimeErrorOptionsOptions accepted by every Foomtime error: an underlying cause and free-form data.
HarnessSessionThe PUBLIC harness contract (F6). A session runs one model turn: it drives the model, executes the supplied tools (calling their execute), and resolves when the turn settles (a tool signalled terminate, or the model produced no tool call). Signal failures by throwing FoomtimeHarnessError subclasses; honor request.signal.
HarnessSessionOptionsA harness opens one session per program run, given the run's model + caps.
NeutralToolDefA tool the harness advertises and executes. Core owns execute (the semantics).
RunProgramOptionsOptions for running a program: the harness registry, model, source.
SessionTurnRequestOne model turn for the harness to run: prompt + the tools it may call.
SessionTurnResultWhat the harness reports back once a turn settles.
ToolExecResultResult of executing one tool call, returned to the harness loop.
UsageDeltaRaw per-turn usage reported by the harness; folded into the usage Monoid.

Type Aliases

Type AliasDescription
AgentClassDecoratorA decorator usable on a class.
AgentConfigDecorator@foom.config(options) — set agent config on a class or a method. On a class it is the widest scope of the cascade (AgentConfig); on a method it applies whenever that method's body runs an agent turn. Narrower scopes win.
AgentDecoratorUsable on either a class or a method.
AgentDoTemplateAn act turn — do the work (via tools), return nothing. The cheap default for instructions whose payload you don't need (no schema, no final prose).
AgentExposeDecorator@foom.expose (bare) or @foom.expose(options) — make a method agent-callable via foom_call. Methods are unreachable by default (F3). Three tiers by context cost (see AgentExposeOptions): bare = silent, { announcement } = named in the prompt, { tool } = full native tool. Private (#) members can never be exposed.
AgentMethodDecoratorA decorator usable on a method.
AgentOptionsEverything accepted at a call/scope: cascading config plus per-call extras.
AgentProseTemplateA streaming prose turn from a template literal — freeform natural language. Awaiting yields the full message; for await streams chunks.
AgentValueTemplateA structured-value turn: pass a Standard Schema, then tag a template literal. The agent must foom_return a value; it is validated against the schema and the awaited result is typed as the schema's output.
ControlToolName-
DurationA wall-clock duration literal: seconds, minutes, or hours.
JsonSchemaA JSON Schema object advertised to the model (derived, not authored — ADR-0003).
LLMTokenA streamed token, surfaced to the onToken hook.
OpenSessionFactory the runner calls to open a session for a program run.
RepairChannelWhich repairable agent fault exhausted the repair loop.
StreamEventIncremental output during a turn. text/reasoning are token deltas (surfaced to onToken). The rest carry transcript structure a harness observes from its model loop — assistant message boundaries and the tool calls it made — so a frontend can show the live conversation. A harness emits what it can; a minimal one emits only text.
SystemPromptSystem-prompt contribution for one scope. Exactly one of append / replace: append accumulates onto the inherited prompt; replace discards everything from wider scopes and becomes the new base.
ThinkingLevelReasoning effort. Known levels plus provider-passthrough raw strings.

Variables

VariableDescription
CONTROL_TOOLSReserved native tool names for the control operations.
CORE_VERSIONThe version of @microfoom/core this build was published at.
foomThe microfoom decorator namespace. `foom.config` sets agent config on a class or method; `foom.expose` makes a method agent-callable. Both run at class-definition time and only record metadata — they never run prompts.

Functions

FunctionDescription
attachContextInternal: the runner wires this.agent after constructing a program.
deriveMethodParametersDerive the parameter schema of className.methodName declared in filePath.
deriveProgramInputDerive the input schema of a program's main from its export default class (named or anonymous). Used to advertise a program as an agent tool: the result is an object schema keyed by main's single parameter name.
durationToMsParse a Duration literal to milliseconds. Returns undefined for a malformed string so callers can reject it through the typed error channel rather than trusting a silent NaN.
isControlToolTrue when a tool name is one of the reserved control operations.
makeStandardSchemaBuild a Standard Schema from a plain validate function. Used by the parameter derivation (ADR-0003) to package a derived validator and by tests; keeps the ~standard shape in one place.
mergeConfigMerge a wider scope's config with a narrower one. Associative, so folding a chain in either grouping yields the same result (Q6). Pure and total.
mergeConfigChainFold a widest-to-narrowest chain of scopes into one effective config.
ProgramName an input schema, then extends Program(Input); main(input) is typed from it. The return type is taken from your main (inferred by runProgram), so the common case needs no type arguments at all — just extends Program(schema).
runProgram-

On this page