agency
Execute Agency source in a child process, inspect module exports and effects, or build source with AST and template helpers. Child operations still consult the parent's interrupt handlers.
import { runCode } from "std::agency"
node main() {
const result = runCode("export node main() { return 42 }")
print(result)
}Types
CompiledProgram
A compiled program returned by compile; retain the full returned value for execution.
/** A compiled program returned by compile; retain the full returned value for execution. */
export type CompiledProgram = {
moduleId: string
}(source)
AgencyModuleSource
An installed standard-library module selected by its std:: import name.
/** An installed standard-library module selected by its std:: import name. */
export type AgencyModuleSource = {
kind: "module";
module: string
}(source)
AgencyFileSource
An Agency file whose local imports remain inside dir.
/** An Agency file whose local imports remain inside dir. */
export type AgencyFileSource = {
kind: "file";
dir: string;
filename: string
}(source)
AgencyTextSource
Source text or a complete Template Agency program, optionally with a local import directory.
/** Source text or a complete Template Agency program, optionally with a local import directory. */
export type AgencyTextSource = {
kind: "source";
source: string | Code;
dir?: string
}(source)
AgencySource
export type AgencySource =
| AgencyModuleSource
| AgencyFileSource
| AgencyTextSource(source)
RunOptions
Subprocess limits and working directory, with the same defaults as run.
/** Subprocess limits and working directory, with the same defaults as run. */
export type RunOptions = {
wallClock?: number;
memory?: number;
ipcPayload?: number;
stdout?: number;
logFile?: string;
cwd?: string;
maxDepth?: number;
maxCost?: number
}(source)
SourceLocation
export type SourceLocation = {
line: number;
col: number;
start: number;
end: number
}(source)
TypeCheckDiagnostic
export type TypeCheckDiagnostic = {
/** Stable AG#### diagnostic code. Suppress one line with
`// @tc-ignore AG####`, or match on it instead of parsing the message. */
code: string;
severity: string;
message: string;
loc?: SourceLocation;
/** Structured payload of the diagnostic (the values rendered into the
message, e.g. the expected and actual type strings; counts and positions
are numbers). */
params: Record<string, string | number>
}(source)
TypeCheckReport
export type TypeCheckReport = {
errors: TypeCheckDiagnostic[];
warnings: TypeCheckDiagnostic[]
}(source)
ProcessInfo
A program started by spawn.
/** A program started by spawn. */
export type ProcessInfo = {
pid: number;
name: string;
outputFile: string
}(source)
InterruptAnswer
export type InterruptAnswer = {
action: "approve" | "reject";
value?: any;
expectedMessage?: string
}(source)
TestArguments
export type TestArguments = Record<string, any>(source)
AgencyTestCase
export type AgencyTestCase = {
node: string;
args?: TestArguments;
expected: any;
interrupts?: InterruptAnswer[];
wallClock?: number;
description?: string
}(source)
CaseReport
export type CaseReport = {
node: string;
pass: boolean;
feedback: string
}(source)
TestReport
export type TestReport = {
pass: boolean;
cases: CaseReport[]
}(source)
EffectsByExport
Per-exported-symbol effect lists, keyed by node/function name.
/** Per-exported-symbol effect lists, keyed by node/function name. */
export type EffectsByExport = Record<string, string[]>(source)
ExportParam
One parameter of an exported def or node.
/** One parameter of an exported def or node. */
export type ExportParam = {
name: string;
/** The declared type, printed the way the signature prints it. Null when none is declared. */
type?: string;
/** The default as Agency source, such as `0` or `null`. Null when the parameter has none. */
default?: string;
/** The text of the docstring's `@param` entry for this parameter, or null. */
description?: string
}(source)
ExportInfo
Metadata for one public export. The signature omits export and tool markers. For functions and nodes, docstring holds the tool description; for types, it holds the doc comment.
Effects use the names and unknown marker returned by getEffects. Types and constants have no effects. A re-export names the outermost module it came through; an unresolved re-export has unknown effects.
/** Metadata for one public export. The signature omits export and tool
markers. For functions and nodes, docstring holds the tool description;
for types, it holds the doc comment.
Effects use the names and unknown marker returned by getEffects. Types
and constants have no effects. A re-export names the outermost module
it came through; an unresolved re-export has unknown effects. */
export type ExportInfo = {
name: string;
kind: "def" | "node" | "type" | "const" | "reexport";
signature: string;
/** The declared return type, printed on its own. Null when none is declared. */
returnType?: string;
/** True when a def or node returns a `Result`, with the module's own aliases resolved. */
returnsResult: boolean;
docstring?: string;
effects: string[];
destructive: boolean;
idempotent: boolean;
handoff: boolean;
reexportedFrom?: string;
/** Each parameter of a def or node; empty for every other kind, and for a re-export that cannot be read from a source string. */
params: ExportParam[]
}(source)
ModuleInfo
export type ModuleInfo = {
description?: string;
exports: ExportInfo[]
}(source)
AST
A parsed Agency program, the value parseAST returns on success. type is always "agencyProgram". nodes holds the top-level declarations (imports, functions, graph nodes, type aliases, ...). Each is an object with a type discriminant field. Its remaining fields vary by node type, so nodes stay untyped.
/** A parsed Agency program, the value `parseAST` returns on success.
`type` is always "agencyProgram". `nodes` holds the top-level
declarations (imports, functions, graph nodes, type aliases, ...). Each
is an object with a `type` discriminant field. Its remaining fields
vary by node type, so nodes stay untyped. */
export type AST = {
type: "agencyProgram";
nodes: any[];
docComment?: any
}(source)
Code
Code is AST plus a fragment kind: a value can hold a whole program (what loadTemplate and parseAST produce), a statement list, or a single expression. The kind is what lets an expression-sized fragment fill an expression hole.
/** `Code` is `AST` plus a fragment kind: a value can hold a whole program
(what `loadTemplate` and `parseAST` produce), a statement list, or a
single expression. The kind is what lets an expression-sized fragment
fill an expression hole. */
export type Code = {
type: "agencyProgram";
kind?: "program" | "statements" | "expr";
nodes: any[];
docComment?: any
}(source)
HoleInfo
export type HoleInfo = {
name: string;
sort: "expr" | "statements" | "identifier" | "decl";
splice: boolean;
type?: string;
origin?: string
}(source)
Effects
std::read
@alwaysUnder(dir)
effect std::read {
dir: string;
filename: string
}(source)
std::write
@alwaysUnder(dir)
effect std::write {
dir: string;
filename: string
}(source)
std::run
effect std::run {
moduleId: string;
node: string;
args: Record<string, any>;
limits: { wallClock: number; memory: number; ipcPayload: number; stdout: number; maxCost: number | null };
cwd: string;
logFile: string;
depth: number;
module: string;
function: string;
trustedModules: string[]
}(source)
std::spawn
@always(dir, filename)
effect std::spawn {
dir: string;
filename: string;
node: string;
args: string[];
policy: Record<string, any>;
maxCost?: number;
maxTime?: number;
messageCount: number;
name: string;
cwd: string;
outputFile: string;
depth: number
}(source)
Constants
CLI_NOT_AVAILABLE
Guidance for environments where the Agency CLI is not installed.
/** Guidance for environments where the Agency CLI is not installed. */
export static const CLI_NOT_AVAILABLE = "The agency command line is not available here. Use the tools instead: typecheck(source) or typecheckFile(dir, filename) for type errors; testFile(dir, filename) to run a .test.json harness (write the files it tests first); runFile(dir, filename, node) to run a program; parseAST, format, describe for source analysis."(source)
Functions
compile
compile(source: string, dir: string = "", strict: boolean = false): ResultCompile Agency source for a later subprocess run. Only std:: and local .agency imports are supported; compile-time splices are refused.
Use runCode to execute source supplied by an LLM in one call. Use compile and run separately when Agency code can retain the full compiled value between calls. Compilation permits standard-library imports and local .agency files inside the given directory. It refuses JS/TS, Node and pkg:: imports, symlinks, and compile-time splices.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| source | string | ||
| dir | string | "" | Resolve and confine local imports within this directory, or leave empty to disallow them. |
| strict | boolean | false | Also reject unresolved names and JavaScript globals outside the sandbox allowlist. |
Returns: Result
Needs: fileRead
(source)
run
run(
compiled: CompiledProgram,
node: string,
args: Record<string, any> = {},
wallClock: number | null = null,
memory: number | null = null,
ipcPayload: number | null = null,
stdout: number | null = null,
logFile: string | null = null,
cwd: string | null = null,
maxDepth: number | null = null,
maxCost: number | null = null,
): ResultExecute a compiled Agency program in a subprocess.
Run a compiled program in a child process. Parent handlers and guards apply to the child, and supported lifecycle callbacks are forwarded. Streaming callbacks are not forwarded. A resource-limit failure reports limit_exceeded. Each execution segment gets its own wall-clock, memory, IPC, and output budget; paused time does not count. The lowest ancestor maxDepth remains in force.
Success carries the subprocess result envelope, including its data value and usage information. Use runCode for just the node's value.
The run interrupt's trustedModules lists the host's compiled files the program loads (see sandbox.trustedModules in agency.json); it is empty for a program that loads none.
The run interrupt's module and function labels describe a prepared call; they do not verify compiled code stored in a checkpoint. Use module-specific approval rules only with trusted saved state. External hosts should verify checkpoint integrity before resuming saved code; see checkpoint integrity.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| compiled | CompiledProgram | The complete value returned by compile, including its captured code. | |
| node | string | The exported entry node to execute. | |
| args | Record<string, any> | {} | Named arguments for the entry node. |
| wallClock | number | null | null | The execution time limit in milliseconds, up to one hour, or null for the default. |
| memory | number | null | null | The V8 heap limit in bytes, up to 4gb, or null for the default. |
| ipcPayload | number | null | null | The limit per IPC message in bytes, up to 1gb, or null for the default. |
| stdout | number | null | null | The combined stdout and stderr limit in bytes, up to 100mb, or null for the default. |
| logFile | string | null | null | An optional statelog JSONL destination for this child run. |
| cwd | string | null | null | The child working directory, or empty for this run's working directory. |
| maxDepth | number | null | null | The subprocess nesting cap, up to ten, also bounded by ancestor caps. |
| maxCost | number | null | null | The child's LLM spend limit in dollars, or null for no additional cost cap. |
Returns: Result
Throws: std::run, std::guard
Needs: fileRead, fileWrite, subprocess
(source)
runFunction
runFunction(
source: AgencySource,
functionName: string,
args: Record<string, any> = {},
options: RunOptions = {},
): ResultCall a public exported Agency function in a fresh subprocess.
Call a public exported def without writing an entry node. The source can name a std:: module, a file inside a directory, or source text or complete Template Agency Code. Local imports must remain inside the directory; the same import restrictions as compile apply. Nodes and handoff functions are not supported.
Each call starts a fresh subprocess with the parent handlers, policies, guards, and supported callbacks. A returned Result passes through unchanged; a plain value becomes a success.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| source | AgencySource | A std:: module, contained Agency file, or complete Agency source program. | |
| functionName | string | The public exported def to call, excluding nodes and handoff functions. | |
| args | Record<string, any> | {} | Named arguments, with ordinary Agency defaults and aliases. |
| options | RunOptions | {} | Per-call resource limits, statelog destination, and working directory. |
Returns: Result
Throws: std::run, std::guard
Needs: fileRead, fileWrite, subprocess
(source)
learn
learn(
source: AgencySource,
names: string[] = [],
namespace: string = "",
options: RunOptions = {},
): Result<any[]>Create callable tools from public exported Agency functions. Module initialization runs during inspection and can pause or fail. The batch fails if any selected def is a handoff, requires a function argument, or lacks a concrete parameter schema.
Creates callable tools with the source functions' descriptions, schemas, aliases, and argument binding. Import preparation captures local source files, so later calls use those bytes. A namespace prefixes advertised names as namespace_exportName.
Learning runs module initialization in a subprocess to inspect tool metadata. That can pause, fail, or be rejected; it does not call the selected bodies. Inspection and each later tool call use the normal run gate and parent handlers. The module and function labels follow the trusted-state rules documented on run; the inspection launch uses the module label with function set to <inspect>, so a module-specific std::run rule can match or refuse it.
The whole batch fails if a selected function is a handoff, needs a required function argument, or lacks a concrete parameter schema. The returned functions are not saved or added to an agent's tool list.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| source | AgencySource | A std:: module, contained Agency file, or complete Agency source program. | |
| names | string[] | [] | Public exported defs to select, or empty for all public defs. |
| namespace | string | "" | An optional prefix using letters, digits, underscores, or hyphens, keeping each full tool name within 64 characters. |
| options | RunOptions | {} | Resource limits, statelog destination, and working directory for inspection and calls. |
Returns: Result<any[]>
Throws: std::run, std::guard
Needs: fileRead, fileWrite, subprocess
(source)
runFile
runFile(
dir: string,
filename: string,
node: string,
args: Record<string, any> = {},
wallClock: number = 60s,
memory: number = 512mb,
ipcPayload: number = 100mb,
stdout: number = 1mb,
maxCost: number | null = null,
): ResultCompile an Agency file and execute its exported node in a subprocess. Only std:: and contained .agency imports are supported.
Compiles a file and runs its exported node through run, with the same parent handlers, guards, callbacks, and subprocess limits. Local imports remain within the supplied directory. The import restrictions on compile apply to the full dependency closure.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| dir | string | The directory containing the file and confining its local imports. | |
| filename | string | A relative Agency filename that stays inside dir. | |
| node | string | The exported entry node to execute. | |
| args | Record<string, any> | {} | Named arguments for the entry node. |
| wallClock | number | 60s | The execution time limit in milliseconds, up to one hour. |
| memory | number | 512mb | The V8 heap limit in bytes, up to 4gb. |
| ipcPayload | number | 100mb | The limit per IPC message in bytes, up to 1gb. |
| stdout | number | 1mb | The combined stdout and stderr limit in bytes, up to 100mb. |
| maxCost | number | null | null | The child's LLM spend limit in dollars, or null for no additional cost cap. |
Returns: Result
Throws: std::run, std::guard
Needs: fileRead, fileWrite, subprocess
(source)
spawn
spawn(
dir: string,
filename: string,
node: string = "main",
args: string[] = [],
policy: Record<string, any> = {},
maxCost: number | null = null,
maxTime: number | null = null,
messages: any[] = [],
name: string = "",
cwd: string | null = null,
outputFile: string | null = null,
): Result<ProcessInfo>Start an Agency file as a separate process and return at once. The process keeps running after this program ends. It has its own approval rules, given here as policy, and its own cost and time limits. A handler around this call approves the start and nothing the process does later. A question the process cannot settle waits for a person, who answers it with agency attach. What the process prints is saved to the output file in the result.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| dir | string | The directory containing the file. | |
| filename | string | The Agency file to run. | |
| node | string | "main" | The node to start. |
| args | string[] | [] | Arguments the program reads with std::args. |
| policy | Record<string, any> | {} | The approval rules the process runs under. The default has no rules. |
| maxCost | number | null | null | The most the process may spend, in dollars, or null to set no limit here. A budget in the program's own agency.json still applies. |
| maxTime | number | null | null | The longest the process may work, in milliseconds, or null to set no limit here. A budget in the program's own agency.json still applies. |
| messages | any[] | [] | A conversation the process's first thread starts with. |
| name | string | "" | The name the process shows in ps. The default is the filename. |
| cwd | string | null | null | The working directory. The default is this program's. |
| outputFile | string | null | null | The file the process's output is saved to. The default is a new file under ~/.agency/spawned. |
Returns: Result<ProcessInfo>
Throws: std::spawn
Needs: fileRead, fileWrite, subprocess, env
(source)
test
test(
dir: string,
filename: string,
cases: AgencyTestCase[],
wallClock: number = 60s,
memory: number = 512mb,
ipcPayload: number = 100mb,
stdout: number = 1mb,
maxCost: number | null = null,
): Result<TestReport>Run test cases against an Agency file in subprocesses and report each case's result. Only std:: and contained .agency imports are supported.
Each case runs in its own child process through run. Parent handlers vote on both the launch and the tested code's interrupts. Scripted interrupt answers add handler votes in order; a parent rejection still wins. Exhausted answers let outer handlers decide. Leftover answers or an expected-message mismatch fail the case.
Compilation errors fail the whole call. A failed value check, rejected interrupt, or per-case resource limit appears in the report and does not stop later cases. The cost cap covers the whole batch and returns a limit_exceeded failure when reached.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| dir | string | The directory containing the tested file and confining local imports. | |
| filename | string | A relative Agency source filename that stays inside dir. | |
| cases | AgencyTestCase[] | Exported entry nodes, named arguments, expected values, and optional scripted interrupt answers. | |
| wallClock | number | 60s | Milliseconds per case, overridden by a case's own wallClock value. |
| memory | number | 512mb | The V8 heap limit per case in bytes. |
| ipcPayload | number | 100mb | The byte limit per IPC message in each case. |
| stdout | number | 1mb | The combined stdout and stderr limit per case in bytes. |
| maxCost | number | null | null | The LLM spend limit in dollars for the whole batch, or null for no additional cost cap. |
Returns: Result<TestReport>
Throws: std::guard, std::run
Needs: fileRead, fileWrite, subprocess
(source)
testFile
testFile(
dir: string,
filename: string,
maxCost: number | null = null,
): Result<TestReport>Run the test cases declared in an Agency .test.json file.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| dir | string | The directory containing the test file and its source file. | |
| filename | string | A relative .test.json filename that stays inside dir. | |
| maxCost | number | null | null | The LLM spend limit in dollars for the whole batch, or null for no additional cost cap. |
Returns: Result<TestReport>
Throws: std::read, std::guard, std::run
Needs: fileRead, fileWrite, subprocess
(source)
runCode
runCode(
source: string,
node: string = "main",
args: Record<string, any> = {},
wallClock: number = 60s,
memory: number = 512mb,
ipcPayload: number = 100mb,
stdout: number = 1mb,
maxCost: number | null = null,
cwd: string = "",
dir: string = "",
): ResultCompile Agency source and execute an exported node in one call. Prefer this over separate compile and run calls. Only std:: and contained .agency imports are supported; splices are refused. Compile errors come back as a failure without running anything; fix the source and call again.
Use this when an LLM supplies source code to execute. It combines compilation and execution so the model does not need to copy a compiled program value into another call. The node's value is returned without the subprocess envelope.
Parent handlers, guards, and supported callbacks apply as in run. A compile error returns a failure before execution. The full import closure follows compile restrictions. cwd controls runtime file operations; dir separately controls local import resolution.
The function is unmarked because arbitrary supplied code determines whether retrying is appropriate. Each new attempt raises the run gate and the child's own effects again.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| source | string | ||
| node | string | "main" | The exported entry node to execute. |
| args | Record<string, any> | {} | Named arguments for the entry node. |
| wallClock | number | 60s | A positive execution time limit in milliseconds, up to one hour. |
| memory | number | 512mb | A positive V8 heap limit in bytes, up to 4gb. |
| ipcPayload | number | 100mb | A positive byte limit per IPC message, up to 1gb. |
| stdout | number | 1mb | A positive combined stdout and stderr byte limit, up to 100mb. |
| maxCost | number | null | null | The child's LLM spend limit in dollars, or null for no additional cost cap. |
| cwd | string | "" | The runtime working directory. Empty means this run's working directory, which may not be where you want files; pass the agent working directory so the program's file writes land there. |
| dir | string | "" | Resolve and confine local imports within this directory, or leave empty to disallow them. |
Returns: Result
Throws: std::run, std::guard
Needs: fileRead, fileWrite, subprocess
(source)
typecheck
typecheck(
source: string,
ignoreCodes: string[] = [],
dir: string = "",
strict: boolean = false,
): Result<TypeCheckReport>Type-check Agency source and return errors and warnings. To check a file already on disk, call typecheckFile with its path instead of pasting its contents. A clean report does not mean compile or run will accept the code unless strict is true.
Checks source text without writing it. With a directory, relative imports resolve as if the source were a file there. Use typecheckFile for an existing file.
A normal check can accept imports that subprocess compilation refuses. Enable strict checking to apply the sandbox import and bound-name checks before trying to run generated code.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| source | string | ||
| ignoreCodes | string[] | [] | Diagnostic codes, such as AG3009, to omit from errors and warnings. |
| dir | string | "" | Resolve relative imports within this directory, or leave empty when no local imports are needed. |
| strict | boolean | false | Also report sandbox import violations, unresolved names, and disallowed JavaScript globals. |
Returns: Result<TypeCheckReport>
Needs: fileRead
(source)
getEffects
getEffects(source: string): Result<EffectsByExport>List the interrupt effects each exported function or node can raise. Dynamic calls can escape the analysis, so an empty list does not prove that execution has no effects.
Includes effects propagated through statically known calls. Bare interrupts appear as unknown. Compile-time generated code, functions received as parameters, and function references passed through variables can escape the analysis. Use this to inspect a program, with those limits in mind.
Parameters:
| Name | Type | Default |
|---|---|---|
| source | string |
Returns: Result<EffectsByExport>
Needs: fileRead
(source)
describe
describe(
source: string,
dir: string = "",
filename: string = "",
): Result<ModuleInfo>Describe an Agency module's public exports, signatures, documentation, and statically known effects.
Use export metadata when generating code from a module, for example one handler per effect its tools can raise. It uses the visibility rules of agency doc: hidden and underscore-prefixed exports are omitted. The description is the module's one-line summary.
For a module with local imports, supply its directory and filename along with the file's exact source text. The import closure is checked under the same restrictions as compilation. Imported source is read to compute metadata without a separate read interrupt. Relative re-exports remain entries with unknown effects; std:: re-exports resolve to full entries.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| source | string | Module source text matching the file exactly when a filename is supplied. | |
| dir | string | "" | Supply with filename to resolve local imports within this directory. |
| filename | string | "" | The module's path relative to dir, or empty when describing source without local imports. |
Returns: Result<ModuleInfo>
Needs: fileRead
(source)
typecheckFile
typecheckFile(dir: string, filename: string): Result raises <std::read>Type-check an Agency file on disk.
Resolves imports relative to the file's own directory. This check does not apply subprocess import restrictions, so a clean report can still be refused by runFile.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| dir | string | ||
| filename | string | A relative Agency filename that stays inside dir. |
Returns: Result
Throws: std::read
Needs: fileRead
(source)
parseAST
parseAST(source: string): Result<AST>Parse Agency source into an abstract syntax tree.
Parameters:
| Name | Type | Default |
|---|---|---|
| source | string |
Returns: Result<AST>
(source)
writeAST
writeAST(
ast: AST,
dir: string,
filename: string,
overwrite: boolean = true,
): Result raises <std::write>Format an Agency AST as source and write it to a file.
Writes the canonical formatter output, preserving comments while normalizing whitespace. The target must stay inside the supplied directory; symlinks below that directory are refused.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| ast | AST | ||
| dir | string | ||
| filename | string | A relative output filename that stays inside dir. | |
| overwrite | boolean | true | If false, fail when the output file already exists. |
Returns: Result
Throws: std::write
Needs: fileRead, fileWrite
(source)
format
format(source: string): ResultFormat Agency source with the standard Agency formatter.
Parameters:
| Name | Type | Default |
|---|---|---|
| source | string |
Returns: Result
(source)
loadTemplate
loadTemplate(dir: string, filename: string): Result<Code> raises <std::read>Read an Agency file containing template holes.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| dir | string | ||
| filename | string | A relative template filename that stays inside dir. |
Returns: Result<Code>
Throws: std::read
Needs: fileRead
(source)
holesOf
holesOf(template: Code): HoleInfo[]List the unfilled holes in an Agency code template.
Inspect remaining holes before filling a template. Each name appears once, in encounter order. The origin identifies the fill through which a grafted hole arrived when known; original holes have no origin.
Parameters:
| Name | Type | Default |
|---|---|---|
| template | Code |
Returns: HoleInfo[]
(source)
fill
fill(template: Code, values: Record<string, Json | Code>): Result<Code>Fill selected holes in an Agency code template.
Plain values become literal nodes; Code fragments are inserted as trees. String values are not parsed as source. A partial fill returns a template whose remaining holes can be filled later.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| template | Code | ||
| values | Record<string, Json | Code> | Map existing hole names to literal data or Code fragments of the required kind. |
Returns: Result<Code>
(source)
combine
combine(codes: Code[]): Result<Code>Combine Agency code fragments in order. Whole programs cannot be mixed with loose statements or expressions.
Use this when generating one fragment per item, then joining the results. Fragments of the same kind retain that kind; expressions combine into a statement list. Whole programs cannot combine with loose expressions or statements.
Parameters:
| Name | Type | Default |
|---|---|---|
| codes | Code[] |
Returns: Result<Code>
(source)
toSource
toSource(code: Code): stringPrint Agency Code as source, preserving any unfilled template holes.
Parameters:
| Name | Type | Default |
|---|---|---|
| code | Code |
Returns: string
(source)
parseExpr
parseExpr(source: string): Result<Code>Parse exactly one Agency expression into a Code fragment for an expression hole.
Parameters:
| Name | Type | Default |
|---|---|---|
| source | string |
Returns: Result<Code>
(source)
parseStatements
parseStatements(source: string): Result<Code>Parse Agency statements into a Code fragment for a statements hole.
Parameters:
| Name | Type | Default |
|---|---|---|
| source | string |
Returns: Result<Code>
(source)
formatFile
formatFile(dir: string, filename: string): Result raises <std::write>Format an Agency file in place.
Read and write happen inside the same interrupt, so approving it approves both. If the file is already formatted, no write occurs and its mtime is preserved.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| dir | string | ||
| filename | string | A relative Agency filename that stays inside dir. |
Returns: Result
Throws: std::write
Needs: fileRead, fileWrite
(source)
walkAST
walkAST(ast: AST, visitor: (node: any, ancestors: any[]) -> any): ASTVisit and modify nodes in a cloned Agency AST.
Visits parents before children in a deep-cloned tree. Mutate each visited node in place to transform the returned clone. The original tree is unchanged.
The visit list is fixed before callbacks run: added nodes are not visited, and replacing a child reference does not remove the old subtree from that list. Ancestors run from the root to the parent, excluding the visited node.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| ast | AST | ||
| visitor | (node: any, ancestors: any[]) => any | Called with the node and its ancestors, allowing in-place edits and ignoring the return value. |
Returns: AST
(source)
getNodesOfType
getNodesOfType(source: string, types: string[]): Result<any[]>Parse Agency source and find AST nodes matching the requested kinds.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| source | string | ||
| types | string[] | AST discriminants such as "function", "graphNode", or "importStatement". |
Returns: Result<any[]>
(source)
getImports
getImports(source: string): Result<any[]>Find import statements in Agency source.
Parameters:
| Name | Type | Default |
|---|---|---|
| source | string |
Returns: Result<any[]>
(source)
getFunctions
getFunctions(source: string): Result<any[]>Find function definitions in Agency source.
Parameters:
| Name | Type | Default |
|---|---|---|
| source | string |
Returns: Result<any[]>
(source)
getGraphNodes
getGraphNodes(source: string): Result<any[]>Find graph node definitions in Agency source.
Parameters:
| Name | Type | Default |
|---|---|---|
| source | string |
Returns: Result<any[]>
(source)
filterImports
filterImports(
source: string,
allowedPackages: string[] = [],
excludedPackages: string[] = [],
allowKinds: string[] = [],
excludeKinds: string[] = [],
): Result<{ source: string; filtered: boolean }>Remove imports that fail the supplied allow and exclude rules. Excludes win; empty rule lists permit every import.
Use to remove unwanted imports from generated source before further checking. This only filters import statements; it does not validate the remaining dependency closure. The returned source is formatted.
Import kinds are stdlib for std:: paths, pkg for pkg:: paths, local for file paths, and node for bare Node specifiers. Package patterns use picomatch syntax against the original import path. Excludes always win. With no allow rules, remaining imports pass. Otherwise an allowed kind or an allowed path pattern is enough to retain an import.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| source | string | ||
| allowedPackages | string[] | [] | Import-path globs to retain, unless an exclude rule matches. |
| excludedPackages | string[] | [] | Import-path globs to remove even when allowed elsewhere. |
| allowKinds | string[] | [] | Retain imports of kind stdlib, pkg, local, or node. |
| excludeKinds | string[] | [] | Remove imports of these kinds even when allowed elsewhere. |
Returns: Result<{ source: string; filtered: boolean }>
(source)
getVersion
getVersion(): stringGet the current version of the Agency standard library.
Returns: string
(source)
cliHandles
cliHandles(subcommand: string): booleanCheck whether the in-process Agency command helper supports a subcommand.
Parameters:
| Name | Type | Default |
|---|---|---|
| subcommand | string |
Returns: boolean
(source)
cli
cli(args: string[], cwd: string = "."): Result<ExecResult>Run a supported Agency file command and return stdout, stderr, and exitCode.
Runs supported file commands through the matching functions in this module, without spawning an installed Agency CLI. Supports test, typecheck/tc, ast, fmt, and run. The run command selects node main. The fmt command returns formatted source without writing it back. Use the underlying functions when you need flags or other options.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| args | string[] | Exactly a supported subcommand and filename, such as ["test", "x.test.json"]. | |
| cwd | string | "." | The directory containing the file argument. |
Returns: Result<ExecResult>
Throws: std::read, std::guard, std::run
Needs: fileRead, fileWrite, subprocess
(source)