@ikarmic/forge-core
v5.5.2
Published
Agent engine for IKarmic AI Forge. Model loop, tools, MCP, sandbox, memory, compaction, plan mode, skills, hooks.
Maintainers
Readme
@ikarmic/forge-core
The agent engine for IKarmic AI Forge. Shared by the CLI and the VS Code extension.
What's in the box
Agent: the model + tool loop with streaming events, manual approval, abort support, multi-turn history.BUILTIN_TOOLS: ten ready-made tools:read_file,write_file,edit_file,list_files,search_files,run_command,fetch_url,sub_agent,memory_read,memory_write.createLanguageModel({ provider, model }): Vercel AI SDK adapter for OpenAI, Anthropic, Google, Ollama, and OpenRouter.resolveModelFromEnv(): picks a provider/model from your environment.- MCP integration:
loadMcpConfig,connectAll,closeAll, plus a JSON-Schema → Zod converter that turns any MCP server's tools into first-classToolDefinitionobjects. Supports stdio, SSE, and streamable-HTTP transports. - Tool sandbox:
ToolSandboxrestricts which tools the agent can call and what those tools can touch (path / command / URL policies). See Sandbox below. - Session persistence:
saveSession/loadSession/listSessionsfor multi-turn history that survives a process restart. - Cost tracking:
lookupPricing+computeCostUsdagainst a built-in pricing table; surfaced ascostevents andcostUsdonAgentRunResult. - Secret redaction:
redact()scrubs provider keys, JWTs, PEM keys, and.env-style secrets from tool output before the model sees them. - Tool result cache:
ToolResultCache(LRU + TTL, never caches destructive tools) survives across turns within a session. - Project memory:
buildMemoryBlock()auto-loads.forge/MEMORY.mdinto the system prompt;memory_read/memory_write/memory_forgettools let the agent record and retire conventions mid-run (typed sections, relevance-ranked injection, stale-ref markers). - Plan mode:
AgentConfig.planModeruns a single-turn, tool-free pass that emits a numbered plan as text. Pair with an approve/edit/cancel flow. - Context compaction: opt-in summarization of older turns when approaching the model's context window.
AgentConfig.enableCompactiontoggles it; the rest are knobs. - Skills system:
discoverSkills()findsSKILL.mdfiles in./skills/,./.forge/skills/,~/.forge/skills/.selectSkills()+composeSkillsPrompt()score and inject the top matches for the current task. - Lifecycle hooks:
HooksBussubscribes to 10 lifecycle events (PreToolUse,PostToolUse,PreCompact,SessionStart,SessionEnd,UserPromptSubmit,SubagentStart,SubagentStop,Notification,Stop). Configure vialoadHooksConfig()from~/.forge/settings.json+.forge/settings.json.
Install
pnpm add @ikarmic/forge-core ai @ai-sdk/anthropic
# (or @ai-sdk/openai, @ai-sdk/google)Minimal example
import { Agent, resolveModelFromEnv } from '@ikarmic/forge-core';
const agent = new Agent({
model: resolveModelFromEnv(),
cwd: process.cwd(),
auto: true,
});
const result = await agent.run({
task: 'list all .ts files under src/ and count their lines',
onEvent: (event) => {
if (event.type === 'text_delta') process.stdout.write(event.text);
if (event.type === 'tool_call') console.log(`\n→ ${event.name}(${JSON.stringify(event.args)})`);
},
});
console.log(`\nDone in ${result.iterations} steps (${result.inputTokens}↑ ${result.outputTokens}↓ tokens)`);Custom tools
import { z } from 'zod';
import type { ToolDefinition } from '@ikarmic/forge-core';
const gitStatusTool: ToolDefinition = {
name: 'git_status',
description: 'Run `git status --short` and return the result.',
parameters: z.object({}),
execute: async (_args, ctx) => {
const { spawn } = await import('node:child_process');
// ...
return { ok: true };
},
};
const agent = new Agent({
model: resolveModelFromEnv(),
extraTools: [gitStatusTool],
});Approval flow
By default, run_command and any tool marked destructive: true require approval via the approve callback. In --auto mode they're approved automatically; in interactive mode the CLI shows a y/n prompt and resolves the returned promise.
const agent = new Agent({
model: resolveModelFromEnv(),
approve: async (req) => {
console.log(`Approve ${req.name}?`);
return readlineYesNo();
},
});Sandbox
ToolSandbox is the security layer for the agent. Two dimensions:
- Tool allow/deny lists: strip tools from the model's view entirely.
- Per-tool policies: narrow what a still-exposed tool can do.
import { Agent, resolveModelFromEnv } from '@ikarmic/forge-core';
const agent = new Agent({
model: resolveModelFromEnv(),
toolSandbox: {
// Only expose these three tools to the model.
allowTools: ['read_file', 'list_files', 'search_files'],
policies: {
// File tools can only operate inside src/ or tests/.
read_file: { allowedPaths: ['src/**', 'tests/**'] },
list_files: { allowedPaths: ['src/**', 'tests/**'] },
// run_command: only allow npm/pnpm/node invocations, never rm or curl.
run_command: {
allowedCommands: [/^(npm|pnpm|node)\b/],
deniedCommands: [/^rm\b/, /^curl\b/],
},
// fetch_url: only allow HTTPS docs endpoints.
fetch_url: { allowedUrls: [/^https:\/\/docs\./] },
},
},
});allowToolsis an explicit whitelist (only listed tools survive).denyToolsis a blacklist applied to whatever survivedallowTools.- For path patterns: absolute patterns are anchored, relative patterns match at any depth.
*matches a non-separator run,**crosses separators,X/**also matchesXitself. - For command / URL patterns: anything you can compile to a
RegExp. - When both
allowedPathsanddeniedPathsare set, deniedPaths wins: the user can refine the allowed set but cannot grant access to a denied path.
Violations surface as a normal tool error ([sandbox] Path ... is not in allowedPaths (...)), so the model can recover by trying a different path/command/URL.
The CLI exposes all of the above as flags: see forge --help.
MCP integration
Load tools from any MCP-compatible server and merge them into the agent. Supports stdio, SSE, and streamable-HTTP transports.
import { Agent, loadMcpConfig, connectAll, closeAll } from '@ikarmic/forge-core';
const config = await loadMcpConfig('./forge.mcp.json');
const servers = await connectAll(config);
const mcpTools = servers.flatMap((s) => s.tools);
try {
const agent = new Agent({
model: resolveModelFromEnv(),
extraTools: mcpTools,
});
const result = await agent.run({ task: 'use the filesystem tool to list src/' });
console.log(result.finalText);
} finally {
await closeAll(servers); // important: spawned processes must be cleaned up
}MCP tools appear in the agent's prompt with fully-qualified names like mcp__filesystem__read_file so they can't collide with the built-in tool set.
License
Proprietary, free to run with the Forge extension and CLI. See LICENSE. Versions 4.5.0 and earlier stay MIT.
