@aaspai/agent-sdk
v0.0.1-alpha.1
Published
Worker runtime SDK for AASPAI agent control-plane integration
Maintainers
Readme
@aaspai/agent-sdk
TypeScript-first SDK for autonomous AASPAI agents (basic, graph, deep) with worker runtime, policy/autonomy controls, and observability hooks.
Start Here
- User docs:
docs/sdks/typescript/agents/overview.mdxdocs/sdks/typescript/agents/worker-sdk.mdxdocs/sdks/typescript/agents/coding-agent.mdxdocs/sdks/typescript/agents/production.mdx
- Frontend SDK docs:
docs/sdks/typescript/agents/frontend-sdk.mdx
- End-to-end examples:
apps/examples/agent-chat-starterpackages/create-aaspai-agent-worker(scaffolder template)
Core capabilities
- Worker runtime loop (
AgentWorkerRuntime) - Control-plane client (
createHttpAgentWorkerControlPlane) - Agent contracts + identity/policy envelopes
- Agent constructors:
createBasicAgent(...)createGraphAgent(...)createDeepAgent(...)
- Native graph primitives (
AaspaiGraphBuilder) - Tool registry + policy checks (
ToolRegistry,checkToolPolicy) - Built-in isolated workspace tools (
registerBuiltinTools,createNodeSandboxBackend) - Remote sandbox adapter (
createRemoteSandboxBackend,createRemoteSandboxBackendFromEnv) - Browser fetch tool (
browser.fetch_page) - Tool-result persistence + artifact offloading (
ToolRegistrypersistence hooks) - Semantic memory + retrieval for deep kernel (
createInMemorySemanticMemoryStore) - Prompt caching for planner/executor paths (
createInMemoryPromptCacheStore) - Model-aware context-window controls + context-pressure auto-retry
- Deep runtime pause/resume + manual compaction signals
- Invariant/off-track detection in deep runtime
- Memory-conflict detection in deep runtime
- Worker drain/kill-switch-ready runtime filtering (active/draining/offline)
- Lane/session/scope-based claim isolation controls
- Lane scheduler (
LaneScheduler) - Simulation + evaluator helpers
- Agent Ops tracing (
createAgentOpsTracer) - Optional OTEL-compatible trace export sink (
createOtelHttpBatchSink) - Deep-agent runtime state persistence via control-plane APIs (resume-ready)
- Coding runtime kit for custom workers (
createCodingRuntimeKit,createCodingRuntimeKitFromEnv) - Optional coding worker recipes (graph/deep) with override hooks (
createCodingWorker,createCodingWorkerFromEnv) - Built-in coding integration tool aliases for sandbox/github/preview
Quick start
import {
createBasicAgent,
startAgentWorker,
type AgentExecutionEnvelope,
} from '@aaspai/agent-sdk';
const envelope: AgentExecutionEnvelope = {
identity: {
mission: { purpose: 'CRM support', successCriteria: ['Resolve inbound tickets'] },
organization: { projectId: 'crm-live' },
role: { role: 'support-agent', persona: 'helpful and precise', responsibilities: ['triage', 'resolution'] },
task: { objective: 'Handle support requests quickly' },
},
policy: {
autonomyLevel: 'L1',
budget: { maxRuntimeMs: 300000, maxToolCalls: 20 },
},
};
const agent = createBasicAgent({
id: 'support-agent',
envelope,
async respond({ context }) {
const last = context.messages.at(-1)?.content;
return `Support agent received: ${String(last ?? '')}`;
},
});
startAgentWorker({ agent });Coding runtime kit (recommended)
import {
createCodingRuntimeKitFromEnv,
createDeepAgent,
} from '@aaspai/agent-sdk';
const kit = createCodingRuntimeKitFromEnv({
workerKey: 'crm-coding-agent',
instructions: 'You are a senior full-stack engineer...',
workflow: { runtimeMode: 'deep' },
});
const agent = createDeepAgent({
id: 'crm-coding-agent',
goal: 'Deliver coding tasks safely with evidence.',
planner: async () => ({
tasks: [
{ id: 'scan', title: 'Scan workspace', status: 'pending' },
{ id: 'respond', title: 'Prepare response for user', status: 'pending' },
],
}),
executor: async ({ task, context }) => {
if (task.id === 'scan') {
await kit.toolRegistry.execute(
'coding.fs.list',
{ directory: '.', recursive: false, limit: 120 },
{
runId: context.runId,
sessionId: context.sessionId,
assistantId: context.assistantId,
}
);
}
return { completed: true, outputText: 'Ready. Share a concrete coding task.' };
},
});
kit.worker.start(agent);Optional coding worker recipe
import { createCodingWorkerFromEnv } from '@aaspai/agent-sdk';
const worker = createCodingWorkerFromEnv({
workerKey: 'crm-coding-agent',
instructions: 'You are a senior full-stack engineer...',
workflow: {
preset: 'builder-v1',
runtimeMode: 'graph', // graph | deep
},
});
worker.worker.start();Preflight modes (recommended for robust deep workers):
AASPAI_CODING_PREFLIGHT_MODE=strict # fail fast on env contract issues
# AASPAI_CODING_PREFLIGHT_MODE=warn
# AASPAI_CODING_PREFLIGHT_MODE=offStrict preflight validates:
- control-plane env (
AGENT_WORKER_CONTROL_PLANE_URL,AGENT_WORKER_TOKEN) - project scope consistency (
AASPAI_PROJECT_ID,AGENT_WORKER_PROJECT_ID) - deep runtime LLM keys (
OPENROUTER_API_KEY/AASPAI_LLM_API_KEY) - Daytona connectivity (
DAYTONA_API_KEYorAASPAI_CODING_DAYTONA_GATEWAY_URL) - preview port and snapshot signals
Use built-in AASPAI backend coding gateway bindings (Daytona/GitHub/Preview):
import {
createAaspaiCodingIntegrations,
createCodingWorkerFromEnv,
} from '@aaspai/agent-sdk';
const worker = createCodingWorkerFromEnv({
workerKey: 'crm-coding-agent',
instructions: 'You are a senior full-stack engineer...',
integrations: createAaspaiCodingIntegrations(),
});Graph overrides:
import { createCodingWorker } from '@aaspai/agent-sdk';
const worker = createCodingWorker({
workerKey: 'crm-coding-agent',
instructions: 'Build requested feature safely',
graphOverrides: {
analyze_intent: {
wrap: async (input, next) => {
const result = await next(input);
return {
patch: {
...(result.patch || {}),
summaryNotes: [...input.state.summaryNotes, 'Custom intent wrapper executed'],
},
};
},
},
},
});Built-in tools (Iteration 1)
import {
ToolRegistry,
registerBuiltinTools,
createNodeSandboxBackend,
} from '@aaspai/agent-sdk';
const registry = new ToolRegistry();
const backend = createNodeSandboxBackend({
workspaceRoot: process.env.AGENT_WORKSPACE_ROOT,
agentId: 'support-agent',
mode: 'workspace-write', // workspace-write | workspace-readonly | disabled
});
registerBuiltinTools(registry, { backend });
// Tools:
// - fs.read_file
// - fs.write_file
// - fs.edit_file
// - fs.ls
// - fs.glob
// - fs.grep
// - shell.execute (high-impact, approval expected)
// - browser.fetch_pageModular SDK layout
core/: contracts, policy, runtime/shared typesagents/: basic/graph/deep agent definitions + kernelsruntime/: control-plane transport, scheduler, worker runtime, bootstraptooling/: tool registry, built-in tools, sandbox adapters, artifact storeevaluation/: simulation and evaluator helpersobservability/: ops tracing helperscoding/: coding runtime primitives (tooling, env resolver, sandbox manager, runtime kit, integrations)recipes/: optional opinionated worker recipes built on top ofcoding/
Approval and destructive-action guardrails
checkToolPolicy(...)now supports allow/deny lists (allowTools,denyTools)- high-impact tools require explicit approval by default (
requireApprovalForRisks) ToolRegistry.execute(...)supportsapprovalHandler- destructive actions can be flagged by tools (
isDestructiveAction) and forced through approval - tool-call budgets are enforced via policy
budget.maxToolCalls
Remote sandbox provider (Iteration 2)
import {
ToolRegistry,
registerBuiltinTools,
createRemoteSandboxBackend,
} from '@aaspai/agent-sdk';
const registry = new ToolRegistry();
const backend = createRemoteSandboxBackend({
baseUrl: process.env.AGENT_REMOTE_SANDBOX_URL!,
token: process.env.AGENT_REMOTE_SANDBOX_TOKEN,
workspaceId: 'worker-01',
});
registerBuiltinTools(registry, { backend, provider: 'remote' });Tool-result persistence + artifacts (Iteration 2)
import {
ToolRegistry,
createFileToolArtifactStore,
} from '@aaspai/agent-sdk';
const registry = new ToolRegistry();
const artifactStore = createFileToolArtifactStore({
rootDir: '.aaspai-tool-artifacts',
});
await registry.execute(
'shell.execute',
{ command: 'npm run build' },
{ runId: 'r1', sessionId: 's1', assistantId: 'a1' },
{
policy,
persistence: {
artifactStore,
offloadLargePayloads: true,
maxInlineBytes: 4096,
onPersist: async ({ toolName, artifacts }) => {
console.log('persisted', toolName, artifacts);
},
},
}
);Deep kernel context intelligence (Iteration 3)
import {
createDeepAgent,
createInMemorySemanticMemoryStore,
createInMemoryPromptCacheStore,
} from '@aaspai/agent-sdk';
const deepAgent = createDeepAgent({
id: 'ops-deep-agent',
goal: 'Run long-horizon operations safely',
envelope,
planner,
executor,
semanticMemory: {
store: createInMemorySemanticMemoryStore({ maxEntries: 3000 }),
topK: 8,
minScore: 0.08,
},
promptCache: {
store: createInMemoryPromptCacheStore({ maxEntries: 3000 }),
plannerTtlMs: 20000,
executorTtlMs: 20000,
},
contextWindow: {
modelId: 'openai/gpt-4o-mini',
reserveOutputTokens: 1800,
pressureThresholdRatio: 0.82,
maxPressureRetries: 2,
},
});Run controls (Pause/Resume/Compact)
- Runtime control state key:
<stateKey>.controls(default:deep.kernel.state.controls) - Public APIs:
POST /api/agents/runs/:runId/pausePOST /api/agents/runs/:runId/resumePOST /api/agents/runs/:runId/compact
- Optional request field:
stateKey(for non-default deep state keys)
Example body:
{
"stateKey": "examples.deep.kernel.state",
"reason": "manual operator action"
}Isolation + drain controls (Iteration 4)
Worker claim isolation:
startAgentWorker({
agent,
scopeKey: 'org-alpha/project-crm',
laneKeyPrefix: 'scope:org-alpha/project-crm:',
laneKeys: ['scope:org-alpha/project-crm:followup:session-123'],
});Worker operation mode endpoints:
POST /api/agents/workers/:workerId/drainPOST /api/agents/workers/:workerId/activatePOST /api/agents/workers/:workerId/offline
Observability parity (Iteration 5)
Run replay/compare + OTEL export APIs:
GET /api/agents/ops/runs/:runId/replayGET /api/agents/ops/runs/compare?leftRunId=...&rightRunId=...GET /api/agents/ops/runs/:runId/otel
Optional OTEL sink on worker runtime:
import {
createOtelHttpBatchSink,
startAgentWorker,
} from '@aaspai/agent-sdk';
const otelSink = createOtelHttpBatchSink({
endpoint: 'http://localhost:4318/v1/traces',
headers: {
Authorization: `Bearer ${process.env.OTEL_TOKEN ?? ''}`,
},
serviceName: 'crm-agent-worker',
serviceVersion: '1.0.0',
});
startAgentWorker({
agent,
opsBatchSinks: [otelSink],
});Governance hardening (Iteration 6)
- Threat model:
planning/agent-sdk-threat-model-v1.md - Adversarial harness:
scripts/agent-adversarial-suite.mjs - Root test command:
npm run test:agent:adversarial
- Full agent regression command:
npm run test:agent:all
LangGraph compatibility
Core SDK is no longer a LangGraph wrapper.
If you still need LangGraph primitives while migrating:
import { StateGraph, Annotation, START, END } from '@aaspai/agent-sdk/langgraph-compat';Notes
- Node.js oriented.
- Worker runtime is transport-agnostic through
AgentWorkerControlPlane. - Use strong
AGENT_WORKER_TOKENin production.
