Agent API
The agent API is exported from @flue/runtime.
import {
ResultUnavailableError,
Type,
connectMcpServer,
createAgent,
defineAgentProfile,
defineTool,
type AgentCreateContext,
type AgentHarnessOptions,
type AgentProfile,
type AgentRuntimeConfig,
type BashFactory,
type CallHandle,
type CompactionConfig,
type CreatedAgent,
type FileStat,
type FlueContext,
type FlueFs,
type FlueHarness,
type FlueSession,
type FlueSessions,
type McpServerConnection,
type McpServerOptions,
type PromptImage,
type PromptModel,
type PromptOptions,
type PromptResponse,
type PromptResultResponse,
type PromptUsage,
type SandboxFactory,
type SessionStore,
type ShellOptions,
type ShellResult,
type Skill,
type SkillOptions,
type SkillReference,
type TaskOptions,
type ThinkingLevel,
type ToolDefinition,
type ToolParameters,
} from '@flue/runtime';
defineAgentProfile(...)
function defineAgentProfile(profile: AgentProfile): AgentProfile;
Validates and returns a reusable agent profile. Use profiles as the baseline for a created agent or as named subagents available to session.task().
Throws when the profile contains unknown fields, invalid capabilities, duplicate capability names, or circular subagents.
AgentProfile
| Field | Type | Description |
|---|---|---|
name | string | Profile name. Required when selecting this profile with session.task(). |
model | string | false | Default model specifier. Set to false to require call-level model selection. |
instructions | string | Instructions prepended to discovered workspace context. |
skills | Skill[] | Registered skills available to initialized sessions. |
tools | ToolDefinition[] | Custom model-callable tools available to initialized sessions. |
subagents | AgentProfile[] | Named profiles available for delegated session.task() operations. |
thinkingLevel | ThinkingLevel | Default reasoning effort. Individual operations may override this value. |
compaction | false | CompactionConfig | Automatic conversation-compaction configuration. false disables threshold compaction; overflow recovery and explicit session.compact() calls still compact when needed. |
CompactionConfig
| Field | Type | Default | Description |
|---|---|---|---|
reserveTokens | number | model-aware; capped at 20000 | Token headroom reserved before automatic compaction. Smaller model output limits and small context windows reduce this default. |
keepRecentTokens | number | 8000 | Recent tokens preserved unsummarized after compaction. |
model | string | session model | Model specifier override used for compaction summaries. |
Skill
type Skill =
| SkillReference
| {
name: string;
description: string;
};
Skill metadata registered with an agent, harness, or profile. Imported SkillReference values bundle application-owned skill content. Inline metadata adds only a named catalog entry; it does not package or inject an instruction body. Initialization rejects a registered skill whose name collides with a workspace-discovered skill. See Skills.
defineTool(...)
function defineTool<TParams extends ToolParameters>(
tool: ToolDefinition<TParams>,
): ToolDefinition<TParams>;
Validates a custom model-callable tool and returns a shallow-frozen copy.
This validates the required definition fields. Tool names are checked for collisions with other active tools when a session assembles its tool list.
ToolDefinition
| Field | Type | Description |
|---|---|---|
name | string | Tool name. Must be unique across active built-in and custom tools. |
description | string | Tells the model when and how to use this tool. |
parameters | ToolParameters | JSON Schema-compatible parameter schema. |
execute | (args: Record<string, any>, signal?: AbortSignal) => Promise<string> | Returns text sent back to the model. Thrown errors become tool errors. |
Type is re-exported from @flue/runtime for constructing JSON Schema-compatible parameters.
const lookupPolicy = defineTool({
name: 'lookup_policy',
description: 'Read one approved policy by topic.',
parameters: Type.Object({ topic: Type.String() }),
execute: async ({ topic }) => readPolicy(String(topic)),
});
connectMcpServer(...)
function connectMcpServer(name: string, options: McpServerOptions): Promise<McpServerConnection>;
Connects to a remote MCP server and adapts its listed tools into ordinary Flue tool definitions.
Adapted tool names use mcp__<server>__<tool>. Unsupported characters are replaced with underscores, and duplicate adapted names are rejected. Close the returned connection when its tools are no longer needed.
McpServerOptions
| Field | Type | Default | Description |
|---|---|---|---|
url | string | URL | — | MCP server endpoint. |
transport | 'streamable-http' | 'sse' | 'streamable-http' | Remote MCP transport. Use 'sse' for legacy servers. |
headers | HeadersInit | — | Headers merged into MCP transport requests. |
requestInit | RequestInit | — | Additional MCP transport request configuration. |
fetch | typeof fetch | — | Custom fetch implementation used by the MCP transport. |
clientName | string | 'flue' | MCP client name. |
clientVersion | string | '0.0.0' | MCP client version. |
McpServerConnection
interface McpServerConnection {
name: string;
tools: ToolDefinition[];
close(): Promise<void>;
}
| Field | Description |
|---|---|
name | Server name supplied to connectMcpServer(). |
tools | MCP tools adapted into ordinary Flue tool definitions. |
close() | Close the underlying MCP client connection. |
createAgent(...)
function createAgent<TPayload = unknown, TEnv = Record<string, any>>(
initialize: (
context: AgentCreateContext<TPayload, TEnv>,
) => AgentRuntimeConfig | Promise<AgentRuntimeConfig>,
): CreatedAgent<TPayload, TEnv>;
Creates an agent initializer. Default-export the returned value from an agents/<name>.ts module to define an addressable agent, or pass it to ctx.init() inside a workflow.
The initializer runs whenever the runtime initializes a harness from the created agent: when a workflow calls ctx.init(), and when the runtime prepares an addressable agent interaction. Do not treat it as a one-time constructor for a persistent agent instance id. Return a runtime config object with model: '<provider>/<model>', model: false, or a profile with its own model field.
AgentCreateContext
| Field | Type | Description |
|---|---|---|
id | string | Agent instance id, or workflow run id when initialized with ctx.init(). |
env | TEnv | Platform environment bindings supplied by the runtime. |
payload | TPayload | undefined | Workflow payload when initialized with ctx.init(); otherwise undefined. |
AgentRuntimeConfig
| Field | Type | Description |
|---|---|---|
profile | AgentProfile | Reusable baseline profile. Created-agent fields replace or extend profile values. |
model | string | false | Default model specifier. Set to false to require call-level model selection. |
instructions | string | Instructions prepended to discovered workspace context. |
skills | Skill[] | Additional registered skills available to initialized sessions. |
tools | ToolDefinition[] | Additional custom model-callable tools available to initialized sessions. |
subagents | AgentProfile[] | Additional named profiles available for delegated session.task() operations. |
thinkingLevel | ThinkingLevel | Default reasoning effort. Individual operations may override this value. |
compaction | false | CompactionConfig | Automatic conversation-compaction configuration. false disables threshold compaction; overflow recovery and explicit session.compact() calls still compact when needed. |
cwd | string | Working directory inside the initialized sandbox. |
sandbox | false | SandboxFactory | BashFactory | Sandbox factory used to construct the initialized environment. See Sandboxes. |
persist | SessionStore | Conversation-state store used by initialized sessions. See Data Persistence API. |
CreatedAgent
CreatedAgent is the opaque initializer value returned by createAgent().
init(...)
interface FlueContext<TPayload, TEnv> {
init(agent: CreatedAgent<TPayload, TEnv>, options?: AgentHarnessOptions): Promise<FlueHarness>;
}
ctx.init() initializes a created agent for one workflow invocation. Each harness name may be initialized once per context. The default harness name is 'default'.
AgentHarnessOptions
| Field | Type | Default | Description |
|---|---|---|---|
name | string | 'default' | Harness name. |
tools | ToolDefinition[] | — | Additional custom model-callable tools available to initialized sessions. |
skills | Skill[] | — | Additional registered skills available to initialized sessions. |
subagents | AgentProfile[] | — | Additional named profiles available for delegated session.task() operations. |
Agent
A created agent is the value returned by createAgent(). Addressable agents are default-exported from agents/<name>.ts. Workflows initialize a created agent with ctx.init().
Harness
A harness is an initialized agent environment returned by ctx.init().
FlueHarness
Initialized agent environment returned by ctx.init().
interface FlueHarness {
readonly name: string;
session(name?: string): Promise<FlueSession>;
readonly sessions: FlueSessions;
shell(command: string, options?: ShellOptions): CallHandle<ShellResult>;
readonly fs: FlueFs;
}
harness.session(...)
session(name?: string): Promise<FlueSession>;
Gets or creates a session in this harness. Defaults to the 'default' session.
harness.sessions.get(...)
get(name?: string): Promise<FlueSession>;
Loads an existing session. Defaults to 'default'. Throws if it does not exist.
harness.sessions.create(...)
create(name?: string): Promise<FlueSession>;
Creates a new session. Defaults to 'default'. Throws if it already exists.
harness.sessions.delete(...)
delete(name?: string): Promise<void>;
Deletes a session’s stored conversation state. Defaults to 'default'. No-op when missing.
harness.shell(...)
shell(command: string, options?: ShellOptions): CallHandle<ShellResult>;
Runs a shell command in the harness sandbox without recording it in a conversation.
harness.fs
- Type:
FlueFs
Reads and writes files in the harness sandbox without recording them in a conversation.
Session
A session is named conversation state inside a harness. A session runs one active prompt, skill, task, shell, or compact operation at a time. Use separate named sessions for parallel conversation branches.
FlueSession
Named conversation state inside a harness.
interface FlueSession {
readonly name: string;
prompt(text: string, options?: PromptOptions): CallHandle<PromptResponse>;
skill(skill: SkillReference | string, options?: SkillOptions): CallHandle<PromptResponse>;
task(text: string, options?: TaskOptions): CallHandle<PromptResponse>;
shell(command: string, options?: ShellOptions): CallHandle<ShellResult>;
readonly fs: FlueFs;
compact(): Promise<void>;
delete(): Promise<void>;
}
The prompt(), skill(), and task() signatures above omit structured-result overloads. Pass a Valibot schema as options.result to resolve with validated response.data.
session.prompt(...)
prompt(text: string, options?: PromptOptions): CallHandle<PromptResponse>;
Runs a model operation with a text instruction.
PromptOptions
| Field | Type | Description |
|---|---|---|
result | Valibot schema | Require validated structured data and resolve with response.data. |
tools | ToolDefinition[] | Additional custom model-callable tools for this operation. |
model | string | Model specifier override for this operation. |
thinkingLevel | ThinkingLevel | Reasoning-effort override for this operation. |
signal | AbortSignal | Cancel this operation. |
images | PromptImage[] | Images attached to the user message. Requires a vision-capable model. |
schema | Valibot schema | Deprecated alias for result. |
PromptImage
type PromptImage = {
type: 'image';
data: string;
mimeType: string;
};
The selected model must support image input.
PromptResponse
interface PromptResponse {
text: string;
usage: PromptUsage;
model: PromptModel;
}
PromptUsage
Aggregated token and cost usage for model work performed by one operation. Tool use, result retries, and automatic compaction may cause one operation to include multiple model turns.
PromptModel
interface PromptModel {
provider: string;
id: string;
}
Model selected for the operation’s primary turn.
PromptResultResponse
interface PromptResultResponse<T> {
data: T;
usage: PromptUsage;
model: PromptModel;
}
Use result and response.data in new code. The schema option and former response.result field are deprecated compatibility names. A structured-result operation throws ResultUnavailableError when the agent cannot produce validated data.
session.skill(...)
skill(skill: SkillReference | string, options?: SkillOptions): CallHandle<PromptResponse>;
Runs a registered skill. Pass options.result to require validated structured data instead of freeform text.
SkillReference
interface SkillReference {
readonly __flueSkillReference: true;
readonly id: string;
readonly name: string;
readonly description: string;
}
Opaque imported packaged-skill reference accepted by session.skill(). Import a SKILL.md value rather than constructing one manually.
SkillOptions
| Field | Type | Description |
|---|---|---|
args | Record<string, unknown> | Arguments included with the skill instruction. |
result | Valibot schema | Require validated structured data and resolve with response.data. |
tools | ToolDefinition[] | Additional custom model-callable tools for this operation. |
model | string | Model specifier override for this operation. |
thinkingLevel | ThinkingLevel | Reasoning-effort override for this operation. |
signal | AbortSignal | Cancel this operation. |
images | PromptImage[] | Images attached to the skill’s user message. Requires a vision-capable model. |
schema | Valibot schema | Deprecated alias for result. |
session.task(...)
task(text: string, options?: TaskOptions): CallHandle<PromptResponse>;
Delegates work to a detached child session. Pass options.agent to select a named subagent profile and options.result to require validated data.
TaskOptions
| Field | Type | Description |
|---|---|---|
agent | string | Named subagent profile selected for this delegated task. |
result | Valibot schema | Require validated structured data and resolve with response.data. |
tools | ToolDefinition[] | Additional custom model-callable tools for this operation. |
model | string | Model specifier override for this operation. |
thinkingLevel | ThinkingLevel | Reasoning-effort override for this operation. |
cwd | string | Working directory for the detached task session. Defaults to the parent session cwd. |
signal | AbortSignal | Cancel this task. |
images | PromptImage[] | Images attached to the task’s initial user message. Requires a vision-capable model. |
schema | Valibot schema | Deprecated alias for result. |
session.shell(...)
shell(command: string, options?: ShellOptions): CallHandle<ShellResult>;
Runs a shell command and records its command exchange in conversation state.
ShellOptions
| Field | Type | Description |
|---|---|---|
env | Record<string, string> | Environment variables supplied to the command. |
cwd | string | Working directory supplied to the command. |
signal | AbortSignal | Cancel this operation. |
ShellResult
interface ShellResult {
stdout: string;
stderr: string;
exitCode: number;
}
session.fs
- Type:
FlueFs
Reads and writes files in the session sandbox without recording them in the conversation transcript.
session.compact()
compact(): Promise<void>;
Triggers conversation compaction immediately. Resolves without work when there is nothing to compact. Throws if another operation is active on the session.
session.delete()
delete(): Promise<void>;
Deletes this session’s stored conversation state.
CallHandle<T>
interface CallHandle<T> extends PromiseLike<T> {
readonly signal: AbortSignal;
abort(reason?: unknown): void;
}
prompt(), skill(), task(), and shell() return awaitable call handles. Retain the handle when application code needs to cancel in-flight work. Aborting rejects the awaited operation with an AbortError (DOMException). Pass options.signal to merge an external abort signal with the handle’s signal.
FlueFs
interface FlueFs {
readFile(path: string): Promise<string>;
readFileBuffer(path: string): Promise<Uint8Array>;
writeFile(path: string, content: string | Uint8Array): Promise<void>;
stat(path: string): Promise<FileStat>;
readdir(path: string): Promise<string[]>;
exists(path: string): Promise<boolean>;
mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;
rm(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void>;
}
Paths may be absolute or relative. Relative paths use the configured cwd, or the sandbox connector’s default when cwd is omitted; use absolute paths for portability across connectors. These operations are out-of-band and do not appear in conversation history.
FileStat
interface FileStat {
isFile: boolean;
isDirectory: boolean;
isSymbolicLink: boolean;
size: number;
mtime: Date;
}