HomeSDK Documentation

SDK Documentation

Full reference for the DashClaw SDK. 57 methods to instrument your AI agents with action recording, context management, session handoffs, security scanning, 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: 'https://your-dashboard.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.

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. "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: 'https://your-app.vercel.app',
  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']
  }
}

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.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

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

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.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' });

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 — repeated calls update 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) before sending it externally. Content is never stored — only metadata.

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');

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`);

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...',
});

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`);

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=https://your-deployment.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