HomeSDK Documentation

SDK Documentation

Full reference for the DashClaw SDK. 177+ methods across 29 categories to govern your AI agents with action recording, evaluation framework, scoring profiles, learning analytics, prompt management, feedback loops, behavioral drift, compliance exports, and more.

View raw

Quick Start

1

Copy the SDK

Install from npm, or copy the single-file SDK directly.

terminal
npm install dashclaw
2

Initialize the client

agent.js
import { DashClaw } from 'dashclaw';

const claw = new DashClaw({
  baseUrl: 'http://localhost:3000', // or https://your-app.vercel.app
  apiKey: process.env.DASHCLAW_API_KEY,
  agentId: 'my-agent',
  agentName: 'My Agent',
});
3

Record your first action

agent.js
// Create an action before doing work
const { action_id } = await claw.createAction({
  action_type: 'deploy',
  declared_goal: 'Deploy authentication service',
  risk_score: 60,
});

// ... do the work ...

// Update when done
await claw.updateOutcome(action_id, {
  status: 'completed',
  output_summary: 'Auth service deployed to prod',
});

Or use track() to wrap it in a single call that auto-records success/failure.

Prefer to let your coding agent do setup and coverage automatically?

Constructor

Create a DashClaw instance. Requires Node 18+ (native fetch).

const claw = new DashClaw({ baseUrl, apiKey, agentId, agentName, swarmId, guardMode, guardCallback });
ParameterTypeRequiredDescription
baseUrlstringYesDashClaw dashboard URL (e.g. "http://localhost:3000" or "https://your-app.vercel.app")
apiKeystringYesAPI key for authentication (determines which org's data you access)
agentIdstringYesUnique identifier for this agent
agentNamestringNoHuman-readable agent name
swarmIdstringNoSwarm/group identifier if part of a multi-agent system
guardModestringNoAuto guard check before createAction/track: "off" (default), "warn" (log + proceed), "enforce" (throw on block)
guardCallbackFunctionNoCalled with guard decision object when guardMode is active

Guard Mode

When guardMode is set, every call to createAction() and track() automatically checks guard policies before proceeding.

import { DashClaw, GuardBlockedError } from 'dashclaw';

const claw = new DashClaw({
  baseUrl: 'http://localhost:3000',
  apiKey: process.env.DASHCLAW_API_KEY,
  agentId: 'my-agent',
  guardMode: 'enforce', // throws GuardBlockedError on block/require_approval
  guardCallback: (decision) => console.log('Guard:', decision.decision),
});

try {
  await claw.createAction({ action_type: 'deploy', declared_goal: 'Ship v2' });
} catch (err) {
  if (err instanceof GuardBlockedError) {
    console.log(err.decision);  // 'block' or 'require_approval'
    console.log(err.reasons);   // ['Risk score 90 >= threshold 80']
  }
}

Real-Time Events

Subscribe to server-sent events for instant push notifications. Eliminates polling for approvals, policy changes, and task assignments.

Reactive Mission Control

Strategic fleet overview with real-time health pulses, decision timelines, and a live terminal-style swarm log.

Instant Governance

Guard decisions and risk signals stream instantly to the dashboard, allowing human operators to react the moment a policy is triggered.

claw.events()

Open a persistent SSE connection. Returns a chainable handle with .on(event, callback) and .close(). Supported events: action.created, action.updated, loop.created, loop.updated, goal.created, goal.updated, decision.created, guard.decision.created, signal.detected, token.usage, message.created, policy.updated, task.assigned, task.completed.

Returns: { on(eventType, callback): this, close(): void }

const stream = dc.events();

stream
  .on('action.created', (data) => console.log('New action:', data.action_id))
  .on('action.updated', (data) => {
    if (data.status === 'running') console.log('Approved:', data.action_id);
  })
  .on('loop.created', (data) => console.log('New dependency:', data.description))
  .on('loop.updated', (data) => console.log('Loop status changed:', data.status))
  .on('goal.created', (data) => console.log('New goal:', data.title))
  .on('goal.updated', (data) => console.log('Goal progress:', data.progress + '%'))
  .on('decision.created', (data) => console.log('Agent decided:', data.decision))
  .on('guard.decision.created', (data) => console.log('Guard:', data.decision))
  .on('signal.detected', (data) => console.log('Alert:', data.label))
  .on('token.usage', (data) => console.log('Burn:', data.estimated_cost))
  .on('policy.updated', (data) => console.log('Policy changed:', data.change_type))
  .on('task.assigned', (data) => console.log('Task routed:', data.task?.title))
  .on('task.completed', (data) => console.log('Task done:', data.task?.task_id))
  .on('error', (err) => console.error('Stream error:', err));

// When done:
stream.close();

Action Recording

Create, update, and query action records. Every agent action gets a full audit trail.

claw.createAction(action)

Create a new action record. The agent's agentId, agentName, and swarmId are automatically attached.

ParameterTypeRequiredDescription
action_typestringYesOne of: build, deploy, post, apply, security, message, api, calendar, research, review, fix, refactor, test, config, monitor, alert, cleanup, sync, migrate, other
declared_goalstringYesWhat this action aims to accomplish
action_idstringNoCustom action ID (auto-generated act_ UUID if omitted)
reasoningstringNoWhy the agent decided to take this action
authorization_scopestringNoWhat permissions were granted
triggerstringNoWhat triggered this action
systems_touchedstring[]NoSystems this action interacts with
input_summarystringNoSummary of input data
parent_action_idstringNoParent action if this is a sub-action
reversiblebooleanNoWhether this action can be undone (default: true)
risk_scorenumberNoRisk score 0-100 (default: 0)
confidencenumberNoConfidence level 0-100 (default: 50)

Returns: Promise<{ action: Object, action_id: string }>

const { action_id } = await claw.createAction({
  action_type: 'deploy',
  declared_goal: 'Deploy auth service to production',
  risk_score: 70,
  systems_touched: ['kubernetes', 'auth-service'],
  reasoning: 'Scheduled release after QA approval',
});

claw.waitForApproval(actionId, options?)

Poll for human approval when an action enters pending_approval status. Useful with hitlMode='off' when you want explicit control over blocking behavior.

ParameterTypeRequiredDescription
actionIdstringYesThe pending action_id to poll
options.timeoutnumberNoMaximum wait in ms (default: 300000)
options.intervalnumberNoPolling interval in ms (default: 5000)

Returns: Promise<{ action: Object, action_id: string }>

const { action_id } = await claw.createAction({
  action_type: 'deploy',
  declared_goal: 'Ship release candidate',
});

const approval = await claw.waitForApproval(action_id, {
  timeout: 180000,
  interval: 3000,
});

console.log('Approved status:', approval.action.status);

claw.updateOutcome(actionId, outcome)

Update the outcome of an existing action. Automatically sets timestamp_end if not provided.

ParameterTypeRequiredDescription
actionIdstringYesThe action_id to update
statusstringNoNew status: completed, failed, cancelled
output_summarystringNoWhat happened
side_effectsstring[]NoUnintended consequences
artifacts_createdstring[]NoFiles, records, etc. created
error_messagestringNoError details if failed
duration_msnumberNoHow long it took in milliseconds
cost_estimatenumberNoEstimated cost in USD

Returns: Promise<{ action: Object }>

await claw.updateOutcome(action_id, {
  status: 'completed',
  output_summary: 'Auth service deployed successfully',
  artifacts_created: ['deploy-log-2024-01.txt'],
  duration_ms: 45000,
});

claw.track(actionDef, fn)

Helper that creates an action, runs your async function, and auto-updates the outcome. If fn throws, the action is marked as failed with the error message.

ParameterTypeRequiredDescription
actionDefObjectYesAction definition (same params as createAction)
fnFunctionYesAsync function to execute. Receives { action_id } as argument.

Returns: Promise<*> (the return value of fn)

const result = await claw.track(
  { action_type: 'build', declared_goal: 'Compile project' },
  async ({ action_id }) => {
    // Your logic here. If this throws, the action is marked failed.
    await runBuild();
    return 'Build succeeded';
  }
);

claw.getActions(filters?)

Get a list of actions with optional filters. Returns paginated results with stats.

ParameterTypeRequiredDescription
agent_idstringNoFilter by agent
swarm_idstringNoFilter by swarm
statusstringNoFilter by status (running, completed, failed, cancelled)
action_typestringNoFilter by type
risk_minnumberNoMinimum risk score
limitnumberNoMax results (default: 50)
offsetnumberNoPagination offset (default: 0)

Returns: Promise<{ actions: Object[], total: number, stats: Object }>

const { actions, total } = await claw.getActions({
  status: 'failed',
  risk_min: 50,
  limit: 20,
});

claw.getAction(actionId)

Get a single action with its associated open loops and assumptions.

ParameterTypeRequiredDescription
actionIdstringYesThe action_id to retrieve

Returns: Promise<{ action: Object, open_loops: Object[], assumptions: Object[] }>

const { action, open_loops, assumptions } = await claw.getAction('act_abc123');

claw.getActionTrace(actionId)

Get root-cause trace for an action, including its assumptions, open loops, parent chain, and related actions.

ParameterTypeRequiredDescription
actionIdstringYesThe action_id to trace

Returns: Promise<{ action: Object, trace: Object }>

const { trace } = await claw.getActionTrace('act_abc123');
// trace includes: assumptions, open_loops, parent_chain, related_actions

Evaluation Framework

Track output quality automatically with 5 built-in scorer types. No LLM required for most scorers.

claw.createScorer({ name, scorerType, config, description })

Create a new evaluation scorer.

ParameterTypeRequiredDescription
namestringYesScorer name
scorerTypestringYesregex, keywords, numeric_range, custom_function, or llm_judge
configobjectYesConfiguration for the scorer
descriptionstringNoPurpose of this scorer

Returns: Promise<Object>

await claw.createScorer({
  name: 'JSON Validator',
  scorerType: 'regex',
  config: { pattern: '^\{.*\}$' },
});

claw.getScorers()

List all available scorers.

Returns: Promise<{ scorers: Object[], llm_available: boolean }>

claw.getEvalRuns(filters?)

List evaluation runs with status and result summaries.

ParameterTypeRequiredDescription
statusstringNorunning, completed, failed
limitnumberNoMax results

Returns: Promise<{ runs: Object[] }>

claw.getEvalStats(filters?)

Get aggregate evaluation statistics across scorers and agents.

ParameterTypeRequiredDescription
agent_idstringNoFilter by agent
scorer_namestringNoFilter by scorer
daysnumberNoLookback period

Returns: Promise<Object>

Prompt Management

Version-controlled prompt templates with mustache variable rendering.

claw.createPromptTemplate({ name, content, category })

Create a new prompt template.

ParameterTypeRequiredDescription
namestringYesTemplate name
contentstringYesTemplate content with {{variables}}
categorystringNoOptional grouping category

Returns: Promise<Object>

claw.getPromptTemplate(templateId)

Get a template by ID, including its current active version.

Returns: Promise<Object>

claw.renderPrompt({ template_id, variables, action_id })

Render a template with variables on the server. Optionally link to an action for usage tracking.

ParameterTypeRequiredDescription
template_idstringYesTemplate ID
variablesobjectYesMustache variables
action_idstringNoLink to an action

Returns: Promise<{ rendered: string }>

claw.listPromptVersions(templateId)

List all versions of a prompt template.

Returns: Promise<Object[]>

claw.activatePromptVersion(templateId, versionId)

Set a specific version as the active one for a template.

Returns: Promise<Object>

User Feedback

Collect and analyze human feedback on agent actions.

claw.submitFeedback({ actionId, rating, comment })

Submit feedback for a specific action.

ParameterTypeRequiredDescription
actionIdstringYesAction ID
ratingnumberYesRating 1-5
commentstringNoOptional text feedback

Returns: Promise<Object>

claw.getFeedback(feedbackId)

Retrieve a single feedback entry.

Returns: Promise<Object>

claw.getFeedbackStats({ agent_id })

Get feedback statistics, including average rating and sentiment trends.

Returns: Promise<Object>

Behavioral Drift

Monitor agent behavior deviations from statistical baselines using z-scores.

claw.computeDriftBaselines({ agent_id, lookback_days })

Establish statistical baselines for an agent's behavior metrics.

Returns: Promise<Object>

claw.detectDrift({ agent_id, window_days })

Run drift detection against the established baselines.

Returns: Promise<Object>

claw.listDriftAlerts(filters?)

List behavioral drift alerts with severity and status.

Returns: Promise<Object[]>

Compliance Exports

Generate evidence packages for SOC 2, NIST AI RMF, EU AI Act, and ISO 42001.

claw.createComplianceExport({ name, frameworks, format, window_days })

Generate a compliance export bundle.

Returns: Promise<Object>

claw.getComplianceExport(exportId)

Get the status and details of a compliance export.

Returns: Promise<Object>

claw.listComplianceExports({ limit })

List recent compliance exports.

Returns: Promise<Object[]>

Learning Analytics

Track agent improvement velocity, maturity levels, and learning curves per skill.

claw.getLearningVelocity({ agent_id })

Get agent improvement rate over time.

Returns: Promise<Object>

claw.getMaturityLevels()

Get the 6-level maturity model distribution for the agent.

Returns: Promise<Object>

claw.getLearningCurves({ agent_id, action_type })

Get performance improvement curves for a specific skill/action type.

Returns: Promise<Object>

Scoring Profiles

User-defined weighted quality scoring with 3 composite methods, 8 data sources, risk templates, and auto-calibration. Zero LLM required.

claw.createScoringProfile({ name, action_type, composite_method, dimensions })

Create a scoring profile with optional inline dimensions.

ParameterTypeRequiredDescription
namestringYesProfile name
descriptionstringNoProfile description
action_typestringNoFilter to specific action type (null = all)
composite_methodstringNoweighted_average (default), minimum, or geometric_mean
dimensionsarrayNoInline dimension definitions (name, data_source, weight, scale)

Returns: Promise<Object>

const profile = await dc.createScoringProfile({
  name: 'deploy-quality',
  action_type: 'deploy',
  composite_method: 'weighted_average',
  dimensions: [
    { name: 'Speed', data_source: 'duration_ms', weight: 0.3,
      scale: [
        { label: 'excellent', operator: 'lt', value: 30000, score: 100 },
        { label: 'good', operator: 'lt', value: 60000, score: 75 },
        { label: 'poor', operator: 'gte', value: 60000, score: 20 },
      ]},
    { name: 'Reliability', data_source: 'confidence', weight: 0.7,
      scale: [
        { label: 'excellent', operator: 'gte', value: 0.9, score: 100 },
        { label: 'poor', operator: 'lt', value: 0.7, score: 25 },
      ]},
  ],
});

claw.listScoringProfiles(filters?)

List all scoring profiles for the organization.

Returns: Promise<Object[]>

claw.getScoringProfile(profileId)

Get a single scoring profile with its dimensions.

Returns: Promise<Object>

claw.updateScoringProfile(profileId, updates)

Update a scoring profile's metadata.

Returns: Promise<Object>

claw.deleteScoringProfile(profileId)

Delete a scoring profile and all its scores.

Returns: Promise<Object>

claw.addScoringDimension(profileId, dimension)

Add a new weighted dimension to a profile.

Returns: Promise<Object>

claw.updateScoringDimension(profileId, dimensionId, updates)

Update an existing dimension's weight or scale.

Returns: Promise<Object>

claw.deleteScoringDimension(profileId, dimensionId)

Remove a dimension from a profile.

Returns: Promise<Object>

claw.scoreWithProfile(profile_id, action)

Score a single action against a profile. Returns composite score + per-dimension breakdown.

ParameterTypeRequiredDescription
profile_idstringYesProfile to score against
actionobjectYesAction data object

Returns: Promise<Object>

const result = await dc.scoreWithProfile('sp_abc123', {
  duration_ms: 25000, confidence: 0.95, cost_estimate: 0.008,
});
// result.composite_score = 92.5
// result.dimensions = [{ dimension_name: 'Speed', score: 100, label: 'excellent' }, ...]

claw.batchScoreWithProfile(profile_id, actions)

Score multiple actions at once. Returns per-action results + summary.

ParameterTypeRequiredDescription
profile_idstringYesProfile to score against
actionsarrayYesArray of action data objects

Returns: Promise<Object>

const batch = await dc.batchScoreWithProfile('sp_abc123', [
  { duration_ms: 500, confidence: 0.98 },
  { duration_ms: 10000, confidence: 0.5 },
]);
// batch.summary = { total: 2, scored: 2, avg_score: 72.3 }

claw.getProfileScores(profileId, filters?)

List historical scores generated for a profile.

Returns: Promise<Object[]>

claw.getProfileScoreStats(profile_id)

Get aggregate statistics for a profile's scores.

ParameterTypeRequiredDescription
profile_idstringYesProfile ID

Returns: Promise<Object>

const stats = await dc.getProfileScoreStats('sp_abc123');
// { total_scores: 142, avg_score: 78.3, min_score: 23, max_score: 99, stddev_score: 12.5 }

claw.createRiskTemplate({ name, base_risk, rules })

Create a rule-based risk template. Replaces hardcoded agent risk numbers.

ParameterTypeRequiredDescription
namestringYesTemplate name
base_risknumberNoStarting risk score (0-100)
rulesarrayNoArray of { condition, add } rules

Returns: Promise<Object>

const template = await dc.createRiskTemplate({
  name: 'Production Safety',
  base_risk: 20,
  rules: [
    { condition: "metadata.environment == 'production'", add: 25 },
    { condition: "metadata.modifies_data == true", add: 15 },
    { condition: "metadata.irreversible == true", add: 30 },
  ],
});

claw.listRiskTemplates()

List all risk templates for the organization.

Returns: Promise<Object[]>

claw.updateRiskTemplate(templateId, updates)

Update a risk template's rules or base risk.

Returns: Promise<Object>

claw.deleteRiskTemplate(templateId)

Delete a risk template.

Returns: Promise<Object>

claw.autoCalibrate({ action_type, lookback_days })

Analyze historical action data to suggest scoring thresholds from percentile distribution.

ParameterTypeRequiredDescription
action_typestringNoFilter to action type (null = all)
lookback_daysnumberNoDays to analyze (default: 30)

Returns: Promise<Object>

const cal = await dc.autoCalibrate({ lookback_days: 30, action_type: 'deploy' });
// cal.suggestions[0] = { metric: 'duration_ms', sample_size: 480,
//   distribution: { p25: 3000, p50: 8000, p75: 20000 },
//   suggested_scale: [...] }

Loops & Assumptions

Track unresolved dependencies and log what your agents assume. Catch drift before it causes failures.

claw.registerOpenLoop(loop)

Register an open loop (unresolved dependency, pending approval, etc.) for an action.

ParameterTypeRequiredDescription
action_idstringYesParent action ID
loop_typestringYesOne of: followup, question, dependency, approval, review, handoff, other
descriptionstringYesWhat needs to be resolved
prioritystringNoOne of: low, medium, high, critical (default: medium)
ownerstringNoWho is responsible for resolving this

Returns: Promise<{ loop: Object, loop_id: string }>

const { loop_id } = await claw.registerOpenLoop({
  action_id: 'act_abc123',
  loop_type: 'approval',
  description: 'Needs manager approval for prod deploy',
  priority: 'high',
  owner: 'ops-team',
});

claw.resolveOpenLoop(loopId, status, resolution?)

Resolve or cancel an open loop.

ParameterTypeRequiredDescription
loopIdstringYesThe loop_id to resolve
statusstringYes"resolved" or "cancelled"
resolutionstringNoResolution description (required when resolving)

Returns: Promise<{ loop: Object }>

await claw.resolveOpenLoop('loop_xyz789', 'resolved', 'Manager approved via Slack');

claw.registerAssumption(assumption)

Register an assumption made during an action. Track what your agent assumes so you can validate or invalidate later.

ParameterTypeRequiredDescription
action_idstringYesParent action ID
assumptionstringYesThe assumption being made
basisstringNoEvidence or reasoning for the assumption
validatedbooleanNoWhether this has been validated (default: false)

Returns: Promise<{ assumption: Object, assumption_id: string }>

const { assumption_id } = await claw.registerAssumption({
  action_id: 'act_abc123',
  assumption: 'Database schema is unchanged since last deploy',
  basis: 'No migration files found in latest commits',
});

claw.getAssumption(assumptionId)

Get a single assumption by ID.

ParameterTypeRequiredDescription
assumptionIdstringYesThe assumption_id to retrieve

Returns: Promise<{ assumption: Object }>

const { assumption } = await claw.getAssumption('asm_abc123');

claw.validateAssumption(assumptionId, validated, invalidated_reason?)

Validate or invalidate an assumption. When invalidating, a reason is required.

ParameterTypeRequiredDescription
assumptionIdstringYesThe assumption_id to update
validatedbooleanYestrue to validate, false to invalidate
invalidated_reasonstringNoRequired when invalidating (validated = false)

Returns: Promise<{ assumption: Object }>

// Validate
await claw.validateAssumption('asm_abc123', true);

// Invalidate
await claw.validateAssumption('asm_abc123', false, 'Schema was altered by migration #47');

claw.getOpenLoops(filters?)

Get open loops with optional filters. Returns paginated results with stats.

ParameterTypeRequiredDescription
statusstringNoFilter by status: open, resolved, cancelled
loop_typestringNoFilter by loop type
prioritystringNoFilter by priority
limitnumberNoMax results (default: 50)

Returns: Promise<{ loops: Object[], total: number, stats: Object }>

const { loops } = await claw.getOpenLoops({
  status: 'open',
  priority: 'critical',
});

claw.getDriftReport(filters?)

Get drift report for assumptions with risk scoring. Shows which assumptions are stale, unvalidated, or contradicted by outcomes.

ParameterTypeRequiredDescription
action_idstringNoFilter by action
limitnumberNoMax results (default: 50)

Returns: Promise<{ assumptions: Object[], drift_summary: Object }>

const { assumptions, drift_summary } = await claw.getDriftReport();
console.log(drift_summary);
// { total, validated, invalidated, unvalidated, drift_score }

Signals

Automatic detection of problematic agent behavior. Seven signal types fire based on action patterns. No configuration required.

claw.getSignals()

Get current risk signals across all agents. Returns 7 signal types: autonomy_spike, high_impact_low_oversight, repeated_failures, stale_loop, assumption_drift, stale_assumption, and stale_running_action.

Returns: Promise<{ signals: Object[], counts: { red: number, amber: number, total: number } }>

const { signals, counts } = await claw.getSignals();
console.log(`${counts.red} red, ${counts.amber} amber signals`);

for (const signal of signals) {
  console.log(`[${signal.severity}] ${signal.signal_type}: ${signal.help}`);
}

Signal Types

autonomy_spikeAgent taking too many actions without human checkpoints
high_impact_low_oversightCritical actions without sufficient review
repeated_failuresSame action type failing multiple times
stale_loopOpen loops unresolved past their expected timeline
assumption_driftAssumptions becoming stale or contradicted by outcomes
stale_assumptionAssumptions not validated within expected timeframe
stale_running_actionActions stuck in running state for over 4 hours

Swarm Intelligence

Visualize multi-agent communication and operational drift in real-time. The Swarm dashboard maps your entire fleet as a neural web, highlighting high-risk nodes and message flows.

Neural Web Visualization

High-performance canvas rendering supports 50+ agents. Nodes are color-coded by risk, and live "packets" visualize inter-agent messaging as it happens.

Swarm Pulse (Expand)

Use the Expand button to trigger a physical pulse that temporarily spreads agents apart, instantly decluttering complex webs for better visibility.

Swarm Grouping

Use the swarmId constructor parameter to group related agents together in the neural web.

const claw = new DashClaw({
  agentId: 'researcher-1',
  swarmId: 'research-fleet-alpha', // Group agents together visually
  // ...
});

Behavior Guard

Check org-level policies before executing risky actions. Returns allow, warn, block, or require_approval based on configured guard policies.

claw.guard(context, options?)

Evaluate guard policies for a proposed action. Call this before risky operations to get a go/no-go decision. The agent_id is auto-attached from the SDK constructor.

ParameterTypeRequiredDescription
context.action_typestringYesThe type of action being proposed
context.risk_scorenumberNoRisk score 0-100
context.systems_touchedstring[]NoSystems this action will affect
context.reversiblebooleanNoWhether the action can be undone
context.declared_goalstringNoWhat the action accomplishes
options.includeSignalsbooleanNoAlso check live risk signals (adds latency)

Returns: Promise<{ decision: string, reasons: string[], warnings: string[], matched_policies: string[], evaluated_at: string }>

const result = await claw.guard({
  action_type: 'deploy',
  risk_score: 85,
  systems_touched: ['production-api'],
  reversible: false,
  declared_goal: 'Deploy auth service v2',
});

if (result.decision === 'block') {
  console.log('Blocked:', result.reasons);
  return; // abort the action
}

if (result.decision === 'warn') {
  console.log('Warnings:', result.warnings);
}

// proceed with the action
await claw.createAction({ action_type: 'deploy', ... });

claw.getGuardDecisions(filters?)

Retrieve recent guard evaluation decisions for audit and review.

ParameterTypeRequiredDescription
filters.decisionstringNoFilter by decision: allow, warn, block, require_approval
filters.limitnumberNoMax results (default 20, max 100)
filters.offsetnumberNoPagination offset

Returns: Promise<{ decisions: Object[], total: number, stats: { total_24h, blocks_24h, warns_24h, approvals_24h } }>

const { decisions, stats } = await claw.getGuardDecisions({
  decision: 'block',
  limit: 10,
});

console.log(`${stats.blocks_24h} blocks in last 24h`);

Policy Types

risk_thresholdBlock or warn when an action's risk score exceeds a configured threshold
require_approvalRequire human approval for specific action types (e.g., deploy, security)
block_action_typeUnconditionally block specific action types from executing
rate_limitWarn or block when an agent exceeds a configured action frequency
webhook_checkCall an external HTTPS endpoint for custom decision logic (can only escalate severity, never downgrade)

Policies are configured per-org via the Policies page in the dashboard. The guard endpoint evaluates all active policies and returns the strictest applicable decision.

Dashboard Data

Push data from your agent directly to the DashClaw dashboard. All methods auto-attach the agent's agentId.

claw.reportTokenUsage(usage)

Report token and model-usage snapshots for cost/burn-rate analytics. API remains available even when token widgets are disabled in certain dashboard modes.

ParameterTypeRequiredDescription
tokens_innumberYesInput tokens consumed
tokens_outnumberYesOutput tokens generated
context_usednumberNoContext window tokens used
context_maxnumberNoMaximum context window size
modelstringNoModel identifier (e.g., gpt-4o-mini)

Returns: Promise<{ snapshot: Object }>

await claw.reportTokenUsage({
  tokens_in: 1234,
  tokens_out: 980,
  context_used: 2214,
  context_max: 128000,
  model: 'gpt-4o',
});

claw.wrapClient(llmClient, options?)

Wrap an Anthropic or OpenAI client to auto-report token usage after every call. Returns the same client instance. Streaming calls are safely ignored.

ParameterTypeRequiredDescription
llmClientObjectYesAn Anthropic or OpenAI SDK client instance
options.providerstringNoForce 'anthropic' or 'openai' if auto-detect fails

Returns: Object (the wrapped client)

import Anthropic from '@anthropic-ai/sdk';

const anthropic = claw.wrapClient(new Anthropic());
const msg = await anthropic.messages.create({
  model: 'claude-sonnet-4-20250514',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello' }],
});
// Token usage auto-reported to DashClaw

claw.recordDecision(entry)

Record a decision for the learning database. Track what your agent decides and why.

ParameterTypeRequiredDescription
decisionstringYesWhat was decided
contextstringNoContext around the decision
reasoningstringNoWhy this decision was made
outcomestringNo"success", "failure", or "pending"
confidencenumberNoConfidence level 0-100

Returns: Promise<{ decision: Object }>

await claw.recordDecision({
  decision: 'Use Redis for session caching',
  reasoning: 'Lower latency than Postgres for read-heavy access pattern',
  confidence: 85,
});

claw.createGoal(goal)

Create a goal in the goals tracker.

ParameterTypeRequiredDescription
titlestringYesGoal title
categorystringNoGoal category
descriptionstringNoDetailed description
target_datestringNoTarget completion date (ISO string)
progressnumberNoProgress 0-100
statusstringNo"active", "completed", or "paused"

Returns: Promise<{ goal: Object }>

await claw.createGoal({
  title: 'Complete API migration',
  category: 'engineering',
  target_date: '2025-03-01T00:00:00.000Z',
  progress: 30,
});

claw.recordContent(content)

Record content creation (articles, posts, documents).

ParameterTypeRequiredDescription
titlestringYesContent title
platformstringNoPlatform (e.g., "linkedin", "twitter")
statusstringNo"draft" or "published"
urlstringNoPublished URL

Returns: Promise<{ content: Object }>

await claw.recordContent({
  title: 'How We Migrated to Edge Functions',
  platform: 'linkedin',
  status: 'published',
  url: 'https://linkedin.com/posts/...',
});

claw.recordInteraction(interaction)

Record a relationship interaction (message, meeting, email).

ParameterTypeRequiredDescription
summarystringYesWhat happened
contact_namestringNoContact name (auto-resolves to contact_id)
contact_idstringNoDirect contact ID
directionstringNo"inbound" or "outbound"
typestringNoInteraction type (e.g., "message", "meeting", "email")
platformstringNoPlatform used

Returns: Promise<{ interaction: Object }>

await claw.recordInteraction({
  contact_name: 'Jane Smith',
  summary: 'Discussed Q1 roadmap and timeline',
  type: 'meeting',
  direction: 'outbound',
});

claw.reportConnections(connections)

Report active connections/integrations for this agent. Call at agent startup to register what services the agent is connected to.

ParameterTypeRequiredDescription
connectionsObject[]YesArray of connection objects
connections[].providerstringYesService name (e.g., "anthropic", "github")
connections[].authTypestringNoAuth method: api_key, subscription, oauth, pre_configured, environment
connections[].planNamestringNoPlan name (e.g., "Pro Max")
connections[].statusstringNoConnection status: active, inactive, error
connections[].metadataObject|stringNoOptional metadata (e.g., { cost: "$100/mo" })

Returns: Promise<{ connections: Object[], created: number }>

await claw.reportConnections([
  { provider: 'anthropic', authType: 'subscription', planName: 'Pro Max', status: 'active' },
  { provider: 'github', authType: 'oauth', status: 'active' },
  { provider: 'slack', authType: 'api_key', status: 'active', metadata: { workspace: 'eng-team' } },
]);

claw.createCalendarEvent(event)

Create a calendar event.

ParameterTypeRequiredDescription
summarystringYesEvent title/summary
start_timestringYesStart time (ISO string)
end_timestringNoEnd time (ISO string)
locationstringNoEvent location
descriptionstringNoEvent description

Returns: Promise<{ event: Object }>

await claw.createCalendarEvent({
  summary: 'Deploy review',
  start_time: '2025-02-10T14:00:00.000Z',
  end_time: '2025-02-10T14:30:00.000Z',
  description: 'Review prod deploy results',
});

claw.recordIdea(idea)

Record an idea or inspiration for later review.

ParameterTypeRequiredDescription
titlestringYesIdea title
descriptionstringNoDetailed description
categorystringNoCategory (e.g., "feature", "optimization", "content")
scorenumberNoPriority/quality score 0-100 (default: 50)
statusstringNo"pending", "in_progress", "shipped", "rejected"
sourcestringNoWhere this idea came from

Returns: Promise<{ idea: Object }>

await claw.recordIdea({
  title: 'Auto-summarize daily agent activity',
  category: 'feature',
  score: 75,
  source: 'User feedback in Slack #agents',
});

claw.reportMemoryHealth(report)

Report memory health snapshot with entities and topics. Call periodically (e.g., daily) to track memory system health over time.

ParameterTypeRequiredDescription
healthObjectYesHealth metrics object
health.scorenumberYesHealth score 0-100
health.total_filesnumberNoNumber of memory files
health.total_linesnumberNoTotal lines across all files
health.total_size_kbnumberNoTotal size in KB
health.duplicatesnumberNoPotential duplicate facts
health.stale_countnumberNoStale facts count
entitiesObject[]NoKey entities found in memory
topicsObject[]NoTopics/themes found in memory

Returns: Promise<{ snapshot: Object, entities_count: number, topics_count: number }>

await claw.reportMemoryHealth({
  health: {
    score: 82,
    total_files: 15,
    total_lines: 340,
    duplicates: 3,
    stale_count: 7,
  },
  entities: [
    { name: 'PostgreSQL', type: 'service', mentions: 12 },
    { name: 'auth-service', type: 'service', mentions: 8 },
  ],
  topics: [
    { name: 'deployment', mentions: 15 },
    { name: 'authentication', mentions: 9 },
  ],
});

Session Handoffs

Create structured session handoff documents for continuity between agent sessions.

createHandoff(handoff)

Create a session handoff document summarizing work done, decisions made, and next priorities.

ParameterTypeRequiredDescription
summarystringYesSession summary
session_datestringNoDate string (defaults to today)
key_decisionsstring[]NoKey decisions made this session
open_tasksstring[]NoTasks still open
mood_notesstringNoUser mood/energy observations
next_prioritiesstring[]NoWhat to focus on next

Returns: Promise<{handoff: Object, handoff_id: string}>

await claw.createHandoff({
  summary: 'Completed auth system overhaul',
  key_decisions: ['JWT over sessions', 'Added refresh tokens'],
  open_tasks: ['Write migration guide', 'Load test'],
  next_priorities: ['Deploy to staging'],
});

getHandoffs(filters?)

Get handoffs for this agent with optional date and limit filters.

ParameterTypeRequiredDescription
datestringNoFilter by session_date
limitnumberNoMax results

Returns: Promise<{handoffs: Object[], total: number}>

const { handoffs } = await claw.getHandoffs({ limit: 5 });

getLatestHandoff()

Get the most recent handoff for this agent. Useful at session start to restore context.

Returns: Promise<{handoff: Object|null}>

const { handoff } = await claw.getLatestHandoff();
if (handoff) {
  console.log('Last session:', handoff.summary);
  console.log('Open tasks:', JSON.parse(handoff.open_tasks));
}

Context Manager

Capture key points and organize context into threads for long-running topics.

captureKeyPoint(point)

Capture a key point from the current session for later recall.

ParameterTypeRequiredDescription
contentstringYesThe key point content
categorystringNoOne of: decision, task, insight, question, general
importancenumberNoImportance 1-10 (default 5)
session_datestringNoDate string (defaults to today)

Returns: Promise<{point: Object, point_id: string}>

await claw.captureKeyPoint({
  content: 'User wants dark mode as the default theme',
  category: 'decision',
  importance: 8,
});

getKeyPoints(filters?)

Get key points with optional category and date filters.

ParameterTypeRequiredDescription
categorystringNoFilter by category
session_datestringNoFilter by date
limitnumberNoMax results

Returns: Promise<{points: Object[], total: number}>

const { points } = await claw.getKeyPoints({ category: 'decision' });

createThread(thread)

Create a context thread for tracking a topic across multiple entries.

ParameterTypeRequiredDescription
namestringYesThread name (unique per agent per org)
summarystringNoInitial summary

Returns: Promise<{thread: Object, thread_id: string}>

const { thread_id } = await claw.createThread({ name: 'Auth System', summary: 'Tracking auth decisions' });

addThreadEntry(threadId, content, entryType?)

Add an entry to an existing thread.

ParameterTypeRequiredDescription
threadIdstringYesThread ID
contentstringYesEntry content
entryTypestringNoEntry type (default: note)

Returns: Promise<{entry: Object, entry_id: string}>

await claw.addThreadEntry(threadId, 'Decided on JWT strategy');

closeThread(threadId, summary?)

Close a thread with an optional final summary.

ParameterTypeRequiredDescription
threadIdstringYesThread ID
summarystringNoFinal summary

Returns: Promise<{thread: Object}>

await claw.closeThread(threadId, 'Auth complete: JWT + refresh tokens');

getThreads(filters?)

Get threads with optional status filter.

ParameterTypeRequiredDescription
statusstringNoFilter: active or closed
limitnumberNoMax results

Returns: Promise<{threads: Object[], total: number}>

const { threads } = await claw.getThreads({ status: 'active' });

getContextSummary()

Get a combined view of today's key points and active threads.

Returns: Promise<{points: Object[], threads: Object[]}>

const { points, threads } = await claw.getContextSummary();

Automation Snippets

Save, search, and reuse code snippets across agent sessions.

saveSnippet(snippet)

Save or update a reusable code snippet. Upserts on name.

ParameterTypeRequiredDescription
namestringYesSnippet name (unique per org)
codestringYesThe snippet code
descriptionstringNoWhat this snippet does
languagestringNoProgramming language
tagsstring[]NoTags for categorization

Returns: Promise<{snippet: Object, snippet_id: string}>

await claw.saveSnippet({
  name: 'fetch-with-retry',
  code: 'async function fetchRetry(url, n = 3) { ... }',
  language: 'javascript',
  tags: ['fetch', 'retry'],
});

getSnippets(filters?)

Search and list snippets.

ParameterTypeRequiredDescription
searchstringNoSearch name/description
tagstringNoFilter by tag
languagestringNoFilter by language
limitnumberNoMax results

Returns: Promise<{snippets: Object[], total: number}>

const { snippets } = await claw.getSnippets({ language: 'javascript' });

getSnippet(snippetId)

Fetch a single snippet by ID.

ParameterTypeRequiredDescription
snippetIdstringYesSnippet ID

Returns: Promise<{snippet: Object}>

const { snippet } = await claw.getSnippet('sn_abc123');
console.log(snippet.name, snippet.language);

useSnippet(snippetId)

Mark a snippet as used (increments use_count).

ParameterTypeRequiredDescription
snippetIdstringYesSnippet ID

Returns: Promise<{snippet: Object}>

await claw.useSnippet('sn_abc123');

deleteSnippet(snippetId)

Delete a snippet.

ParameterTypeRequiredDescription
snippetIdstringYesSnippet ID

Returns: Promise<{deleted: boolean, id: string}>

await claw.deleteSnippet('sn_abc123');

User Preferences

Track user observations, learned preferences, mood, and successful approaches.

logObservation(obs)

Log something you noticed about the user.

ParameterTypeRequiredDescription
observationstringYesThe observation text
categorystringNoCategory tag
importancenumberNoImportance 1-10

Returns: Promise<{observation: Object}>

await claw.logObservation({ observation: 'Prefers tabs over spaces', category: 'coding', importance: 6 });

setPreference(pref)

Record a learned user preference.

ParameterTypeRequiredDescription
preferencestringYesPreference description
categorystringNoCategory tag
confidencenumberNoConfidence 0-100

Returns: Promise<{preference: Object}>

await claw.setPreference({ preference: 'Prefers concise responses', confidence: 90 });

logMood(entry)

Log user mood and energy level.

ParameterTypeRequiredDescription
moodstringYesMood (e.g., focused, frustrated)
energystringNoEnergy level (high, low)
notesstringNoAdditional notes

Returns: Promise<{mood: Object}>

await claw.logMood({ mood: 'focused', energy: 'high' });

trackApproach(entry)

Track an approach and whether it worked. Upserts on repeated calls, updating success/fail counts.

ParameterTypeRequiredDescription
approachstringYesApproach description
contextstringNoWhen to use this
successbooleanNotrue = worked, false = failed

Returns: Promise<{approach: Object}>

await claw.trackApproach({ approach: 'Show code before explanation', success: true });

getPreferenceSummary()

Get a summary of all user preference data for this agent.

Returns: Promise<{summary: Object}>

const { summary } = await claw.getPreferenceSummary();

getApproaches(filters?)

Get tracked approaches ranked by success count.

ParameterTypeRequiredDescription
limitnumberNoMax results

Returns: Promise<{approaches: Object[], total: number}>

const { approaches } = await claw.getApproaches({ limit: 10 });

Daily Digest

Aggregated daily summary from all data sources. No new storage needed.

getDailyDigest(date?)

Get a daily activity digest aggregated from actions, decisions, lessons, content, ideas, interactions, and goals.

ParameterTypeRequiredDescription
datestringNoYYYY-MM-DD (defaults to today)

Returns: Promise<{date: string, digest: Object, summary: Object}>

const { digest, summary } = await claw.getDailyDigest();
console.log(`Today: ${summary.action_count} actions, ${summary.decision_count} decisions`);

Security Scanning

Scan text for sensitive data (API keys, tokens, PII) and prompt injection attacks before sending it externally. Content is never stored; only metadata is retained.

scanContent(text, destination?)

Scan text for sensitive data. Returns findings and redacted text. Does not store anything.

ParameterTypeRequiredDescription
textstringYesText to scan
destinationstringNoWhere text is headed (context)

Returns: Promise<{clean: boolean, findings_count: number, findings: Object[], redacted_text: string}>

const result = await claw.scanContent(messageText, 'slack');
if (!result.clean) {
  console.warn(`Found ${result.findings_count} issues`);
  messageText = result.redacted_text; // Use redacted version
}

reportSecurityFinding(text, destination?)

Same as scanContent but stores finding metadata (never the content) for audit trails.

ParameterTypeRequiredDescription
textstringYesText to scan
destinationstringNoWhere text is headed

Returns: Promise<{clean: boolean, findings_count: number, findings: Object[], redacted_text: string}>

await claw.reportSecurityFinding(outboundMessage, 'email');

scanPromptInjection(text, options?)

Scan text for prompt injection attacks — role overrides, delimiter injection, instruction smuggling, data exfiltration attempts, and encoding evasion. Returns risk level and actionable recommendation (allow/warn/block).

ParameterTypeRequiredDescription
textstringYesText to scan for injection attacks
options.sourcestringNoWhere this text came from (e.g. user_input, tool_output, retrieval)

Returns: Promise<{clean: boolean, risk_level: string, recommendation: string, findings_count: number, categories: string[], findings: Object[]}>

const result = await claw.scanPromptInjection(userMessage, { source: 'user_input' });
if (result.recommendation === 'block') {
  console.error(`Blocked: ${result.findings_count} injection patterns detected`);
} else if (result.recommendation === 'warn') {
  console.warn(`Warning: ${result.categories.join(', ')} detected`);
}

Agent Messaging

Direct inter-agent messaging with inbox semantics, conversation threads, shared workspace documents, and broadcast capability.

sendMessage({ to, type, subject, body, threadId?, urgent?, docRef? })

Send a message to another agent. Omit 'to' to broadcast to all agents.

ParameterTypeRequiredDescription
tostringNoTarget agent ID (null = broadcast)
typestringNoMessage type: action|info|lesson|question|status (default: info)
subjectstringNoSubject line (max 200 chars)
bodystringYesMessage body (max 2000 chars)
threadIdstringNoThread ID to attach to
urgentbooleanNoMark as urgent
docRefstringNoReference to a shared doc ID

Returns: Promise<{message: Object, message_id: string}>

await claw.sendMessage({
  to: 'ops-agent',
  type: 'question',
  subject: 'Deploy approval needed',
  body: 'Auth service ready for prod. Please review.',
  urgent: true,
});

getInbox({ type?, unread?, threadId?, limit? })

Get inbox messages for this agent (direct + broadcasts, excluding archived).

ParameterTypeRequiredDescription
typestringNoFilter by message type
unreadbooleanNoOnly unread messages
threadIdstringNoFilter by thread
limitnumberNoMax messages (default: 50)

Returns: Promise<{messages: Object[], total: number, unread_count: number}>

const { messages, unread_count } = await claw.getInbox({ unread: true });
console.log(`${unread_count} unread messages`);

getSentMessages({ type?, threadId?, limit? })

Get messages sent by this agent.

ParameterTypeRequiredDescription
typestringNoFilter by message type
threadIdstringNoFilter by thread
limitnumberNoMax messages (default: 50)

Returns: Promise<{messages: Object[], total: number}>

const { messages } = await claw.getSentMessages({ type: 'action' });

getMessages({ direction?, type?, unread?, threadId?, limit? })

Flexible message query. direction: 'inbox' (default), 'sent', or 'all'.

ParameterTypeRequiredDescription
directionstringNo'inbox' (default), 'sent', or 'all'
typestringNoFilter by message type
unreadbooleanNoOnly unread messages (inbox direction only)
threadIdstringNoFilter by thread
limitnumberNoMax messages (default: 50)

Returns: Promise<{messages: Object[], total: number, unread_count: number}>

const { messages } = await claw.getMessages({ direction: 'all', type: 'question' });

getMessage(messageId)

Fetch a single message by ID.

ParameterTypeRequiredDescription
messageIdstringYesMessage ID

Returns: Promise<{message: Object}>

const { message } = await claw.getMessage('msg_abc123');

markRead(messageIds)

Mark one or more messages as read.

ParameterTypeRequiredDescription
messageIdsstring[]YesArray of message IDs

Returns: Promise<{updated: number}>

await claw.markRead(['msg_abc123', 'msg_def456']);

archiveMessages(messageIds)

Archive messages (removes from inbox).

ParameterTypeRequiredDescription
messageIdsstring[]YesArray of message IDs

Returns: Promise<{updated: number}>

await claw.archiveMessages(['msg_abc123']);

broadcast({ type, subject, body, threadId? })

Broadcast a message to all agents in the organization.

ParameterTypeRequiredDescription
typestringNoMessage type (default: info)
subjectstringNoSubject line
bodystringYesMessage body
threadIdstringNoThread ID

Returns: Promise<{message: Object, message_id: string}>

await claw.broadcast({
  type: 'status',
  subject: 'Deployment complete',
  body: 'Auth service v2.1 deployed to production.',
});

createMessageThread({ name, participants? })

Start a new conversation thread.

ParameterTypeRequiredDescription
namestringYesThread name
participantsstring[]NoAgent IDs (null = open to all)

Returns: Promise<{thread: Object, thread_id: string}>

const { thread_id } = await claw.createMessageThread({
  name: 'Auth Service Migration',
  participants: ['ops-agent', 'security-agent'],
});

getMessageThreads({ status?, limit? })

List message threads this agent participates in.

ParameterTypeRequiredDescription
statusstringNoFilter: open|resolved|archived
limitnumberNoMax threads (default: 20)

Returns: Promise<{threads: Object[], total: number}>

const { threads } = await claw.getMessageThreads({ status: 'open' });

resolveMessageThread(threadId, summary?)

Close a conversation thread with an optional summary.

ParameterTypeRequiredDescription
threadIdstringYesThread ID
summarystringNoResolution summary

Returns: Promise<{thread: Object}>

await claw.resolveMessageThread('mt_abc123', 'Migration completed successfully.');

saveSharedDoc({ name, content })

Create or update a shared workspace document. Upserts by name; updates increment the version.

ParameterTypeRequiredDescription
namestringYesDocument name (unique per org)
contentstringYesDocument content

Returns: Promise<{doc: Object, doc_id: string}>

await claw.saveSharedDoc({
  name: 'runbook/auth-deploy',
  content: '# Auth Deploy Runbook\n\n1. Run migrations...',
});

getAttachmentUrl(attachmentId)

Get a URL to download an attachment.

ParameterTypeRequiredDescription
attachmentIdstringYesAttachment ID (att_*)

Returns: string: URL to fetch the attachment binary

const url = claw.getAttachmentUrl('att_abc123');
console.log(url); // https://dashclaw.example.com/api/attachments/att_abc123

getAttachment(attachmentId)

Download an attachment as a Buffer.

ParameterTypeRequiredDescription
attachmentIdstringYesAttachment ID (att_*)

Returns: Promise<{ data: Buffer, filename: string, mimeType: string }>

const { data, filename, mimeType } = await claw.getAttachment('att_abc123');
fs.writeFileSync(filename, data);

Bulk Sync

Push multiple data categories in a single request. Ideal for bootstrapping agent state or periodic state snapshots. Every key is optional. Only provided categories are processed. Each category is independent; partial failures in one category don't block others.

syncState(state)

Sync multiple data categories in a single request. Accepts connections, memory, goals, learning, content, inspiration, context_points, context_threads, handoffs, preferences, and snippets.

ParameterTypeRequiredDescription
state.connectionsObject[]NoService connections (max 50)
state.memoryObjectNo{ health, entities[], topics[] }
state.goalsObject[]NoGoals (max 100)
state.learningObject[]NoDecisions/lessons (max 100)
state.context_pointsObject[]NoKey points (max 200)
state.context_threadsObject[]NoThreads (max 50, upserts by name)
state.snippetsObject[]NoCode snippets (max 50, upserts by name)
state.handoffsObject[]NoSession handoffs (max 50)
state.preferencesObjectNo{ observations[], preferences[], moods[], approaches[] }
state.contentObject[]NoContent items (max 100)
state.inspirationObject[]NoIdeas (max 100)

Returns: Promise<{results: Object, total_synced: number, total_errors: number, duration_ms: number}>

const result = await claw.syncState({
  connections: [
    { provider: 'github', auth_type: 'oauth', status: 'active' },
    { provider: 'neon', auth_type: 'api_key', status: 'active' },
  ],
  goals: [
    { title: 'Deploy v2', status: 'active' },
  ],
  learning: [
    { decision: 'Used JWT for Edge compat', reasoning: 'NextAuth on Vercel Edge' },
  ],
  context_points: [
    { content: 'Dark-only theme', category: 'insight', importance: 7 },
  ],
});
console.log(`Synced ${result.total_synced} items in ${result.duration_ms}ms`);

Policy Testing

Run guardrails tests, generate compliance proof reports, and import policy packs.

claw.testPolicies()

Run guardrails tests against all active policies for the organization. Returns a summary of which policies passed and which failed.

Returns: Promise<{ success: boolean, totals: number, passed: number, failed: number }>

const result = await claw.testPolicies();
console.log(`${result.passed}/${result.totals} policies passed`);
if (!result.success) {
  console.warn(`${result.failed} policies failed validation`);
}

claw.getProofReport(options?)

Generate a compliance proof report summarizing policy test results, guard decisions, and overall posture. Useful for audits and stakeholder reporting.

ParameterTypeRequiredDescription
options.formatstringNoReport format: "json" or "md" (default: "json")

Returns: Promise<{ report: Object }>

// JSON format (default)
const { report } = await claw.getProofReport();

// Markdown format for sharing
const { report: mdReport } = await claw.getProofReport({ format: 'md' });

claw.importPolicies({ pack?, yaml? })

Import a named policy pack or raw YAML policy definitions. Admin only. Existing policies with the same name are skipped.

ParameterTypeRequiredDescription
packstringNoNamed policy pack to import (e.g., "enterprise-strict")
yamlstringNoRaw YAML policy definitions to import

Returns: Promise<{ imported: number, skipped: number, errors: string[] }>

// Import a named pack
const result = await claw.importPolicies({ pack: 'enterprise-strict' });
console.log(`Imported ${result.imported}, skipped ${result.skipped}`);

// Import raw YAML
const yaml = `
- name: block-high-risk
  type: risk_threshold
  threshold: 80
  action: block
`;
await claw.importPolicies({ yaml });

Compliance Engine

Map policies to compliance frameworks, run gap analysis, generate reports, and collect evidence.

claw.mapCompliance(framework)

Map your active policies to controls in a compliance framework. Shows which controls are covered and which are not.

ParameterTypeRequiredDescription
frameworkstringYesFramework identifier (e.g., "nist-ai-rmf", "eu-ai-act", "iso-42001")

Returns: Promise<{ compliance_map: Object }>

const { compliance_map } = await claw.mapCompliance('nist-ai-rmf');
console.log('Covered controls:', compliance_map.covered);
console.log('Uncovered controls:', compliance_map.uncovered);

claw.analyzeGaps(framework)

Run a gap analysis against a compliance framework. Returns identified gaps with severity ratings and a remediation plan.

ParameterTypeRequiredDescription
frameworkstringYesFramework identifier

Returns: Promise<{ gap_analysis: Object }>

const { gap_analysis } = await claw.analyzeGaps('eu-ai-act');
console.log('Gaps found:', gap_analysis.gaps.length);
for (const gap of gap_analysis.gaps) {
  console.log(`[${gap.severity}] ${gap.control}: ${gap.remediation}`);
}

claw.getComplianceReport(framework, options?)

Generate a full compliance report and snapshot for a framework. Combines policy mapping, gap analysis, and evidence into a single document.

ParameterTypeRequiredDescription
frameworkstringYesFramework identifier
options.formatstringNoReport format: "json" or "md" (default: "json")

Returns: Promise<{ report: Object }>

const { report } = await claw.getComplianceReport('iso-42001');
console.log('Overall score:', report.score);
console.log('Status:', report.status);

claw.listFrameworks()

List all available compliance frameworks that can be used for mapping, gap analysis, and reporting.

Returns: Promise<{ frameworks: Object[] }>

const { frameworks } = await claw.listFrameworks();
for (const fw of frameworks) {
  console.log(`${fw.id}: ${fw.name} (${fw.controls_count} controls)`);
}

claw.getComplianceEvidence(options?)

Get live compliance evidence collected from guard decisions, policy tests, and agent activity within a time window.

ParameterTypeRequiredDescription
options.windowstringNoTime window for evidence collection (default: "30d")

Returns: Promise<{ evidence: Object }>

const { evidence } = await claw.getComplianceEvidence({ window: '7d' });
console.log('Evidence items:', evidence.items.length);
console.log('Coverage:', evidence.coverage_pct + '%');

Task Routing

Register agents with capabilities, submit tasks for intelligent routing, and track routing health and statistics.

claw.listRoutingAgents(filters?)

List registered routing agents with optional status filter.

ParameterTypeRequiredDescription
filters.statusstringNoFilter by status: available, busy, offline

Returns: Promise<{ agents: Object[] }>

const { agents } = await claw.listRoutingAgents({ status: 'available' });
console.log(`${agents.length} agents available for tasks`);

claw.registerRoutingAgent(agent)

Register an agent for task routing with its capabilities and concurrency limits.

ParameterTypeRequiredDescription
namestringYesAgent name
capabilitiesstring[]NoList of skills/capabilities (e.g., ["code-review", "deploy"])
maxConcurrentnumberNoMaximum concurrent tasks (default: 1)
endpointstringNoWebhook endpoint for task notifications

Returns: Promise<{ agent: Object }>

const { agent } = await claw.registerRoutingAgent({
  name: 'deploy-agent',
  capabilities: ['deploy', 'rollback', 'health-check'],
  maxConcurrent: 3,
  endpoint: 'https://my-agent.example.com/tasks',
});

claw.getRoutingAgent(agentId)

Get a single routing agent by ID, including current metrics and task counts.

ParameterTypeRequiredDescription
agentIdstringYesAgent ID

Returns: Promise<{ agent: Object }>

const { agent } = await claw.getRoutingAgent('ra_abc123');
console.log(agent.name, agent.status, agent.active_tasks);

claw.updateRoutingAgentStatus(agentId, status)

Update a routing agent's availability status.

ParameterTypeRequiredDescription
agentIdstringYesAgent ID
statusstringYesNew status: available, busy, or offline

Returns: Promise<{ agent: Object }>

await claw.updateRoutingAgentStatus('ra_abc123', 'busy');

claw.deleteRoutingAgent(agentId)

Delete a routing agent registration.

ParameterTypeRequiredDescription
agentIdstringYesAgent ID

Returns: Promise<{ deleted: Object }>

await claw.deleteRoutingAgent('ra_abc123');

claw.listRoutingTasks(filters?)

List routing tasks with optional filters for status, assignee, and pagination.

ParameterTypeRequiredDescription
filters.statusstringNoFilter by status: pending, assigned, completed, failed, timed_out
filters.assignedTostringNoFilter by assigned agent ID
filters.limitnumberNoMax results (default: 50)

Returns: Promise<{ tasks: Object[] }>

const { tasks } = await claw.listRoutingTasks({
  status: 'pending',
  limit: 10,
});

claw.submitRoutingTask(task)

Submit a task for intelligent routing. The system matches required skills to available agents and assigns automatically.

ParameterTypeRequiredDescription
titlestringYesTask title
descriptionstringNoTask description
requiredSkillsstring[]NoSkills needed to complete this task
urgencystringNoUrgency level: low, normal, high, critical (default: normal)
timeoutSecondsnumberNoTask timeout in seconds
maxRetriesnumberNoMaximum retry attempts on failure
callbackUrlstringNoWebhook URL for task completion notification

Returns: Promise<{ task: Object, routing: Object }>

const { task, routing } = await claw.submitRoutingTask({
  title: 'Deploy auth service v2',
  description: 'Deploy the latest auth service build to production',
  requiredSkills: ['deploy', 'kubernetes'],
  urgency: 'high',
  timeoutSeconds: 600,
  callbackUrl: 'https://my-app.example.com/hooks/task-done',
});
console.log(`Task ${task.id} assigned to ${routing.assigned_to}`);

claw.completeRoutingTask(taskId, result?)

Mark a routing task as completed with an optional result payload.

ParameterTypeRequiredDescription
taskIdstringYesTask ID
successbooleanNoWhether the task succeeded (default: true)
resultObjectNoResult data from task execution
errorstringNoError message if task failed

Returns: Promise<{ task: Object, routing: Object }>

// Success
await claw.completeRoutingTask('rt_abc123', {
  success: true,
  result: { deployed_version: '2.1.0', pods: 3 },
});

// Failure
await claw.completeRoutingTask('rt_abc123', {
  success: false,
  error: 'Health check failed after deploy',
});

claw.getRoutingStats()

Get aggregate routing statistics including agent counts, task counts, and routing performance metrics.

Returns: Promise<{ agents: Object, tasks: Object, routing: Object }>

const stats = await claw.getRoutingStats();
console.log(`Agents: ${stats.agents.total} (${stats.agents.available} available)`);
console.log(`Tasks: ${stats.tasks.total} (${stats.tasks.pending} pending)`);

claw.getRoutingHealth()

Get routing system health status, including agent availability and task queue depth.

Returns: Promise<{ status: string, agents: Object, tasks: Object }>

const health = await claw.getRoutingHealth();
console.log('Routing status:', health.status);
console.log('Available agents:', health.agents.available);
console.log('Queued tasks:', health.tasks.queued);

Agent Schedules

Define recurring tasks and cron-based schedules for agents. Visible in the workspace overview.

claw.listAgentSchedules(filters?)

List agent schedules, optionally filtered by agent.

ParameterTypeRequiredDescription
filters.agent_idstringNoFilter by agent ID

Returns: Promise<{ schedules: Object[] }>

const { schedules } = await claw.listAgentSchedules({ agent_id: 'forge' });
schedules.forEach(s => console.log(s.name, s.cron_expression));

claw.createAgentSchedule(schedule)

Create a new agent schedule entry.

ParameterTypeRequiredDescription
schedule.agent_idstringYesAgent this schedule belongs to
schedule.namestringYesSchedule name
schedule.cron_expressionstringYesCron expression (e.g. 0 */6 * * *)
schedule.descriptionstringNoHuman-readable description
schedule.enabledbooleanNoWhether schedule is active (default: true)

Returns: Promise<{ schedule: Object }>

const { schedule } = await claw.createAgentSchedule({
  agent_id: 'forge',
  name: 'Build projects',
  cron_expression: '0 */6 * * *',
  description: 'Check for pending builds every 6 hours'
});

Agent Pairing

One-click agent enrollment. Agents request pairing with a public key, admins approve via a click link.

claw.createPairing(options)

Create an agent pairing request. Returns a link the user can click to approve the agent.

ParameterTypeRequiredDescription
publicKeyPemstringYesPEM public key (SPKI format) to register for this agent
algorithmstringNoSigning algorithm (default: RSASSA-PKCS1-v1_5)
agentNamestringNoAgent display name

Returns: Promise<{ pairing: Object, pairing_url: string }>

claw.getPairing(pairingId)

Fetch a pairing request by ID.

ParameterTypeRequiredDescription
pairingIdstringYesPairing ID

Returns: Promise<{ pairing: Object }>

claw.createPairingFromPrivateJwk(privateJwk, options?)

Convenience method: derive a public PEM from a private JWK and create a pairing request in one step.

ParameterTypeRequiredDescription
privateJwkObjectYesPrivate key in JWK format
options.agentNamestringNoAgent display name

Returns: Promise<{ pairing: Object, pairing_url: string }>

claw.approveAction(actionId, decision, reasoning?)

Approve or deny a pending action as a human operator.

ParameterTypeRequiredDescription
actionIdstringYesAction ID to approve or deny
decisionstringYes'allow' or 'deny'
reasoningstringNoOptional explanation for the decision

Returns: Promise<{ action: Object }>

await claw.approveAction('act_abc123', 'allow', 'Reviewed and safe to proceed');

claw.getPendingApprovals({ limit?, offset? })

Get all actions currently waiting for human approval.

ParameterTypeRequiredDescription
limitnumberNoMax results (default: 20)
offsetnumberNoPagination offset

Returns: Promise<{ actions: Object[], total: number }>

const { actions } = await claw.getPendingApprovals({ limit: 10 });

claw.waitForPairing(pairingId, options?)

Poll a pairing request until it is approved or expires. Throws on timeout or expiration.

ParameterTypeRequiredDescription
pairingIdstringYesThe pairing ID to poll
options.timeoutnumberNoMax wait time in ms (default: 300000 / 5 min)
options.intervalnumberNoPoll interval in ms (default: 2000)

Returns: Promise<Object>

Identity Binding

Register and manage agent public keys for cryptographic action verification. Requires admin API key.

claw.registerIdentity(identity)

Register or update an agent's public key for identity verification. Upserts on agent_id.

ParameterTypeRequiredDescription
agent_idstringYesAgent ID to register
public_keystringYesPEM public key (SPKI format)
algorithmstringNoSigning algorithm (default: RSASSA-PKCS1-v1_5)

Returns: Promise<{ identity: Object }>

claw.getIdentities()

List all registered agent identities for this organization.

Returns: Promise<{ identities: Object[] }>

Organization Management

Manage organizations and API keys. All methods require an admin-role API key.

claw.getOrg()

Get the current organization's details.

Returns: Promise<{ organizations: Object[] }>

claw.createOrg(org)

Create a new organization with an initial admin API key. The new org always starts on the free plan.

ParameterTypeRequiredDescription
namestringYesOrganization name
slugstringYesURL-safe slug (lowercase alphanumeric + hyphens, max 64 chars)

Returns: Promise<{ organization: Object, api_key: Object }>

claw.getOrgById(orgId)

Get organization details by ID.

ParameterTypeRequiredDescription
orgIdstringYesOrganization ID

Returns: Promise<{ organization: Object }>

claw.updateOrg(orgId, updates)

Update organization details (name, slug).

ParameterTypeRequiredDescription
orgIdstringYesOrganization ID
updatesObjectYesFields to update (name, slug)

Returns: Promise<{ organization: Object }>

claw.getOrgKeys(orgId)

List API keys for an organization. Returns key metadata (prefix, role, label) but never the full key.

ParameterTypeRequiredDescription
orgIdstringYesOrganization ID

Returns: Promise<{ keys: Object[] }>

Activity Logs

Query the organization-wide activity audit log.

claw.getActivityLogs(filters?)

Get activity/audit logs for the organization. Returns paginated results with stats.

ParameterTypeRequiredDescription
actionstringNoFilter by action type
actor_idstringNoFilter by actor
resource_typestringNoFilter by resource type
beforestringNoBefore timestamp (ISO string)
afterstringNoAfter timestamp (ISO string)
limitnumberNoMax results (default: 50, max: 200)
offsetnumberNoPagination offset

Returns: Promise<{ logs: Object[], stats: Object, pagination: Object }>

Webhooks

Manage webhook subscriptions for real-time event delivery to your endpoints.

claw.getWebhooks()

List all webhooks for this organization.

Returns: Promise<{ webhooks: Object[] }>

claw.createWebhook(webhook)

Create a new webhook subscription.

ParameterTypeRequiredDescription
urlstringYesWebhook endpoint URL (must be HTTPS in production)
eventsstring[]NoEvent types to subscribe to

Returns: Promise<{ webhook: Object }>

claw.deleteWebhook(webhookId)

Delete a webhook subscription.

ParameterTypeRequiredDescription
webhookIdstringYesWebhook ID

Returns: Promise<{ deleted: boolean }>

claw.testWebhook(webhookId)

Send a test event to a webhook endpoint to verify connectivity.

ParameterTypeRequiredDescription
webhookIdstringYesWebhook ID

Returns: Promise<{ delivery: Object }>

claw.getWebhookDeliveries(webhookId)

Get delivery history for a webhook. Shows recent attempts, statuses, and response codes.

ParameterTypeRequiredDescription
webhookIdstringYesWebhook ID

Returns: Promise<{ deliveries: Object[] }>

Error Handling

All SDK methods throw on non-2xx responses. Errors include status (HTTP code) and details (when available).

Error shape
{
  message: "Validation failed",  // error.message
  status: 400,                    // error.status (HTTP status code)
  details: { ... }                // error.details (optional)
}
Recommended pattern
try {
  const { action_id } = await claw.createAction({
    action_type: 'deploy',
    declared_goal: 'Deploy to production',
  });
} catch (err) {
  if (err.status === 401) {
    console.error('Invalid API key');
  } else if (err.status === 429) {
    console.error('Rate limited. Slow down.');
  } else {
    console.error(`Action failed: ${err.message}`);
  }
}

Agent Tools (Python)

The agent-tools/ directory contains Python CLI tools that run locally alongside your agent. They track learning, goals, context, memory health, security, and more in local SQLite databases. Each tool supports an optional --push flag to sync data to your DashClaw dashboard.

Install & Configure

Run the installer for your platform, then configure dashboard sync (optional).

Mac / Linux
bash ./agent-tools/install-mac.sh
Windows (PowerShell)
powershell -ExecutionPolicy Bypass -File .\agent-tools\install-windows.ps1
Configure dashboard sync (optional)
# Copy and edit the config file
cp agent-tools/.env.example agent-tools/secrets/dashclaw.env

# Set your dashboard URL, API key, and agent ID
DASHCLAW_URL=http://localhost:3000  # or https://your-app.vercel.app
DASHCLAW_API_KEY=oc_live_...
DASHCLAW_AGENT_ID=my-agent

Tool Categories

Ops & Learning

learning-databaseerror-loggerdaily-digestapi-monitor

Context & Sessions

context-managersession-handoffopen-loops

Memory & Knowledge

memory-healthmemory-searchtoken-efficiency

Security & Audit

outbound-filtersession-isolatoraudit-logger

Relationships

relationship-trackercommunication-analyticsuser-context

Automation

automation-librarytoken-capturesync_to_dashclaw

Tool-to-SDK Mapping

Python CLI tools push to the same API endpoints as the JavaScript SDK methods.

Python ToolCommandAPI EndpointJS SDK Method
learner.pylog --pushPOST /api/learningrecordDecision()
goals.pyadd --pushPOST /api/goalscreateGoal()
tracker.pylog --pushPOST /api/relationshipsrecordInteraction()
scanner.pyscan --pushPOST /api/memoryreportMemoryHealth()
context.pycapture --pushPOST /api/context/pointscaptureKeyPoint()
context.pythread --pushPOST /api/context/threadscreateThread()
handoff.pycreate --pushPOST /api/handoffscreateHandoff()
snippets.pyadd --pushPOST /api/snippetssaveSnippet()
user_context.pynote --pushPOST /api/preferenceslogObservation()
loops.pyadd --pushPOST /api/actions/loopsregisterOpenLoop()
comms.pylog --pushPOST /api/relationshipsrecordInteraction()
errors.pylog --pushPOST /api/learningrecordDecision()
outbound_filter.pyscan --pushPOST /api/security/scanscanContent()

Bulk Sync

Sync all local data
# Preview what would sync
python agent-tools/tools/sync_to_dashclaw.py --dry-run

# Sync everything
python agent-tools/tools/sync_to_dashclaw.py

# Sync specific categories
python agent-tools/tools/sync_to_dashclaw.py --categories learning,goals,context_points