dashclaw 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2165 -2096
  2. package/dashclaw.js +2885 -2796
  3. package/package.json +46 -46
package/README.md CHANGED
@@ -1,2096 +1,2165 @@
1
- # DashClaw SDK: Agent Decision Infrastructure
2
-
3
- Full reference for the DashClaw SDK (Node.js). For Python, see the [Python SDK docs](../sdk-python/README.md).
4
-
5
- DashClaw treats every agent action as a governed decision. The SDK provides decision recording, policy enforcement, evaluation, and compliance mapping. It proves what your agents decided and why.
6
-
7
- Install, configure, and govern your AI agents with 178+ methods across 30+ categories including action recording, behavior guard, evaluation framework, scoring profiles, learning analytics, prompt management, feedback loops, behavioral drift, compliance exports, and more. Native adapters for **OpenClaw**, **CrewAI**, **AutoGen**, and **LangChain**.
8
-
9
- ---
10
-
11
- ## Quick Start
12
-
13
- ### 1. Copy the SDK
14
- Install from npm, or copy the single-file SDK directly.
15
- ```bash
16
- npm install dashclaw
17
- ```
18
-
19
- ### 2. Initialize the client
20
- ```javascript
21
- import { DashClaw } from 'dashclaw';
22
-
23
- const claw = new DashClaw({
24
- baseUrl: process.env.DASHCLAW_BASE_URL || 'http://localhost:3000',
25
- // Use http://localhost:3000 for local, or https://your-app.vercel.app for cloud
26
- apiKey: process.env.DASHCLAW_API_KEY,
27
- agentId: 'my-agent',
28
- agentName: 'My Agent',
29
- hitlMode: 'wait', // Optional: automatically wait for human approval
30
- });
31
- ```
32
-
33
- ### 3. Record your first action
34
- ```javascript
35
- // Create an action before doing work
36
- const { action_id } = await claw.createAction({
37
- action_type: 'deploy',
38
- declared_goal: 'Deploy authentication service',
39
- risk_score: 60,
40
- });
41
-
42
- // ... do the work ...
43
-
44
- // Update when done
45
- await claw.updateOutcome(action_id, {
46
- status: 'completed',
47
- output_summary: 'Auth service deployed to prod',
48
- });
49
- ```
50
-
51
- ---
52
-
53
- ## Constructor
54
-
55
- Create a DashClaw instance. Requires Node 18+ (native fetch).
56
-
57
- ```javascript
58
- const claw = new DashClaw({
59
- baseUrl,
60
- apiKey,
61
- agentId,
62
- agentName,
63
- swarmId,
64
- guardMode,
65
- guardCallback,
66
- autoRecommend,
67
- recommendationConfidenceMin,
68
- recommendationCallback,
69
- hitlMode,
70
- });
71
- ```
72
-
73
- ### Parameters
74
- | Parameter | Type | Required | Description |
75
- |-----------|------|----------|-------------|
76
- | baseUrl | string | Yes | DashClaw dashboard URL (e.g. "http://localhost:3000" or "https://your-app.vercel.app") |
77
- | apiKey | string | Yes | API key for authentication (determines which org\'s data you access) |
78
- | agentId | string | Yes | Unique identifier for this agent |
79
- | agentName | string | No | Human-readable agent name |
80
- | swarmId | string | No | Swarm/group identifier if part of a multi-agent system |
81
- | guardMode | string | No | Auto guard check before createAction/track: "off" (default), "warn" (log + proceed), "enforce" (throw on block) |
82
- | guardCallback | Function | No | Called with guard decision object when guardMode is active |
83
- | autoRecommend | string | No | Recommendation auto-adapt mode: "off" (default), "warn" (record override), "enforce" (apply safe hints) |
84
- | recommendationConfidenceMin | number | No | Min recommendation confidence required for auto-adapt in enforce mode (default 70) |
85
- | recommendationCallback | Function | No | Called with recommendation adaptation details when autoRecommend is active |
86
- | hitlMode | string | No | HITL behavior: "off" (default - return 202 immediately), "wait" (automatically block and poll until approved/denied) |
87
-
88
- ### Guard Mode, Auto-Recommend, and HITL
89
- When enabled, every call to `createAction()` can run recommendation adaptation and guard checks before submission.
90
-
91
- ```javascript
92
- import { DashClaw, GuardBlockedError, ApprovalDeniedError } from 'dashclaw';
93
-
94
- const claw = new DashClaw({
95
- baseUrl: 'http://localhost:3000',
96
- apiKey: process.env.DASHCLAW_API_KEY,
97
- agentId: 'my-agent',
98
- autoRecommend: 'enforce', // apply safe recommendation hints
99
- recommendationConfidenceMin: 80,
100
- guardMode: 'enforce', // throws GuardBlockedError on block
101
- hitlMode: 'wait', // poll until approved or throw ApprovalDeniedError
102
- });
103
-
104
- try {
105
- await claw.createAction({ action_type: 'deploy', declared_goal: 'Ship v2' });
106
- // If a policy triggers 'require_approval', the SDK will pause here until an admin clicks 'Allow'
107
- } catch (err) {
108
- if (err instanceof GuardBlockedError) {
109
- console.log('Blocked by policy:', err.reasons);
110
- } else if (err instanceof ApprovalDeniedError) {
111
- console.log('Denied by human operator');
112
- }
113
- }
114
- ```
115
-
116
- ### Compliance & Governance Patterns
117
-
118
- DashClaw's guard + action recording pipeline maps directly to compliance controls.
119
-
120
- **SOC 2 CC6.1: Logical Access Controls**
121
- ```javascript
122
- // Before any high-risk operation, enforce policy
123
- const guardResult = await claw.guard({
124
- action_type: 'database_write',
125
- risk_score: 85,
126
- systems_touched: ['production_db'],
127
- reversible: false,
128
- declared_goal: 'Drop legacy user table'
129
- });
130
-
131
- if (guardResult.decision === 'block') {
132
- // SOC 2 control satisfied: unauthorized action prevented
133
- console.log('Policy blocked:', guardResult.reasons);
134
- return;
135
- }
136
-
137
- // Decision is governed. Record with full lineage
138
- const { action_id } = await claw.createAction({
139
- action_type: 'database_write',
140
- declared_goal: 'Drop legacy user table',
141
- risk_score: 85,
142
- reversible: false,
143
- authorization_scope: 'admin-approved'
144
- });
145
-
146
- // Register the assumption this decision relies on
147
- await claw.registerAssumption({
148
- action_id,
149
- assumption: 'Legacy table has zero active references',
150
- basis: 'Schema dependency scan completed 2h ago'
151
- });
152
- ```
153
-
154
- **EU AI Act Article 14: Human Oversight**
155
- ```javascript
156
- // require_approval forces human-in-the-loop
157
- const result = await claw.guard({
158
- action_type: 'customer_communication',
159
- risk_score: 60,
160
- declared_goal: 'Send pricing update to 500 customers'
161
- });
162
-
163
- if (result.decision === 'require_approval') {
164
- // Create action in pending state, wait for human approval
165
- const { action_id } = await claw.createAction({
166
- action_type: 'customer_communication',
167
- declared_goal: 'Send pricing update to 500 customers',
168
- status: 'pending'
169
- });
170
- // Approval queue at /approvals shows this to operators
171
- }
172
- ```
173
-
174
- **ISO 42001: AI Decision Accountability**
175
- ```javascript
176
- // Full decision lineage: guard → action → assumptions → outcome
177
- const { action_id } = await claw.createAction({
178
- action_type: 'data_processing',
179
- declared_goal: 'Rebuild customer segmentation model',
180
- risk_score: 45,
181
- systems_touched: ['ml-pipeline', 'customer-db']
182
- });
183
-
184
- await claw.registerAssumption({
185
- action_id,
186
- assumption: 'Customer data is current as of today',
187
- basis: 'CRM sync completed at 09:00 UTC'
188
- });
189
-
190
- // Later: validate or invalidate assumptions
191
- await claw.validateAssumption(assumptionId, true);
192
-
193
- // Decision integrity signals auto-detect when assumptions drift
194
- const signals = await claw.getSignals();
195
- // → Returns 'assumption_drift' if too many invalidated
196
- ```
197
-
198
- ---
199
-
200
- ## Action Recording
201
-
202
- Create, update, and query action records. Every agent action is a governed decision with a full audit trail capturing intent, reasoning, and outcome for compliance and review.
203
-
204
- ### claw.createAction(action)
205
- Create a new action record. The agent's agentId, agentName, and swarmId are automatically attached.
206
-
207
- If `hitlMode` is set to `'wait'` and the action requires approval, this method will not return until the action is approved or denied (or it times out).
208
-
209
- **Parameters:**
210
- | Parameter | Type | Required | Description |
211
- |-----------|------|----------|-------------|
212
- | action_type | string | Yes | One of: build, deploy, post, apply, security, message, api, calendar, research, review, fix, refactor, test, config, monitor, alert, cleanup, sync, migrate, other |
213
- | declared_goal | string | Yes | What this action aims to accomplish |
214
- | action_id | string | No | Custom action ID (auto-generated act_ UUID if omitted) |
215
- | reasoning | string | No | Why the agent decided to take this action |
216
- | authorization_scope | string | No | What permissions were granted |
217
- | trigger | string | No | What triggered this action |
218
- | systems_touched | string[] | No | Systems this action interacts with |
219
- | input_summary | string | No | Summary of input data |
220
- | parent_action_id | string | No | Parent action if this is a sub-action |
221
- | reversible | boolean | No | Whether this action can be undone (default: true) |
222
- | risk_score | number | No | Risk score 0-100 (default: 0) |
223
- | confidence | number | No | Confidence level 0-100 (default: 50) |
224
-
225
- **Returns:** `Promise<{ action: Object, action_id: string }>`
226
-
227
- **Example:**
228
- ```javascript
229
- const { action_id } = await claw.createAction({
230
- action_type: 'deploy',
231
- declared_goal: 'Deploy auth service to production',
232
- risk_score: 70,
233
- systems_touched: ['kubernetes', 'auth-service'],
234
- reasoning: 'Scheduled release after QA approval',
235
- });
236
- ```
237
-
238
- ### claw.waitForApproval(actionId, options?)
239
- Manual poll for human approval. Only needed if `hitlMode` is `'off'`.
240
-
241
- **Parameters:**
242
- | Parameter | Type | Required | Description |
243
- |-----------|------|----------|-------------|
244
- | actionId | string | Yes | The action_id to poll |
245
- | options.timeout | number | No | Max wait time in ms (default: 300000 / 5 min) |
246
- | options.interval | number | No | Poll interval in ms (default: 5000) |
247
-
248
- **Returns:** `Promise<{ action: Object, action_id: string }>`
249
- **Throws:** `ApprovalDeniedError` if denied.
250
-
251
- ### claw.updateOutcome(actionId, outcome)
252
- Update the outcome of an existing action. Automatically sets timestamp_end if not provided.
253
-
254
- **Parameters:**
255
- | Parameter | Type | Required | Description |
256
- |-----------|------|----------|-------------|
257
- | actionId | string | Yes | The action_id to update |
258
- | status | string | No | New status: completed, failed, cancelled |
259
- | output_summary | string | No | What happened |
260
- | side_effects | string[] | No | Unintended consequences |
261
- | artifacts_created | string[] | No | Files, records, etc. created |
262
- | error_message | string | No | Error details if failed |
263
- | duration_ms | number | No | How long it took in milliseconds |
264
- | cost_estimate | number | No | Estimated cost in USD |
265
-
266
- **Returns:** `Promise<{ action: Object }>`
267
-
268
- ### claw.track(actionDef, fn)
269
- 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.
270
-
271
- **Parameters:**
272
- | Parameter | Type | Required | Description |
273
- |-----------|------|----------|-------------|
274
- | actionDef | Object | Yes | Action definition (same params as createAction) |
275
- | fn | Function | Yes | Async function to execute. Receives { action_id } as argument. |
276
-
277
- **Returns:** `Promise<*> (the return value of fn)`
278
-
279
- ### claw.getActions(filters?)
280
- Get a list of actions with optional filters. Returns paginated results with stats.
281
-
282
- **Parameters:**
283
- | Parameter | Type | Required | Description |
284
- |-----------|------|----------|-------------|
285
- | agent_id | string | No | Filter by agent |
286
- | swarm_id | string | No | Filter by swarm |
287
- | status | string | No | Filter by status (running, completed, failed, cancelled) |
288
- | action_type | string | No | Filter by type |
289
- | risk_min | number | No | Minimum risk score |
290
- | limit | number | No | Max results (default: 50) |
291
- | offset | number | No | Pagination offset (default: 0) |
292
-
293
- **Returns:** `Promise<{ actions: Object[], total: number, stats: Object }>`
294
-
295
- ### claw.getAction(actionId)
296
- Get a single action with its associated open loops and assumptions.
297
-
298
- **Parameters:**
299
- | Parameter | Type | Required | Description |
300
- |-----------|------|----------|-------------|
301
- | actionId | string | Yes | The action_id to retrieve |
302
-
303
- **Returns:** `Promise<{ action: Object, open_loops: Object[], assumptions: Object[] }>`
304
-
305
- ### claw.getActionTrace(actionId)
306
- Get root-cause trace for an action, including its assumptions, open loops, parent chain, and related actions.
307
-
308
- **Parameters:**
309
- | Parameter | Type | Required | Description |
310
- |-----------|------|----------|-------------|
311
- | actionId | string | Yes | The action_id to trace |
312
-
313
- **Returns:** `Promise<{ action: Object, trace: Object }>`
314
-
315
- ---
316
-
317
- ## Evaluation Framework
318
-
319
- Track output quality automatically with 5 built-in scorer types. No LLM required for most scorers.
320
-
321
- ### claw.createScorer({ name, scorerType, config, description })
322
- Create a new evaluation scorer.
323
-
324
- **Parameters:**
325
- | Parameter | Type | Required | Description |
326
- |-----------|------|----------|-------------|
327
- | name | string | Yes | Scorer name |
328
- | scorerType | string | Yes | regex, keywords, numeric_range, custom_function, or llm_judge |
329
- | config | Object | Yes | Configuration for the scorer |
330
- | description | string | No | Purpose of this scorer |
331
-
332
- **Returns:** `Promise<Object>`
333
-
334
- **Example:**
335
- ```javascript
336
- await claw.createScorer({
337
- name: 'JSON Validator',
338
- scorerType: 'regex',
339
- config: { pattern: '^\\{.*\\}$' },
340
- });
341
- ```
342
-
343
- ### claw.getScorers()
344
- List all available scorers.
345
-
346
- **Returns:** `Promise<{ scorers: Object[], llm_available: boolean }>`
347
-
348
- ### claw.getEvalRuns(filters?)
349
- List evaluation runs with status and result summaries.
350
-
351
- **Parameters:**
352
- | Parameter | Type | Required | Description |
353
- |-----------|------|----------|-------------|
354
- | status | string | No | running, completed, failed |
355
- | limit | number | No | Max results |
356
-
357
- **Returns:** `Promise<{ runs: Object[] }>`
358
-
359
- ### claw.getEvalStats(filters?)
360
- Get aggregate evaluation statistics across scorers and agents.
361
-
362
- **Parameters:**
363
- | Parameter | Type | Required | Description |
364
- |-----------|------|----------|-------------|
365
- | agent_id | string | No | Filter by agent |
366
- | scorer_name | string | No | Filter by scorer |
367
- | days | number | No | Lookback period |
368
-
369
- **Returns:** `Promise<Object>`
370
-
371
- ---
372
-
373
- ## Prompt Management
374
-
375
- Version-controlled prompt templates with mustache variable rendering.
376
-
377
- ### claw.createPromptTemplate({ name, content, category })
378
- Create a new prompt template.
379
-
380
- **Parameters:**
381
- | Parameter | Type | Required | Description |
382
- |-----------|------|----------|-------------|
383
- | name | string | Yes | Template name |
384
- | content | string | Yes | Template content with {{variables}} |
385
- | category | string | No | Optional grouping category |
386
-
387
- **Returns:** `Promise<Object>`
388
-
389
- ### claw.getPromptTemplate(templateId)
390
- Get a template by ID, including its current active version.
391
-
392
- **Returns:** `Promise<Object>`
393
-
394
- ### claw.renderPrompt({ template_id, variables, action_id })
395
- Render a template with variables on the server. Optionally link to an action for usage tracking.
396
-
397
- **Parameters:**
398
- | Parameter | Type | Required | Description |
399
- |-----------|------|----------|-------------|
400
- | template_id | string | Yes | Template ID |
401
- | variables | Object | Yes | Mustache variables |
402
- | action_id | string | No | Link to an action |
403
-
404
- **Returns:** `Promise<{ rendered: string }>`
405
-
406
- ### claw.listPromptVersions(templateId)
407
- List all versions of a prompt template.
408
-
409
- **Returns:** `Promise<Object[]>`
410
-
411
- ### claw.activatePromptVersion(templateId, versionId)
412
- Set a specific version as the active one for a template.
413
-
414
- **Returns:** `Promise<Object>`
415
-
416
- ---
417
-
418
- ## User Feedback
419
-
420
- Collect and analyze human feedback on agent actions.
421
-
422
- ### claw.submitFeedback({ action_id, agent_id, rating, comment, category, tags })
423
- Submit feedback for a specific action.
424
-
425
- **Parameters:**
426
- | Parameter | Type | Required | Description |
427
- |-----------|------|----------|-------------|
428
- | action_id | string | Yes | Action ID |
429
- | agent_id | string | No | Agent ID |
430
- | rating | number | Yes | Rating 1-5 |
431
- | comment | string | No | Optional text feedback |
432
- | category | string | No | Optional category |
433
- | tags | string[] | No | Optional tags |
434
-
435
- **Returns:** `Promise<Object>`
436
-
437
- ### claw.getFeedback(feedbackId)
438
- Retrieve a single feedback entry.
439
-
440
- **Returns:** `Promise<Object>`
441
-
442
- ### claw.getFeedbackStats({ agent_id })
443
- Get feedback statistics, including average rating and sentiment trends.
444
-
445
- **Returns:** `Promise<Object>`
446
-
447
- ---
448
-
449
- ## Behavioral Drift
450
-
451
- Monitor agent behavior deviations from statistical baselines using z-scores.
452
-
453
- ### claw.computeDriftBaselines({ agent_id, lookback_days })
454
- Establish statistical baselines for an agent's behavior metrics.
455
-
456
- **Returns:** `Promise<Object>`
457
-
458
- ### claw.detectDrift({ agent_id, window_days })
459
- Run drift detection against the established baselines.
460
-
461
- **Returns:** `Promise<Object>`
462
-
463
- ### claw.listDriftAlerts(filters?)
464
- List behavioral drift alerts with severity and status.
465
-
466
- **Returns:** `Promise<Object[]>`
467
-
468
- ---
469
-
470
- ## Compliance Exports
471
-
472
- Generate evidence packages for SOC 2, NIST AI RMF, EU AI Act, and ISO 42001.
473
-
474
- ### claw.createComplianceExport({ name, frameworks, format, window_days })
475
- Generate a compliance export bundle.
476
-
477
- **Returns:** `Promise<Object>`
478
-
479
- ### claw.getComplianceExport(exportId)
480
- Get the status and details of a compliance export.
481
-
482
- **Returns:** `Promise<Object>`
483
-
484
- ### claw.listComplianceExports({ limit })
485
- List recent compliance exports.
486
-
487
- **Returns:** `Promise<Object[]>`
488
-
489
- ---
490
-
491
- ## Learning Analytics
492
-
493
- Track agent improvement velocity, maturity levels, and learning curves per skill.
494
-
495
- ### claw.getLearningVelocity({ agent_id })
496
- Get agent improvement rate over time.
497
-
498
- **Returns:** `Promise<Object>`
499
-
500
- ### claw.getMaturityLevels()
501
- Get the 6-level maturity model distribution for the agent.
502
-
503
- **Returns:** `Promise<Object>`
504
-
505
- ### claw.getLearningCurves({ agent_id, action_type })
506
- Get performance improvement curves for a specific skill/action type.
507
-
508
- **Returns:** `Promise<Object>`
509
-
510
- ---
511
-
512
- ## Scoring Profiles
513
-
514
- User-defined weighted quality scoring with 3 composite methods, 8 data sources, risk templates, and auto-calibration. Zero LLM required.
515
-
516
- ### claw.createScoringProfile({ name, action_type, composite_method, dimensions })
517
- Create a scoring profile with optional inline dimensions.
518
-
519
- **Parameters:**
520
- | Parameter | Type | Required | Description |
521
- |-----------|------|----------|-------------|
522
- | name | string | Yes | Profile name |
523
- | action_type | string | No | Filter to specific action type (null = all) |
524
- | composite_method | string | No | weighted_average (default), minimum, or geometric_mean |
525
- | dimensions | Array | No | Inline dimension definitions (name, data_source, weight, scale) |
526
-
527
- **Returns:** `Promise<Object>`
528
-
529
- **Example:**
530
- ```javascript
531
- const profile = await dc.createScoringProfile({
532
- name: 'deploy-quality',
533
- action_type: 'deploy',
534
- composite_method: 'weighted_average',
535
- dimensions: [
536
- { name: 'Speed', data_source: 'duration_ms', weight: 0.3,
537
- scale: [
538
- { label: 'excellent', operator: 'lt', value: 30000, score: 100 },
539
- { label: 'good', operator: 'lt', value: 60000, score: 75 },
540
- { label: 'poor', operator: 'gte', value: 60000, score: 20 },
541
- ]},
542
- { name: 'Reliability', data_source: 'confidence', weight: 0.7,
543
- scale: [
544
- { label: 'excellent', operator: 'gte', value: 0.9, score: 100 },
545
- { label: 'poor', operator: 'lt', value: 0.7, score: 25 },
546
- ]},
547
- ],
548
- });
549
- ```
550
-
551
- ### claw.scoreWithProfile(profile_id, action)
552
- Score a single action against a profile. Returns composite score + per-dimension breakdown.
553
-
554
- **Parameters:**
555
- | Parameter | Type | Required | Description |
556
- |-----------|------|----------|-------------|
557
- | profile_id | string | Yes | Profile to score against |
558
- | action | Object | Yes | Action data object |
559
-
560
- **Returns:** `Promise<Object>`
561
-
562
- ### claw.batchScoreWithProfile(profile_id, actions)
563
- Score multiple actions at once. Returns per-action results + summary.
564
-
565
- **Returns:** `Promise<Object>`
566
-
567
- ### claw.createRiskTemplate({ name, base_risk, rules })
568
- Create a rule-based risk template. Replaces hardcoded agent risk numbers.
569
-
570
- **Returns:** `Promise<Object>`
571
-
572
- ### claw.autoCalibrate({ action_type, lookback_days })
573
- Analyze historical action data to suggest scoring thresholds from percentile distribution.
574
-
575
- **Returns:** `Promise<Object>`
576
-
577
- ---
578
-
579
- ## Agent Presence & Health
580
-
581
- Monitor agent uptime and status in real-time. Use heartbeats to detect when an agent crashes or loses network connectivity.
582
-
583
- ### claw.heartbeat(options?)
584
- Report agent presence and health to the dashboard.
585
-
586
- **Parameters:**
587
- | Parameter | Type | Required | Description |
588
- |-----------|------|----------|-------------|
589
- | options.status | string | No | Agent status: 'online', 'busy', 'error' (default: 'online') |
590
- | options.currentTaskId | string | No | The ID of the task currently being executed |
591
- | options.metadata | Object | No | Optional key-value pairs for additional context |
592
-
593
- **Returns:** `Promise<{ status: string, timestamp: string }>`
594
-
595
- ### claw.startHeartbeat(options?)
596
- Start an automatic heartbeat timer that reports 'online' every minute.
597
-
598
- **Parameters:**
599
- | Parameter | Type | Required | Description |
600
- |-----------|------|----------|-------------|
601
- | options.interval | number | No | Heartbeat interval in milliseconds (default: 60000 / 1 min) |
602
- | options.status | string | No | Status to report |
603
-
604
- **Example:**
605
- ```javascript
606
- // Start reporting presence automatically
607
- claw.startHeartbeat();
608
-
609
- // Later, stop it
610
- claw.stopHeartbeat();
611
- ```
612
-
613
- ### claw.stopHeartbeat()
614
- Stop the automatic heartbeat timer.
615
-
616
- ---
617
-
618
- ## Real-Time Flight Recorder
619
-
620
- Stream actions live to the dashboard as they happen.
621
-
622
- ### claw.track(actionDef, fn)
623
- (Already documented above) - Use `track()` to automatically emit `running` events at start and `completed`/`failed` events at finish. These show up instantly on the "Flight Recorder" dashboard.
624
-
625
- ---
626
-
627
- ## Real-Time Events
628
-
629
- Subscribe to server-sent events (SSE) for instant push notifications. Eliminates polling for approvals, policy changes, and task assignments.
630
-
631
- ### claw.events()
632
-
633
- Open a persistent SSE connection. Returns a chainable handle with `.on(event, callback)` and `.close()`.
634
-
635
- **Supported events:** `action.created`, `action.updated`, `message.created`, `policy.updated`, `task.assigned`, `task.completed`
636
-
637
- ```javascript
638
- const stream = claw.events();
639
-
640
- stream
641
- .on('action.created', (data) => console.log('New action:', data.action_id))
642
- .on('action.updated', (data) => {
643
- if (data.status === 'running') console.log('Approved:', data.action_id);
644
- })
645
- .on('policy.updated', (data) => console.log('Policy changed:', data.change_type))
646
- .on('task.assigned', (data) => console.log('Task routed:', data.task?.title))
647
- .on('task.completed', (data) => console.log('Task done:', data.task?.task_id))
648
- .on('error', (err) => console.error('Stream error:', err));
649
-
650
- // When done:
651
- stream.close();
652
- ```
653
-
654
- ### claw.waitForApproval(actionId, { useEvents: true })
655
-
656
- SSE-powered approval waiting. Resolves instantly when the operator approves/denies instead of polling every 5 seconds.
657
-
658
- ```javascript
659
- // SSE mode (instant, recommended)
660
- const { action } = await claw.waitForApproval('act_abc', { useEvents: true });
661
-
662
- // Polling mode (default, backward-compatible)
663
- const { action } = await claw.waitForApproval('act_abc');
664
- ```
665
-
666
- | Parameter | Type | Default | Description |
667
- |-----------|------|---------|-------------|
668
- | actionId | string | Yes | Action ID to watch |
669
- | options.timeout | number | 300000 | Max wait time (ms) |
670
- | options.interval | number | 5000 | Poll interval (polling mode only) |
671
- | options.useEvents | boolean | false | Use SSE instead of polling |
672
-
673
- ---
674
-
675
- ## Token & Cost Analytics
676
-
677
- Track token usage and estimated costs for every action. DashClaw automatically aggregates these into "Cost per Goal" metrics.
678
-
679
- **Usage:**
680
- Pass `tokens_in`, `tokens_out`, and `model` when creating or updating actions.
681
-
682
- ```javascript
683
- await claw.createAction({
684
- action_type: 'generation',
685
- declared_goal: 'Generate blog post',
686
- model: 'gpt-4o',
687
- tokens_in: 1500,
688
- tokens_out: 400,
689
- // cost_estimate is auto-calculated on the server if model is known
690
- });
691
- ```
692
-
693
- **Supported Models for Auto-Pricing:**
694
- - GPT-4o, GPT-4-Turbo
695
- - Claude 3.5 Sonnet, Claude 3 Opus, Claude 3 Haiku
696
- - Llama 3 (70b, 8b)
697
-
698
- ---
699
-
700
- ## Loops & Assumptions
701
-
702
- Track unresolved dependencies and log what your agents assume. Catch drift before it causes failures.
703
-
704
- ### claw.registerOpenLoop(loop)
705
- Register an open loop (unresolved dependency, pending approval, etc.) for an action.
706
-
707
- **Parameters:**
708
- | Parameter | Type | Required | Description |
709
- |-----------|------|----------|-------------|
710
- | action_id | string | Yes | Parent action ID |
711
- | loop_type | string | Yes | One of: followup, question, dependency, approval, review, handoff, other |
712
- | description | string | Yes | What needs to be resolved |
713
- | priority | string | No | One of: low, medium, high, critical (default: medium) |
714
- | owner | string | No | Who is responsible for resolving this |
715
-
716
- **Returns:** `Promise<{ loop: Object, loop_id: string }>`
717
-
718
- ### claw.resolveOpenLoop(loopId, status, resolution?)
719
- Resolve or cancel an open loop.
720
-
721
- **Parameters:**
722
- | Parameter | Type | Required | Description |
723
- |-----------|------|----------|-------------|
724
- | loopId | string | Yes | The loop_id to resolve |
725
- | status | string | Yes | "resolved" or "cancelled" |
726
- | resolution | string | No | Resolution description (required when resolving) |
727
-
728
- **Returns:** `Promise<{ loop: Object }>`
729
-
730
- ### claw.registerAssumption(assumption)
731
- Register an assumption made during an action. Track what your agent assumes so you can validate or invalidate later.
732
-
733
- **Parameters:**
734
- | Parameter | Type | Required | Description |
735
- |-----------|------|----------|-------------|
736
- | action_id | string | Yes | Parent action ID |
737
- | assumption | string | Yes | The assumption being made |
738
- | basis | string | No | Evidence or reasoning for the assumption |
739
- | validated | boolean | No | Whether this has been validated (default: false) |
740
-
741
- **Returns:** `Promise<{ assumption: Object, assumption_id: string }>`
742
-
743
- ### claw.getAssumption(assumptionId)
744
- Get a single assumption by ID.
745
-
746
- **Parameters:**
747
- | Parameter | Type | Required | Description |
748
- |-----------|------|----------|-------------|
749
- | assumptionId | string | Yes | The assumption_id to retrieve |
750
-
751
- **Returns:** `Promise<{ assumption: Object }>`
752
-
753
- ### claw.validateAssumption(assumptionId, validated, invalidated_reason?)
754
- Validate or invalidate an assumption. When invalidating, a reason is required.
755
-
756
- **Parameters:**
757
- | Parameter | Type | Required | Description |
758
- |-----------|------|----------|-------------|
759
- | assumptionId | string | Yes | The assumption_id to update |
760
- | validated | boolean | Yes | true to validate, false to invalidate |
761
- | invalidated_reason | string | No | Required when invalidating (validated = false) |
762
-
763
- **Returns:** `Promise<{ assumption: Object }>`
764
-
765
- ### claw.getOpenLoops(filters?)
766
- Get open loops with optional filters. Returns paginated results with stats.
767
-
768
- **Parameters:**
769
- | Parameter | Type | Required | Description |
770
- |-----------|------|----------|-------------|
771
- | status | string | No | Filter by status: open, resolved, cancelled |
772
- | loop_type | string | No | Filter by loop type |
773
- | priority | string | No | Filter by priority |
774
- | limit | number | No | Max results (default: 50) |
775
-
776
- **Returns:** `Promise<{ loops: Object[], total: number, stats: Object }>`
777
-
778
- ### claw.getDriftReport(filters?)
779
- Get drift report for assumptions with risk scoring. Shows which assumptions are stale, unvalidated, or contradicted by outcomes.
780
-
781
- **Parameters:**
782
- | Parameter | Type | Required | Description |
783
- |-----------|------|----------|-------------|
784
- | action_id | string | No | Filter by action |
785
- | limit | number | No | Max results (default: 50) |
786
-
787
- **Returns:** `Promise<{ assumptions: Object[], drift_summary: Object }>`
788
-
789
- ---
790
-
791
- ## Signals
792
-
793
- Automatic detection of problematic agent behavior. Seven signal types fire based on action patterns - no configuration required.
794
-
795
- ### claw.getSignals()
796
- 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.
797
-
798
- **Returns:** `Promise<{ signals: Object[], counts: { red: number, amber: number, total: number } }>`
799
-
800
- ### Signal Types
801
- - **autonomy_spike**: Agent taking too many actions without human checkpoints
802
- - **high_impact_low_oversight**: Critical actions without sufficient review
803
- - **repeated_failures**: Same action type failing multiple times
804
- - **stale_loop**: Open loops unresolved past their expected timeline
805
- - **assumption_drift**: Assumptions becoming stale or contradicted by outcomes
806
- - **stale_assumption**: Assumptions not validated within expected timeframe
807
- - **stale_running_action**: Actions stuck in running state for over 4 hours
808
-
809
- ---
810
-
811
- ## Behavior Guard
812
-
813
- Guard is the heart of DashClaw. Every action can be checked against policies before execution. Returns allow, warn, block, or require_approval based on configured guard policies.
814
-
815
- ### claw.guard(context, options?)
816
- 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.
817
-
818
- **Parameters:**
819
- | Parameter | Type | Required | Description |
820
- |-----------|------|----------|-------------|
821
- | context.action_type | string | Yes | The type of action being proposed |
822
- | context.risk_score | number | No | Risk score 0-100 |
823
- | context.systems_touched | string[] | No | Systems this action will affect |
824
- | context.reversible | boolean | No | Whether the action can be undone |
825
- | context.declared_goal | string | No | What the action accomplishes |
826
- | options.includeSignals | boolean | No | Also check live risk signals (adds latency) |
827
-
828
- **Returns:** `Promise<{ decision: string, reasons: string[], warnings: string[], matched_policies: string[], evaluated_at: string }>`
829
-
830
- ### claw.getGuardDecisions(filters?)
831
- Retrieve recent guard evaluation decisions for audit and review.
832
-
833
- **Parameters:**
834
- | Parameter | Type | Required | Description |
835
- |-----------|------|----------|-------------|
836
- | filters.decision | string | No | Filter by decision: allow, warn, block, require_approval |
837
- | filters.limit | number | No | Max results (default 20, max 100) |
838
- | filters.offset | number | No | Pagination offset |
839
-
840
- **Returns:** `Promise<{ decisions: Object[], total: number, stats: Object }>`
841
-
842
- ---
843
-
844
- ## Dashboard Data
845
-
846
- Push data from your agent directly to the DashClaw dashboard. All methods auto-attach the agent's agentId.
847
-
848
- ### claw.reportTokenUsage(usage)
849
- Report a token usage snapshot for this agent.
850
-
851
- **Parameters:**
852
- | Parameter | Type | Required | Description |
853
- |-----------|------|----------|-------------|
854
- | tokens_in | number | Yes | Input tokens consumed |
855
- | tokens_out | number | Yes | Output tokens generated |
856
- | context_used | number | No | Context window tokens used |
857
- | context_max | number | No | Context window max capacity |
858
- | model | string | No | Model name |
859
-
860
- **Returns:** `Promise<{snapshot: Object}>`
861
-
862
- ### claw.wrapClient(llmClient, options?)
863
- Wrap an Anthropic or OpenAI client to auto-report token usage after every call. Returns the same client instance for fluent usage. Streaming calls (where response lacks `.usage`) are safely ignored.
864
-
865
- **Parameters:**
866
- | Parameter | Type | Required | Description |
867
- |-----------|------|----------|-------------|
868
- | llmClient | Object | Yes | An Anthropic or OpenAI SDK client instance |
869
- | options.provider | string | No | Force `'anthropic'` or `'openai'` if auto-detect fails |
870
-
871
- **Returns:** The wrapped client (same instance)
872
-
873
- **Example (Anthropic):**
874
- ```javascript
875
- import Anthropic from '@anthropic-ai/sdk';
876
- import { DashClaw } from 'dashclaw';
877
-
878
- const claw = new DashClaw({ baseUrl: 'http://localhost:3000', agentId: 'my-agent', apiKey: '...' });
879
- const anthropic = claw.wrapClient(new Anthropic());
880
-
881
- const msg = await anthropic.messages.create({
882
- model: 'claude-sonnet-4-20250514',
883
- max_tokens: 1024,
884
- messages: [{ role: 'user', content: 'Hello' }],
885
- });
886
- // Token usage auto-reported to DashClaw
887
- ```
888
-
889
- **Example (OpenAI):**
890
- ```javascript
891
- import OpenAI from 'openai';
892
-
893
- const openai = claw.wrapClient(new OpenAI());
894
-
895
- const chat = await openai.chat.completions.create({
896
- model: 'gpt-4o',
897
- messages: [{ role: 'user', content: 'Hello' }],
898
- });
899
- // Token usage auto-reported to DashClaw
900
- ```
901
-
902
- ### claw.recordDecision(entry)
903
- Record a decision for the learning database. Track what your agent decides and why.
904
-
905
- **Parameters:**
906
- | Parameter | Type | Required | Description |
907
- |-----------|------|----------|-------------|
908
- | decision | string | Yes | What was decided |
909
- | context | string | No | Context around the decision |
910
- | reasoning | string | No | Why this decision was made |
911
- | outcome | string | No | "success", "failure", or "pending" |
912
- | confidence | number | No | Confidence level 0-100 |
913
-
914
- **Returns:** `Promise<{ decision: Object }>`
915
-
916
- ### claw.getRecommendations(filters?)
917
- Get adaptive recommendations synthesized from scored historical episodes.
918
-
919
- **Parameters:**
920
- | Parameter | Type | Required | Description |
921
- |-----------|------|----------|-------------|
922
- | filters.action_type | string | No | Filter by action type |
923
- | filters.agent_id | string | No | Override agent scope (defaults to SDK agent) |
924
- | filters.include_inactive | boolean | No | Include disabled recommendations (admin/service only) |
925
- | filters.track_events | boolean | No | Record fetched telemetry (default true) |
926
- | filters.include_metrics | boolean | No | Include computed metrics in response |
927
- | filters.lookback_days | number | No | Lookback window for include_metrics |
928
- | filters.limit | number | No | Max results (default 50) |
929
-
930
- **Returns:** `Promise<{ recommendations: Object[], metrics?: Object, total: number }>`
931
-
932
- ### claw.getRecommendationMetrics(filters?)
933
- Get recommendation telemetry and effectiveness deltas.
934
-
935
- **Parameters:**
936
- | Parameter | Type | Required | Description |
937
- |-----------|------|----------|-------------|
938
- | filters.action_type | string | No | Filter by action type |
939
- | filters.agent_id | string | No | Override agent scope (defaults to SDK agent) |
940
- | filters.lookback_days | number | No | Lookback window (default 30) |
941
- | filters.limit | number | No | Max recommendations to evaluate (default 100) |
942
- | filters.include_inactive | boolean | No | Include disabled recommendations (admin/service only) |
943
-
944
- **Returns:** `Promise<{ metrics: Object[], summary: Object, lookback_days: number }>`
945
-
946
- ### claw.recordRecommendationEvents(events)
947
- Write recommendation telemetry events (single event or batch).
948
-
949
- **Returns:** `Promise<{ created: Object[], created_count: number }>`
950
-
951
- ### claw.setRecommendationActive(recommendationId, active)
952
- Enable or disable one recommendation.
953
-
954
- **Returns:** `Promise<{ recommendation: Object }>`
955
-
956
- ### claw.rebuildRecommendations(options?)
957
- Recompute recommendations from recent learning episodes.
958
-
959
- **Parameters:**
960
- | Parameter | Type | Required | Description |
961
- |-----------|------|----------|-------------|
962
- | options.action_type | string | No | Restrict rebuild to one action type |
963
- | options.lookback_days | number | No | Episode history window (default 30) |
964
- | options.min_samples | number | No | Minimum samples per recommendation (default 5) |
965
- | options.episode_limit | number | No | Episode scan cap (default 5000) |
966
- | options.action_id | string | No | Score this action before rebuilding |
967
-
968
- **Returns:** `Promise<{ recommendations: Object[], total: number, episodes_scanned: number }>`
969
-
970
- ### claw.recommendAction(action)
971
- Apply top recommendation hints to an action payload without mutating the original object.
972
-
973
- **Returns:** `Promise<{ action: Object, recommendation: Object|null, adapted_fields: string[] }>`
974
-
975
- ### claw.createGoal(goal)
976
- Create a goal in the goals tracker.
977
-
978
- **Parameters:**
979
- | Parameter | Type | Required | Description |
980
- |-----------|------|----------|-------------|
981
- | title | string | Yes | Goal title |
982
- | category | string | No | Goal category |
983
- | description | string | No | Detailed description |
984
- | target_date | string | No | Target completion date (ISO string) |
985
- | progress | number | No | Progress 0-100 |
986
- | status | string | No | "active", "completed", or "paused" |
987
-
988
- **Returns:** `Promise<{ goal: Object }>`
989
-
990
- ### claw.recordContent(content)
991
- Record content creation (articles, posts, documents).
992
-
993
- **Parameters:**
994
- | Parameter | Type | Required | Description |
995
- |-----------|------|----------|-------------|
996
- | title | string | Yes | Content title |
997
- | platform | string | No | Platform (e.g., "linkedin", "twitter") |
998
- | status | string | No | "draft" or "published" |
999
- | url | string | No | Published URL |
1000
-
1001
- **Returns:** `Promise<{ content: Object }>`
1002
-
1003
- ### claw.recordInteraction(interaction)
1004
- Record a relationship interaction (message, meeting, email).
1005
-
1006
- **Parameters:**
1007
- | Parameter | Type | Required | Description |
1008
- |-----------|------|----------|-------------|
1009
- | summary | string | Yes | What happened |
1010
- | contact_name | string | No | Contact name (auto-resolves to contact_id) |
1011
- | contact_id | string | No | Direct contact ID |
1012
- | direction | string | No | "inbound" or "outbound" |
1013
- | type | string | No | Interaction type (e.g., "message", "meeting", "email") |
1014
- | platform | string | No | Platform used |
1015
-
1016
- **Returns:** `Promise<{ interaction: Object }>`
1017
-
1018
- ### claw.reportConnections(connections)
1019
- Report active connections/integrations for this agent.
1020
-
1021
- **Parameters:**
1022
- | Parameter | Type | Required | Description |
1023
- |-----------|------|----------|-------------|
1024
- | connections | Object[] | Yes | Array of connection objects |
1025
- | connections[].provider | string | Yes | Service name (e.g., "anthropic", "github") |
1026
- | connections[].authType | string | No | Auth method |
1027
- | connections[].planName | string | No | Plan name |
1028
- | connections[].status | string | No | Connection status |
1029
- | connections[].metadata | Object|string | No | Optional metadata |
1030
-
1031
- **Returns:** `Promise<{ connections: Object[], created: number }>`
1032
-
1033
- ### claw.createCalendarEvent(event)
1034
- Create a calendar event.
1035
-
1036
- **Parameters:**
1037
- | Parameter | Type | Required | Description |
1038
- |-----------|------|----------|-------------|
1039
- | summary | string | Yes | Event title/summary |
1040
- | start_time | string | Yes | Start time (ISO string) |
1041
- | end_time | string | No | End time (ISO string) |
1042
- | location | string | No | Event location |
1043
- | description | string | No | Event description |
1044
-
1045
- **Returns:** `Promise<{event: Object}>`
1046
-
1047
- ### claw.recordIdea(idea)
1048
- Record an idea or inspiration for later review.
1049
-
1050
- **Parameters:**
1051
- | Parameter | Type | Required | Description |
1052
- |-----------|------|----------|-------------|
1053
- | title | string | Yes | Idea title |
1054
- | description | string | No | Detailed description |
1055
- | category | string | No | Category |
1056
- | score | number | No | Priority/quality score 0-100 |
1057
- | status | string | No | "pending", "in_progress", "shipped", "rejected" |
1058
- | source | string | No | Where this idea came from |
1059
-
1060
- **Returns:** `Promise<{idea: Object}>`
1061
-
1062
- ### claw.reportMemoryHealth(report)
1063
- Report a memory health snapshot with entities and topics.
1064
-
1065
- **Parameters:**
1066
- | Parameter | Type | Required | Description |
1067
- |-----------|------|----------|-------------|
1068
- | health | Object | Yes | Health metrics (must include `score` 0-100) |
1069
- | entities | Object[] | No | Key entities found in memory |
1070
- | topics | Object[] | No | Topics/themes found in memory |
1071
-
1072
- **Returns:** `Promise<{snapshot: Object, entities_count: number, topics_count: number}>`
1073
-
1074
- ---
1075
-
1076
- ## Session Handoffs
1077
-
1078
- ### claw.createHandoff(handoff)
1079
- Create a session handoff document summarizing work done, decisions made, and next priorities.
1080
-
1081
- **Parameters:**
1082
- | Parameter | Type | Required | Description |
1083
- |-----------|------|----------|-------------|
1084
- | summary | string | Yes | Session summary |
1085
- | session_date | string | No | Date string (defaults to today) |
1086
- | key_decisions | string[] | No | Key decisions made this session |
1087
- | open_tasks | string[] | No | Tasks still open |
1088
- | mood_notes | string | No | User mood/energy observations |
1089
- | next_priorities | string[] | No | What to focus on next |
1090
-
1091
- **Returns:** `Promise<{handoff: Object, handoff_id: string}>`
1092
-
1093
- ### claw.getHandoffs(filters?)
1094
- Get handoffs for this agent with optional date and limit filters.
1095
-
1096
- **Parameters:**
1097
- | Parameter | Type | Required | Description |
1098
- |-----------|------|----------|-------------|
1099
- | date | string | No | Filter by session_date |
1100
- | limit | number | No | Max results |
1101
-
1102
- **Returns:** `Promise<{handoffs: Object[], total: number}>`
1103
-
1104
- ### claw.getLatestHandoff()
1105
- Get the most recent handoff for this agent. Useful for resuming context at the start of a new session.
1106
-
1107
- **Returns:** `Promise<{handoff: Object|null}>`
1108
-
1109
- **Example:**
1110
- ```javascript
1111
- const { handoff } = await claw.getLatestHandoff();
1112
- if (handoff) {
1113
- console.log('Last session:', handoff.summary);
1114
- console.log('Next priorities:', handoff.next_priorities);
1115
- }
1116
- ```
1117
-
1118
- ---
1119
-
1120
- ## Context Manager
1121
-
1122
- Capture key points and organize context into threads for long-running topics.
1123
-
1124
- ### claw.captureKeyPoint(point)
1125
- Capture a key point from the current session for later recall.
1126
-
1127
- **Parameters:**
1128
- | Parameter | Type | Required | Description |
1129
- |-----------|------|----------|-------------|
1130
- | content | string | Yes | The key point content |
1131
- | category | string | No | decision, task, insight, question, general |
1132
- | importance | number | No | Importance 1-10 (default 5) |
1133
- | session_date | string | No | Date string (defaults to today) |
1134
-
1135
- **Returns:** `Promise<{point: Object, point_id: string}>`
1136
-
1137
- ### claw.createThread(thread)
1138
- Create a context thread for tracking a topic across multiple entries.
1139
-
1140
- **Parameters:**
1141
- | Parameter | Type | Required | Description |
1142
- |-----------|------|----------|-------------|
1143
- | name | string | Yes | Thread name (unique per agent per org) |
1144
- | summary | string | No | Initial summary |
1145
-
1146
- **Returns:** `Promise<{thread: Object, thread_id: string}>`
1147
-
1148
- ### claw.getKeyPoints(filters?)
1149
- Get key points with optional filters.
1150
-
1151
- **Parameters:**
1152
- | Parameter | Type | Required | Description |
1153
- |-----------|------|----------|-------------|
1154
- | category | string | No | Filter by category: decision, task, insight, question, general |
1155
- | session_date | string | No | Filter by date (YYYY-MM-DD) |
1156
- | limit | number | No | Max results |
1157
-
1158
- **Returns:** `Promise<{points: Object[], total: number}>`
1159
-
1160
- ### claw.addThreadEntry(threadId, content, entryType?)
1161
- Add an entry to an existing thread.
1162
-
1163
- **Parameters:**
1164
- | Parameter | Type | Required | Description |
1165
- |-----------|------|----------|-------------|
1166
- | threadId | string | Yes | The thread ID |
1167
- | content | string | Yes | Entry content |
1168
- | entryType | string | No | Entry type (default: "note") |
1169
-
1170
- **Returns:** `Promise<{entry: Object, entry_id: string}>`
1171
-
1172
- ### claw.closeThread(threadId, summary?)
1173
- Close a context thread with an optional final summary.
1174
-
1175
- **Parameters:**
1176
- | Parameter | Type | Required | Description |
1177
- |-----------|------|----------|-------------|
1178
- | threadId | string | Yes | The thread ID to close |
1179
- | summary | string | No | Final summary for the thread |
1180
-
1181
- **Returns:** `Promise<{thread: Object}>`
1182
-
1183
- ### claw.getThreads(filters?)
1184
- Get context threads with optional filters.
1185
-
1186
- **Parameters:**
1187
- | Parameter | Type | Required | Description |
1188
- |-----------|------|----------|-------------|
1189
- | status | string | No | Filter by status: active, closed |
1190
- | limit | number | No | Max results |
1191
-
1192
- **Returns:** `Promise<{threads: Object[], total: number}>`
1193
-
1194
- ### claw.getContextSummary()
1195
- Get a combined context summary containing today's key points and all active threads. Convenience method that calls `getKeyPoints()` and `getThreads()` in parallel.
1196
-
1197
- **Returns:** `Promise<{points: Object[], threads: Object[]}>`
1198
-
1199
- **Example:**
1200
- ```javascript
1201
- const { points, threads } = await claw.getContextSummary();
1202
- console.log(`${points.length} key points today, ${threads.length} active threads`);
1203
- ```
1204
-
1205
- ---
1206
-
1207
- ## Automation Snippets
1208
-
1209
- Save, search, and reuse code snippets across agent sessions.
1210
-
1211
- ### claw.saveSnippet(snippet)
1212
- Save or update a reusable code snippet. Upserts on name.
1213
-
1214
- **Parameters:**
1215
- | Parameter | Type | Required | Description |
1216
- |-----------|------|----------|-------------|
1217
- | name | string | Yes | Snippet name (unique per org) |
1218
- | code | string | Yes | The snippet code |
1219
- | description | string | No | What this snippet does |
1220
- | language | string | No | Programming language |
1221
- | tags | string[] | No | Tags for categorization |
1222
-
1223
- **Returns:** `Promise<{snippet: Object, snippet_id: string}>`
1224
-
1225
- **Example:**
1226
- ```javascript
1227
- await claw.saveSnippet({
1228
- name: 'fetch-with-retry',
1229
- code: 'async function fetchRetry(url, n = 3) { ... }',
1230
- language: 'javascript',
1231
- tags: ['fetch', 'retry'],
1232
- });
1233
- ```
1234
-
1235
- ### claw.getSnippet(snippetId)
1236
- Fetch a single snippet by ID.
1237
-
1238
- **Parameters:**
1239
- | Parameter | Type | Required | Description |
1240
- |-----------|------|----------|-------------|
1241
- | snippetId | string | Yes | The snippet ID |
1242
-
1243
- **Returns:** `Promise<{snippet: Object}>`
1244
-
1245
- **Example:**
1246
- ```javascript
1247
- const { snippet } = await claw.getSnippet('sn_abc123');
1248
- console.log(snippet.name, snippet.language);
1249
- ```
1250
-
1251
- ### claw.getSnippets(filters?)
1252
- Search and list snippets.
1253
-
1254
- **Parameters:**
1255
- | Parameter | Type | Required | Description |
1256
- |-----------|------|----------|-------------|
1257
- | search | string | No | Search name/description |
1258
- | tag | string | No | Filter by tag |
1259
- | language | string | No | Filter by language |
1260
- | limit | number | No | Max results |
1261
-
1262
- **Returns:** `Promise<{snippets: Object[], total: number}>`
1263
-
1264
- **Example:**
1265
- ```javascript
1266
- const { snippets } = await claw.getSnippets({ language: 'javascript' });
1267
- ```
1268
-
1269
- ### claw.useSnippet(snippetId)
1270
- Mark a snippet as used (increments use_count).
1271
-
1272
- **Parameters:**
1273
- | Parameter | Type | Required | Description |
1274
- |-----------|------|----------|-------------|
1275
- | snippetId | string | Yes | Snippet ID |
1276
-
1277
- **Returns:** `Promise<{snippet: Object}>`
1278
-
1279
- **Example:**
1280
- ```javascript
1281
- await claw.useSnippet('sn_abc123');
1282
- ```
1283
-
1284
- ### claw.deleteSnippet(snippetId)
1285
- Delete a snippet.
1286
-
1287
- **Parameters:**
1288
- | Parameter | Type | Required | Description |
1289
- |-----------|------|----------|-------------|
1290
- | snippetId | string | Yes | Snippet ID |
1291
-
1292
- **Returns:** `Promise<{deleted: boolean, id: string}>`
1293
-
1294
- **Example:**
1295
- ```javascript
1296
- await claw.deleteSnippet('sn_abc123');
1297
- ```
1298
-
1299
- ---
1300
-
1301
- ## User Preferences
1302
-
1303
- Track user observations, learned preferences, mood/energy, and approach effectiveness across sessions.
1304
-
1305
- ### claw.logObservation(obs)
1306
- Log a user observation (what you noticed about the user's behavior or preferences).
1307
-
1308
- **Parameters:**
1309
- | Parameter | Type | Required | Description |
1310
- |-----------|------|----------|-------------|
1311
- | observation | string | Yes | The observation text |
1312
- | category | string | No | Category tag |
1313
- | importance | number | No | Importance 1-10 |
1314
-
1315
- **Returns:** `Promise<{observation: Object, observation_id: string}>`
1316
-
1317
- **Example:**
1318
- ```javascript
1319
- await claw.logObservation({
1320
- observation: 'User prefers concise responses over detailed explanations',
1321
- category: 'communication',
1322
- importance: 8,
1323
- });
1324
- ```
1325
-
1326
- ### claw.setPreference(pref)
1327
- Set a learned user preference. Use this to record patterns you detect about how the user likes to work.
1328
-
1329
- **Parameters:**
1330
- | Parameter | Type | Required | Description |
1331
- |-----------|------|----------|-------------|
1332
- | preference | string | Yes | The preference description |
1333
- | category | string | No | Category tag |
1334
- | confidence | number | No | Confidence 0-100 |
1335
-
1336
- **Returns:** `Promise<{preference: Object, preference_id: string}>`
1337
-
1338
- ### claw.logMood(entry)
1339
- Log user mood/energy for a session. Helps track patterns in productivity and satisfaction.
1340
-
1341
- **Parameters:**
1342
- | Parameter | Type | Required | Description |
1343
- |-----------|------|----------|-------------|
1344
- | mood | string | Yes | Mood description (e.g., "focused", "frustrated") |
1345
- | energy | string | No | Energy level (e.g., "high", "low") |
1346
- | notes | string | No | Additional notes |
1347
-
1348
- **Returns:** `Promise<{mood: Object, mood_id: string}>`
1349
-
1350
- ### claw.trackApproach(entry)
1351
- Track an approach and whether it succeeded or failed. Builds a knowledge base of what works.
1352
-
1353
- **Parameters:**
1354
- | Parameter | Type | Required | Description |
1355
- |-----------|------|----------|-------------|
1356
- | approach | string | Yes | The approach description |
1357
- | context | string | No | Context for when to use this approach |
1358
- | success | boolean | No | true = worked, false = failed, undefined = just recording |
1359
-
1360
- **Returns:** `Promise<{approach: Object, approach_id: string}>`
1361
-
1362
- ### claw.getPreferenceSummary()
1363
- Get a summary of all user preference data including observations, preferences, moods, and approaches.
1364
-
1365
- **Returns:** `Promise<{summary: Object}>`
1366
-
1367
- ### claw.getApproaches(filters?)
1368
- Get tracked approaches with success/fail counts.
1369
-
1370
- **Parameters:**
1371
- | Parameter | Type | Required | Description |
1372
- |-----------|------|----------|-------------|
1373
- | limit | number | No | Max results |
1374
-
1375
- **Returns:** `Promise<{approaches: Object[], total: number}>`
1376
-
1377
- ---
1378
-
1379
- ## Daily Digest
1380
-
1381
- ### claw.getDailyDigest(date?)
1382
- Get a daily activity digest aggregated from all data sources (actions, decisions, handoffs, context, etc.).
1383
-
1384
- **Parameters:**
1385
- | Parameter | Type | Required | Description |
1386
- |-----------|------|----------|-------------|
1387
- | date | string | No | Date string YYYY-MM-DD (defaults to today) |
1388
-
1389
- **Returns:** `Promise<{date: string, digest: Object, summary: Object}>`
1390
-
1391
- **Example:**
1392
- ```javascript
1393
- const { digest, summary } = await claw.getDailyDigest('2025-01-15');
1394
- console.log(`Actions: ${summary.actions_count}, Decisions: ${summary.decisions_count}`);
1395
- ```
1396
-
1397
- ---
1398
-
1399
- ## Security Scanning
1400
-
1401
- Scan text for sensitive data before sending it anywhere. The scanner detects API keys, tokens, PII, and other secrets.
1402
-
1403
- ### claw.scanContent(text, destination?)
1404
- Scan text for sensitive data. Returns findings and redacted text. Does NOT store the original content.
1405
-
1406
- **Parameters:**
1407
- | Parameter | Type | Required | Description |
1408
- |-----------|------|----------|-------------|
1409
- | text | string | Yes | Text to scan |
1410
- | destination | string | No | Where this text is headed (for context) |
1411
-
1412
- **Returns:** `Promise<{clean: boolean, findings_count: number, findings: Object[], redacted_text: string}>`
1413
-
1414
- **Example:**
1415
- ```javascript
1416
- const result = await claw.scanContent(
1417
- 'Deploy with key sk-abc123xyz to production',
1418
- 'slack'
1419
- );
1420
- if (!result.clean) {
1421
- console.log(`Found ${result.findings_count} issues`);
1422
- console.log('Safe version:', result.redacted_text);
1423
- }
1424
- ```
1425
-
1426
- ### claw.reportSecurityFinding(text, destination?)
1427
- Scan text and store finding metadata for audit trails. The original content is never stored, only the finding metadata.
1428
-
1429
- **Parameters:**
1430
- | Parameter | Type | Required | Description |
1431
- |-----------|------|----------|-------------|
1432
- | text | string | Yes | Text to scan |
1433
- | destination | string | No | Where this text is headed |
1434
-
1435
- **Returns:** `Promise<{clean: boolean, findings_count: number, findings: Object[], redacted_text: string}>`
1436
-
1437
- ### claw.scanPromptInjection(text, options?)
1438
- Scan text for prompt injection attacks — role overrides, delimiter injection, instruction smuggling, data exfiltration attempts, and encoding evasion. Returns risk level and actionable recommendation.
1439
-
1440
- **Parameters:**
1441
- | Parameter | Type | Required | Description |
1442
- |-----------|------|----------|-------------|
1443
- | text | string | Yes | Text to scan for injection attacks |
1444
- | options.source | string | No | Where this text came from (e.g. user_input, tool_output, retrieval) |
1445
-
1446
- **Returns:** `Promise<{clean: boolean, risk_level: string, recommendation: string, findings_count: number, critical_count: number, categories: string[], findings: Object[]}>`
1447
-
1448
- **Example:**
1449
- ```javascript
1450
- const result = await claw.scanPromptInjection(userMessage, { source: 'user_input' });
1451
- if (result.recommendation === 'block') {
1452
- console.error(`Blocked: ${result.findings_count} injection patterns detected`);
1453
- } else if (result.recommendation === 'warn') {
1454
- console.warn(`Warning: ${result.categories.join(', ')} detected`);
1455
- }
1456
- ```
1457
-
1458
- ---
1459
-
1460
- ## Agent Messaging
1461
-
1462
- ### claw.sendMessage(params)
1463
- Send a message to another agent or broadcast.
1464
-
1465
- **Parameters:**
1466
- | Parameter | Type | Required | Description |
1467
- |-----------|------|----------|-------------|
1468
- | to | string | No | Target agent ID (null = broadcast) |
1469
- | type | string | No | info, action, lesson, question, status |
1470
- | subject | string | No | Subject line (max 200 chars) |
1471
- | body | string | Yes | Message body (max 2000 chars) |
1472
- | threadId | string | No | Thread ID to attach to |
1473
- | urgent | boolean | No | Mark as urgent |
1474
- | docRef | string | No | Reference to a shared doc ID |
1475
- | attachments | Array<{filename, mime_type, data}> | No | File attachments (base64, max 3, max 5MB each) |
1476
-
1477
- **Returns:** `Promise<{message: Object, message_id: string}>`
1478
-
1479
- ### claw.getInbox(params?)
1480
- Get inbox messages for this agent.
1481
-
1482
- **Parameters:**
1483
- | Parameter | Type | Required | Description |
1484
- |-----------|------|----------|-------------|
1485
- | type | string | No | Filter by message type |
1486
- | unread | boolean | No | Only unread messages |
1487
- | threadId | string | No | Filter by thread |
1488
- | limit | number | No | Max messages to return (default: 50) |
1489
-
1490
- **Returns:** `Promise<{messages: Object[], total: number, unread_count: number}>`
1491
-
1492
- ### claw.markRead(messageIds)
1493
- Mark messages as read.
1494
-
1495
- **Parameters:**
1496
- | Parameter | Type | Required | Description |
1497
- |-----------|------|----------|-------------|
1498
- | messageIds | string[] | Yes | Array of message IDs to mark read |
1499
-
1500
- **Returns:** `Promise<{updated: number}>`
1501
-
1502
- ### claw.archiveMessages(messageIds)
1503
- Archive messages.
1504
-
1505
- **Parameters:**
1506
- | Parameter | Type | Required | Description |
1507
- |-----------|------|----------|-------------|
1508
- | messageIds | string[] | Yes | Array of message IDs to archive |
1509
-
1510
- **Returns:** `Promise<{updated: number}>`
1511
-
1512
- ### claw.broadcast(params)
1513
- Broadcast a message to all agents in the organization.
1514
-
1515
- **Parameters:**
1516
- | Parameter | Type | Required | Description |
1517
- |-----------|------|----------|-------------|
1518
- | type | string | No | Message type (default: "info") |
1519
- | subject | string | No | Subject line |
1520
- | body | string | Yes | Message body |
1521
- | threadId | string | No | Thread ID |
1522
-
1523
- **Returns:** `Promise<{message: Object, message_id: string}>`
1524
-
1525
- ### claw.createMessageThread(params)
1526
- Create a new message thread for multi-turn conversations between agents.
1527
-
1528
- **Parameters:**
1529
- | Parameter | Type | Required | Description |
1530
- |-----------|------|----------|-------------|
1531
- | name | string | Yes | Thread name |
1532
- | participants | string[] | No | Agent IDs (null = open to all) |
1533
-
1534
- **Returns:** `Promise<{thread: Object, thread_id: string}>`
1535
-
1536
- ### claw.getMessageThreads(params?)
1537
- List message threads.
1538
-
1539
- **Parameters:**
1540
- | Parameter | Type | Required | Description |
1541
- |-----------|------|----------|-------------|
1542
- | status | string | No | Filter by status: open, resolved, archived |
1543
- | limit | number | No | Max threads to return (default: 20) |
1544
-
1545
- **Returns:** `Promise<{threads: Object[], total: number}>`
1546
-
1547
- ### claw.resolveMessageThread(threadId, summary?)
1548
- Resolve (close) a message thread with an optional summary.
1549
-
1550
- **Parameters:**
1551
- | Parameter | Type | Required | Description |
1552
- |-----------|------|----------|-------------|
1553
- | threadId | string | Yes | Thread ID to resolve |
1554
- | summary | string | No | Resolution summary |
1555
-
1556
- **Returns:** `Promise<{thread: Object}>`
1557
-
1558
- ### claw.saveSharedDoc(params)
1559
- Create or update a shared workspace document. Upserts by name.
1560
-
1561
- **Parameters:**
1562
- | Parameter | Type | Required | Description |
1563
- |-----------|------|----------|-------------|
1564
- | name | string | Yes | Document name (unique per org) |
1565
- | content | string | Yes | Document content |
1566
-
1567
- **Returns:** `Promise<{doc: Object, doc_id: string}>`
1568
-
1569
- ### claw.getAttachmentUrl(attachmentId)
1570
-
1571
- Get a URL to download an attachment.
1572
-
1573
- | Parameter | Type | Description |
1574
- |---|---|---|
1575
- | `attachmentId` | `string` | Attachment ID (`att_*`) |
1576
-
1577
- **Returns:** `string`: URL to fetch the attachment binary
1578
-
1579
- ---
1580
-
1581
- ### claw.getAttachment(attachmentId)
1582
-
1583
- Download an attachment as a Buffer.
1584
-
1585
- | Parameter | Type | Description |
1586
- |---|---|---|
1587
- | `attachmentId` | `string` | Attachment ID (`att_*`) |
1588
-
1589
- **Returns:** `Promise<{ data: Buffer, filename: string, mimeType: string }>`
1590
-
1591
- ```js
1592
- const inbox = await claw.getInbox();
1593
- for (const msg of inbox.messages) {
1594
- for (const att of msg.attachments || []) {
1595
- const { data, filename } = await claw.getAttachment(att.id);
1596
- fs.writeFileSync(filename, data);
1597
- }
1598
- }
1599
- ```
1600
-
1601
- ---
1602
-
1603
- ## Agent Pairing
1604
-
1605
- Pair agents with user accounts via public key registration and approval flow.
1606
-
1607
- ### claw.createPairing(options)
1608
- Create an agent pairing request. Returns a link the user can click to approve the pairing.
1609
-
1610
- **Parameters:**
1611
- | Parameter | Type | Required | Description |
1612
- |-----------|------|----------|-------------|
1613
- | publicKeyPem | string | Yes | PEM public key (SPKI format) to register for this agent |
1614
- | algorithm | string | No | Signing algorithm (default: "RSASSA-PKCS1-v1_5") |
1615
- | agentName | string | No | Agent name override |
1616
-
1617
- **Returns:** `Promise<{pairing: Object, pairing_url: string}>`
1618
-
1619
- ### claw.createPairingFromPrivateJwk(privateJwk, options?)
1620
- Convenience method that derives the public PEM from a private JWK and creates a pairing request.
1621
-
1622
- **Parameters:**
1623
- | Parameter | Type | Required | Description |
1624
- |-----------|------|----------|-------------|
1625
- | privateJwk | Object | Yes | Private key in JWK format |
1626
- | options.agentName | string | No | Agent name override |
1627
-
1628
- **Returns:** `Promise<{pairing: Object, pairing_url: string}>`
1629
-
1630
- ### claw.waitForPairing(pairingId, options?)
1631
- Poll a pairing request until it is approved or expired.
1632
-
1633
- **Parameters:**
1634
- | Parameter | Type | Required | Description |
1635
- |-----------|------|----------|-------------|
1636
- | pairingId | string | Yes | The pairing ID to poll |
1637
- | options.timeout | number | No | Max wait time in ms (default: 300000 / 5 min) |
1638
- | options.interval | number | No | Poll interval in ms (default: 2000) |
1639
-
1640
- **Returns:** `Promise<Object>` (the approved pairing object)
1641
-
1642
- **Throws:** `Error` if pairing expires or times out.
1643
-
1644
- **Example:**
1645
- ```javascript
1646
- const { pairing, pairing_url } = await claw.createPairing({
1647
- publicKeyPem: myPublicKeyPem,
1648
- });
1649
- console.log('Approve pairing at:', pairing_url);
1650
-
1651
- const approved = await claw.waitForPairing(pairing.id);
1652
- console.log('Pairing approved!', approved.status);
1653
- ```
1654
-
1655
- ---
1656
-
1657
- ## Identity Binding
1658
-
1659
- Register and manage agent public keys for cryptographic identity verification.
1660
-
1661
- ### claw.registerIdentity(identity)
1662
- Register or update an agent's public key for identity verification. Requires admin API key.
1663
-
1664
- **Parameters:**
1665
- | Parameter | Type | Required | Description |
1666
- |-----------|------|----------|-------------|
1667
- | agent_id | string | Yes | Agent ID to register |
1668
- | public_key | string | Yes | PEM public key (SPKI format) |
1669
- | algorithm | string | No | Signing algorithm (default: "RSASSA-PKCS1-v1_5") |
1670
-
1671
- **Returns:** `Promise<{identity: Object}>`
1672
-
1673
- ### claw.getIdentities()
1674
- List all registered agent identities for this organization.
1675
-
1676
- **Returns:** `Promise<{identities: Object[]}>`
1677
-
1678
- ---
1679
-
1680
- ## Organization Management
1681
-
1682
- Manage organizations and API keys. All methods require admin API key.
1683
-
1684
- ### claw.getOrg()
1685
- Get the current organization's details.
1686
-
1687
- **Returns:** `Promise<{organizations: Object[]}>`
1688
-
1689
- ### claw.createOrg(org)
1690
- Create a new organization with an initial admin API key.
1691
-
1692
- **Parameters:**
1693
- | Parameter | Type | Required | Description |
1694
- |-----------|------|----------|-------------|
1695
- | name | string | Yes | Organization name |
1696
- | slug | string | Yes | URL-safe slug (lowercase alphanumeric + hyphens) |
1697
-
1698
- **Returns:** `Promise<{organization: Object, api_key: Object}>`
1699
-
1700
- ### claw.getOrgById(orgId)
1701
- Get organization details by ID.
1702
-
1703
- **Parameters:**
1704
- | Parameter | Type | Required | Description |
1705
- |-----------|------|----------|-------------|
1706
- | orgId | string | Yes | Organization ID |
1707
-
1708
- **Returns:** `Promise<{organization: Object}>`
1709
-
1710
- ### claw.updateOrg(orgId, updates)
1711
- Update organization details.
1712
-
1713
- **Parameters:**
1714
- | Parameter | Type | Required | Description |
1715
- |-----------|------|----------|-------------|
1716
- | orgId | string | Yes | Organization ID |
1717
- | updates | Object | Yes | Fields to update (name, slug) |
1718
-
1719
- **Returns:** `Promise<{organization: Object}>`
1720
-
1721
- ### claw.getOrgKeys(orgId)
1722
- List API keys for an organization.
1723
-
1724
- **Parameters:**
1725
- | Parameter | Type | Required | Description |
1726
- |-----------|------|----------|-------------|
1727
- | orgId | string | Yes | Organization ID |
1728
-
1729
- **Returns:** `Promise<{keys: Object[]}>`
1730
-
1731
- ---
1732
-
1733
- ## Activity Logs
1734
-
1735
- ### claw.getActivityLogs(filters?)
1736
- Get activity/audit logs for the organization.
1737
-
1738
- **Parameters:**
1739
- | Parameter | Type | Required | Description |
1740
- |-----------|------|----------|-------------|
1741
- | action | string | No | Filter by action type |
1742
- | actor_id | string | No | Filter by actor |
1743
- | resource_type | string | No | Filter by resource type |
1744
- | before | string | No | Before timestamp (ISO string) |
1745
- | after | string | No | After timestamp (ISO string) |
1746
- | limit | number | No | Max results (default: 50, max: 200) |
1747
- | offset | number | No | Pagination offset |
1748
-
1749
- **Returns:** `Promise<{logs: Object[], stats: Object, pagination: Object}>`
1750
-
1751
- ---
1752
-
1753
- ## Webhooks
1754
-
1755
- Subscribe to DashClaw events and receive real-time notifications.
1756
-
1757
- ### claw.getWebhooks()
1758
- List all webhooks for this organization.
1759
-
1760
- **Returns:** `Promise<{webhooks: Object[]}>`
1761
-
1762
- ### claw.createWebhook(webhook)
1763
- Create a new webhook subscription.
1764
-
1765
- **Parameters:**
1766
- | Parameter | Type | Required | Description |
1767
- |-----------|------|----------|-------------|
1768
- | url | string | Yes | Webhook endpoint URL |
1769
- | events | string[] | No | Event types to subscribe to |
1770
-
1771
- **Returns:** `Promise<{webhook: Object}>`
1772
-
1773
- ### claw.deleteWebhook(webhookId)
1774
- Delete a webhook.
1775
-
1776
- **Parameters:**
1777
- | Parameter | Type | Required | Description |
1778
- |-----------|------|----------|-------------|
1779
- | webhookId | string | Yes | Webhook ID |
1780
-
1781
- **Returns:** `Promise<{deleted: boolean}>`
1782
-
1783
- ### claw.testWebhook(webhookId)
1784
- Send a test event to a webhook to verify connectivity.
1785
-
1786
- **Parameters:**
1787
- | Parameter | Type | Required | Description |
1788
- |-----------|------|----------|-------------|
1789
- | webhookId | string | Yes | Webhook ID |
1790
-
1791
- **Returns:** `Promise<{delivery: Object}>`
1792
-
1793
- ### claw.getWebhookDeliveries(webhookId)
1794
- Get delivery history for a webhook.
1795
-
1796
- **Parameters:**
1797
- | Parameter | Type | Required | Description |
1798
- |-----------|------|----------|-------------|
1799
- | webhookId | string | Yes | Webhook ID |
1800
-
1801
- **Returns:** `Promise<{deliveries: Object[]}>`
1802
-
1803
- ---
1804
-
1805
- ## Bulk Sync
1806
-
1807
- ### claw.syncState(state)
1808
- Push multiple data categories in a single request. Accepts connections, memory, goals, learning, content, inspiration, context_points, context_threads, handoffs, preferences, and snippets.
1809
-
1810
- **Returns:** `Promise<{results: Object, total_synced: number, total_errors: number, duration_ms: number}>`
1811
-
1812
- ---
1813
-
1814
- ## Policy Testing
1815
-
1816
- Run guardrails tests, generate compliance proof reports, and import policy packs.
1817
-
1818
- ### claw.testPolicies()
1819
- Run guardrails tests against all active policies. Returns pass/fail results per policy.
1820
-
1821
- **Returns:** `Promise<{ results: Object[], total: number, passed: number, failed: number }>`
1822
-
1823
- **Example:**
1824
- ```javascript
1825
- const report = await claw.testPolicies();
1826
- console.log(`${report.passed}/${report.total} policies passed`);
1827
- for (const r of report.results.filter(r => !r.passed)) {
1828
- console.log(`FAIL: ${r.policy}: ${r.reason}`);
1829
- }
1830
- ```
1831
-
1832
- ### claw.getProofReport(options?)
1833
- Generate a compliance proof report summarizing guard decisions, policy evaluations, and audit evidence.
1834
-
1835
- **Parameters:**
1836
- | Parameter | Type | Required | Description |
1837
- |-----------|------|----------|-------------|
1838
- | format | string | No | Output format: "json" (default) or "md" |
1839
-
1840
- **Returns:** `Promise<{ report: Object|string }>`
1841
-
1842
- ### claw.importPolicies({ pack?, yaml? })
1843
- Import a policy pack or raw YAML. Admin only. Replaces or merges into active policies.
1844
-
1845
- **Parameters:**
1846
- | Parameter | Type | Required | Description |
1847
- |-----------|------|----------|-------------|
1848
- | pack | string | No | Named policy pack: enterprise-strict, smb-safe, startup-growth, development |
1849
- | yaml | string | No | Raw YAML policy definition |
1850
-
1851
- **Returns:** `Promise<{ imported: number, policies: Object[] }>`
1852
-
1853
- ---
1854
-
1855
- ## Compliance Engine
1856
-
1857
- Map policies to regulatory frameworks, run gap analysis, and generate compliance reports.
1858
-
1859
- ### claw.mapCompliance(framework)
1860
- Map active policies to framework controls. Returns a control-by-control coverage matrix.
1861
-
1862
- **Parameters:**
1863
- | Parameter | Type | Required | Description |
1864
- |-----------|------|----------|-------------|
1865
- | framework | string | Yes | Target framework: soc2, iso27001, gdpr, nist-ai-rmf, imda-agentic |
1866
-
1867
- **Returns:** `Promise<{ framework: string, controls: Object[], coverage_pct: number }>`
1868
-
1869
- **Example:**
1870
- ```javascript
1871
- const { controls, coverage_pct } = await claw.mapCompliance('soc2');
1872
- console.log(`SOC 2 coverage: ${coverage_pct}%`);
1873
- for (const ctrl of controls.filter(c => !c.covered)) {
1874
- console.log(`Gap: ${ctrl.id}: ${ctrl.name}`);
1875
- }
1876
- ```
1877
-
1878
- ### claw.analyzeGaps(framework)
1879
- Run gap analysis with remediation plan. Identifies missing controls and suggests policy changes.
1880
-
1881
- **Parameters:**
1882
- | Parameter | Type | Required | Description |
1883
- |-----------|------|----------|-------------|
1884
- | framework | string | Yes | Target framework: soc2, iso27001, gdpr, nist-ai-rmf, imda-agentic |
1885
-
1886
- **Returns:** `Promise<{ framework: string, gaps: Object[], remediation_plan: Object[] }>`
1887
-
1888
- ### claw.getComplianceReport(framework, options?)
1889
- Generate a full compliance report and save a point-in-time snapshot.
1890
-
1891
- **Parameters:**
1892
- | Parameter | Type | Required | Description |
1893
- |-----------|------|----------|-------------|
1894
- | framework | string | Yes | Target framework |
1895
- | options.format | string | No | Output format: "json" (default) or "md" |
1896
-
1897
- **Returns:** `Promise<{ report: Object|string, snapshot_id: string }>`
1898
-
1899
- ### claw.listFrameworks()
1900
- List all available compliance frameworks with metadata.
1901
-
1902
- **Returns:** `Promise<{ frameworks: Object[] }>`
1903
-
1904
- ### claw.getComplianceEvidence(options?)
1905
- Get live guard decision evidence for compliance audits. Returns timestamped decision records.
1906
-
1907
- **Parameters:**
1908
- | Parameter | Type | Required | Description |
1909
- |-----------|------|----------|-------------|
1910
- | options.window | string | No | Time window: "7d" (default), "30d", "90d" |
1911
-
1912
- **Returns:** `Promise<{ evidence: Object[], window: string, total: number }>`
1913
-
1914
- ---
1915
-
1916
- ## Task Routing
1917
-
1918
- Route tasks to agents based on capabilities, availability, and workload. Manage the agent pool and monitor routing health.
1919
-
1920
- ### claw.listRoutingAgents(filters?)
1921
- List registered routing agents with optional status filter.
1922
-
1923
- **Parameters:**
1924
- | Parameter | Type | Required | Description |
1925
- |-----------|------|----------|-------------|
1926
- | filters.status | string | No | Filter by status: available, busy, offline |
1927
-
1928
- **Returns:** `Promise<{ agents: Object[], total: number }>`
1929
-
1930
- ### claw.registerRoutingAgent(agent)
1931
- Register a new agent in the routing pool.
1932
-
1933
- **Parameters:**
1934
- | Parameter | Type | Required | Description |
1935
- |-----------|------|----------|-------------|
1936
- | name | string | Yes | Agent display name |
1937
- | capabilities | string[] | No | List of skills/capabilities |
1938
- | maxConcurrent | number | No | Max concurrent tasks (default: 1) |
1939
- | endpoint | string | No | Agent callback endpoint URL |
1940
-
1941
- **Returns:** `Promise<{ agent: Object, agent_id: string }>`
1942
-
1943
- ### claw.getRoutingAgent(agentId)
1944
- Get a single routing agent with current metrics.
1945
-
1946
- **Parameters:**
1947
- | Parameter | Type | Required | Description |
1948
- |-----------|------|----------|-------------|
1949
- | agentId | string | Yes | The routing agent ID |
1950
-
1951
- **Returns:** `Promise<{ agent: Object, metrics: Object }>`
1952
-
1953
- ### claw.updateRoutingAgentStatus(agentId, status)
1954
- Update a routing agent's availability status.
1955
-
1956
- **Parameters:**
1957
- | Parameter | Type | Required | Description |
1958
- |-----------|------|----------|-------------|
1959
- | agentId | string | Yes | The routing agent ID |
1960
- | status | string | Yes | New status: available, busy, offline |
1961
-
1962
- **Returns:** `Promise<{ agent: Object }>`
1963
-
1964
- ### claw.deleteRoutingAgent(agentId)
1965
- Remove an agent from the routing pool.
1966
-
1967
- **Parameters:**
1968
- | Parameter | Type | Required | Description |
1969
- |-----------|------|----------|-------------|
1970
- | agentId | string | Yes | The routing agent ID |
1971
-
1972
- **Returns:** `Promise<{ deleted: boolean, id: string }>`
1973
-
1974
- ### claw.listRoutingTasks(filters?)
1975
- List routing tasks with optional filters.
1976
-
1977
- **Parameters:**
1978
- | Parameter | Type | Required | Description |
1979
- |-----------|------|----------|-------------|
1980
- | filters.status | string | No | Filter by status: pending, assigned, completed, failed |
1981
- | filters.agent_id | string | No | Filter by assigned agent |
1982
- | filters.limit | number | No | Max results (default: 50) |
1983
- | filters.offset | number | No | Pagination offset |
1984
-
1985
- **Returns:** `Promise<{ tasks: Object[], total: number }>`
1986
-
1987
- ### claw.submitRoutingTask(task)
1988
- Submit a task for automatic routing to the best available agent.
1989
-
1990
- **Parameters:**
1991
- | Parameter | Type | Required | Description |
1992
- |-----------|------|----------|-------------|
1993
- | title | string | Yes | Task title |
1994
- | description | string | No | Detailed description |
1995
- | requiredSkills | string[] | No | Skills needed to handle this task |
1996
- | urgency | string | No | low, medium, high, critical (default: medium) |
1997
- | timeoutSeconds | number | No | Task timeout in seconds |
1998
- | maxRetries | number | No | Max retry attempts on failure |
1999
- | callbackUrl | string | No | URL to notify on completion |
2000
-
2001
- **Returns:** `Promise<{ task: Object, task_id: string, assigned_agent: Object|null }>`
2002
-
2003
- **Example:**
2004
- ```javascript
2005
- const { task_id, assigned_agent } = await claw.submitRoutingTask({
2006
- title: 'Analyze quarterly metrics',
2007
- description: 'Pull Q4 data and generate summary report',
2008
- requiredSkills: ['data-analysis', 'reporting'],
2009
- urgency: 'high',
2010
- timeoutSeconds: 600,
2011
- callbackUrl: 'https://hooks.example.com/task-done',
2012
- });
2013
- console.log(`Task ${task_id} assigned to ${assigned_agent?.name ?? 'queue'}`);
2014
- ```
2015
-
2016
- ### claw.completeRoutingTask(taskId, result?)
2017
- Mark a routing task as completed with optional result payload.
2018
-
2019
- **Parameters:**
2020
- | Parameter | Type | Required | Description |
2021
- |-----------|------|----------|-------------|
2022
- | taskId | string | Yes | The task ID |
2023
- | result | Object | No | Task result data |
2024
-
2025
- **Returns:** `Promise<{ task: Object }>`
2026
-
2027
- ### claw.getRoutingStats()
2028
- Get aggregate routing statistics (throughput, latency, agent utilization).
2029
-
2030
- **Returns:** `Promise<{ stats: Object }>`
2031
-
2032
- ### claw.getRoutingHealth()
2033
- Get routing system health status and diagnostics.
2034
-
2035
- **Returns:** `Promise<{ healthy: boolean, agents: Object, tasks: Object, latency: Object }>`
2036
-
2037
- ---
2038
-
2039
- ## Agent Schedules
2040
-
2041
- Define recurring tasks and cron-based schedules for agents.
2042
-
2043
- ### claw.listAgentSchedules(filters?)
2044
- List agent schedules, optionally filtered by agent.
2045
-
2046
- ```javascript
2047
- const { schedules } = await claw.listAgentSchedules({ agent_id: 'forge' });
2048
- ```
2049
-
2050
- **Parameters:**
2051
- | Parameter | Type | Required | Description |
2052
- |-----------|------|----------|-------------|
2053
- | filters.agent_id | string | No | Filter by agent ID |
2054
-
2055
- **Returns:** `Promise<{ schedules: Object[] }>`
2056
-
2057
- ### claw.createAgentSchedule(schedule)
2058
- Create a new agent schedule entry.
2059
-
2060
- ```javascript
2061
- const { schedule } = await claw.createAgentSchedule({
2062
- agent_id: 'forge',
2063
- name: 'Build projects',
2064
- cron_expression: '0 */6 * * *',
2065
- description: 'Check for pending builds every 6 hours'
2066
- });
2067
- ```
2068
-
2069
- **Parameters:**
2070
- | Parameter | Type | Required | Description |
2071
- |-----------|------|----------|-------------|
2072
- | schedule.agent_id | string | Yes | Agent this schedule belongs to |
2073
- | schedule.name | string | Yes | Schedule name |
2074
- | schedule.cron_expression | string | Yes | Cron expression (e.g. `0 */6 * * *`) |
2075
- | schedule.description | string | No | Human-readable description |
2076
- | schedule.enabled | boolean | No | Whether schedule is active (default: true) |
2077
-
2078
- **Returns:** `Promise<{ schedule: Object }>`
2079
-
2080
- ---
2081
-
2082
- ## Error Handling
2083
-
2084
- All SDK methods throw on non-2xx responses. Errors include `status` (HTTP code) and `details` (when available).
2085
-
2086
- ```javascript
2087
- try {
2088
- await claw.createAction({ ... });
2089
- } catch (err) {
2090
- if (err.status === 401) {
2091
- console.error('Invalid API key');
2092
- } else {
2093
- console.error(`Action failed: \${err.message}`);
2094
- }
2095
- }
2096
- ```
1
+ # DashClaw SDK: Agent Decision Infrastructure
2
+
3
+ Full reference for the DashClaw SDK (Node.js). For Python, see the [Python SDK docs](../sdk-python/README.md).
4
+
5
+ DashClaw treats every agent action as a governed decision. The SDK provides decision recording, policy enforcement, evaluation, and compliance mapping. It proves what your agents decided and why.
6
+
7
+ Install, configure, and govern your AI agents with 178+ methods across 30+ categories including action recording, behavior guard, evaluation framework, scoring profiles, learning analytics, prompt management, feedback loops, behavioral drift, compliance exports, and more. Native adapters for **OpenClaw**, **CrewAI**, **AutoGen**, and **LangChain**.
8
+
9
+ ---
10
+
11
+ ## Quick Start
12
+
13
+ ### 1. Copy the SDK
14
+ Install from npm, or copy the single-file SDK directly.
15
+ ```bash
16
+ npm install dashclaw
17
+ ```
18
+
19
+ ### 2. Initialize the client
20
+ ```javascript
21
+ import { DashClaw } from 'dashclaw';
22
+
23
+ const claw = new DashClaw({
24
+ baseUrl: process.env.DASHCLAW_BASE_URL || 'http://localhost:3000',
25
+ // Use http://localhost:3000 for local, or https://your-app.vercel.app for cloud
26
+ apiKey: process.env.DASHCLAW_API_KEY,
27
+ agentId: 'my-agent',
28
+ agentName: 'My Agent',
29
+ hitlMode: 'wait', // Optional: automatically wait for human approval
30
+ });
31
+ ```
32
+
33
+ ### 3. Record your first action
34
+ ```javascript
35
+ // Create an action before doing work
36
+ const { action_id } = await claw.createAction({
37
+ action_type: 'deploy',
38
+ declared_goal: 'Deploy authentication service',
39
+ risk_score: 60,
40
+ });
41
+
42
+ // ... do the work ...
43
+
44
+ // Update when done
45
+ await claw.updateOutcome(action_id, {
46
+ status: 'completed',
47
+ output_summary: 'Auth service deployed to prod',
48
+ });
49
+ ```
50
+
51
+ ---
52
+
53
+ ## Constructor
54
+
55
+ Create a DashClaw instance. Requires Node 18+ (native fetch).
56
+
57
+ ```javascript
58
+ const claw = new DashClaw({
59
+ baseUrl,
60
+ apiKey,
61
+ agentId,
62
+ agentName,
63
+ swarmId,
64
+ guardMode,
65
+ guardCallback,
66
+ autoRecommend,
67
+ recommendationConfidenceMin,
68
+ recommendationCallback,
69
+ hitlMode,
70
+ });
71
+ ```
72
+
73
+ ### Parameters
74
+ | Parameter | Type | Required | Description |
75
+ |-----------|------|----------|-------------|
76
+ | baseUrl | string | Yes | DashClaw dashboard URL (e.g. "http://localhost:3000" or "https://your-app.vercel.app") |
77
+ | apiKey | string | Yes | API key for authentication (determines which org\'s data you access) |
78
+ | agentId | string | Yes | Unique identifier for this agent |
79
+ | agentName | string | No | Human-readable agent name |
80
+ | swarmId | string | No | Swarm/group identifier if part of a multi-agent system |
81
+ | guardMode | string | No | Auto guard check before createAction/track: "off" (default), "warn" (log + proceed), "enforce" (throw on block) |
82
+ | guardCallback | Function | No | Called with guard decision object when guardMode is active |
83
+ | autoRecommend | string | No | Recommendation auto-adapt mode: "off" (default), "warn" (record override), "enforce" (apply safe hints) |
84
+ | recommendationConfidenceMin | number | No | Min recommendation confidence required for auto-adapt in enforce mode (default 70) |
85
+ | recommendationCallback | Function | No | Called with recommendation adaptation details when autoRecommend is active |
86
+ | hitlMode | string | No | HITL behavior: "off" (default - return 202 immediately), "wait" (automatically block and poll until approved/denied) |
87
+
88
+ ### Guard Mode, Auto-Recommend, and HITL
89
+ When enabled, every call to `createAction()` can run recommendation adaptation and guard checks before submission.
90
+
91
+ ```javascript
92
+ import { DashClaw, GuardBlockedError, ApprovalDeniedError } from 'dashclaw';
93
+
94
+ const claw = new DashClaw({
95
+ baseUrl: 'http://localhost:3000',
96
+ apiKey: process.env.DASHCLAW_API_KEY,
97
+ agentId: 'my-agent',
98
+ autoRecommend: 'enforce', // apply safe recommendation hints
99
+ recommendationConfidenceMin: 80,
100
+ guardMode: 'enforce', // throws GuardBlockedError on block
101
+ hitlMode: 'wait', // poll until approved or throw ApprovalDeniedError
102
+ });
103
+
104
+ try {
105
+ await claw.createAction({ action_type: 'deploy', declared_goal: 'Ship v2' });
106
+ // If a policy triggers 'require_approval', the SDK will pause here until an admin clicks 'Allow'
107
+ } catch (err) {
108
+ if (err instanceof GuardBlockedError) {
109
+ console.log('Blocked by policy:', err.reasons);
110
+ } else if (err instanceof ApprovalDeniedError) {
111
+ console.log('Denied by human operator');
112
+ }
113
+ }
114
+ ```
115
+
116
+ ### Compliance & Governance Patterns
117
+
118
+ DashClaw's guard + action recording pipeline maps directly to compliance controls.
119
+
120
+ **SOC 2 CC6.1: Logical Access Controls**
121
+ ```javascript
122
+ // Before any high-risk operation, enforce policy
123
+ const guardResult = await claw.guard({
124
+ action_type: 'database_write',
125
+ risk_score: 85,
126
+ systems_touched: ['production_db'],
127
+ reversible: false,
128
+ declared_goal: 'Drop legacy user table'
129
+ });
130
+
131
+ if (guardResult.decision === 'block') {
132
+ // SOC 2 control satisfied: unauthorized action prevented
133
+ console.log('Policy blocked:', guardResult.reasons);
134
+ return;
135
+ }
136
+
137
+ // Decision is governed. Record with full lineage
138
+ const { action_id } = await claw.createAction({
139
+ action_type: 'database_write',
140
+ declared_goal: 'Drop legacy user table',
141
+ risk_score: 85,
142
+ reversible: false,
143
+ authorization_scope: 'admin-approved'
144
+ });
145
+
146
+ // Register the assumption this decision relies on
147
+ await claw.registerAssumption({
148
+ action_id,
149
+ assumption: 'Legacy table has zero active references',
150
+ basis: 'Schema dependency scan completed 2h ago'
151
+ });
152
+ ```
153
+
154
+ **EU AI Act Article 14: Human Oversight**
155
+ ```javascript
156
+ // require_approval forces human-in-the-loop
157
+ const result = await claw.guard({
158
+ action_type: 'customer_communication',
159
+ risk_score: 60,
160
+ declared_goal: 'Send pricing update to 500 customers'
161
+ });
162
+
163
+ if (result.decision === 'require_approval') {
164
+ // Create action in pending state, wait for human approval
165
+ const { action_id } = await claw.createAction({
166
+ action_type: 'customer_communication',
167
+ declared_goal: 'Send pricing update to 500 customers',
168
+ status: 'pending'
169
+ });
170
+ // Approval queue at /approvals shows this to operators
171
+ }
172
+ ```
173
+
174
+ **ISO 42001: AI Decision Accountability**
175
+ ```javascript
176
+ // Full decision lineage: guard → action → assumptions → outcome
177
+ const { action_id } = await claw.createAction({
178
+ action_type: 'data_processing',
179
+ declared_goal: 'Rebuild customer segmentation model',
180
+ risk_score: 45,
181
+ systems_touched: ['ml-pipeline', 'customer-db']
182
+ });
183
+
184
+ await claw.registerAssumption({
185
+ action_id,
186
+ assumption: 'Customer data is current as of today',
187
+ basis: 'CRM sync completed at 09:00 UTC'
188
+ });
189
+
190
+ // Later: validate or invalidate assumptions
191
+ await claw.validateAssumption(assumptionId, true);
192
+
193
+ // Decision integrity signals auto-detect when assumptions drift
194
+ const signals = await claw.getSignals();
195
+ // → Returns 'assumption_drift' if too many invalidated
196
+ ```
197
+
198
+ ---
199
+
200
+ ## Action Recording
201
+
202
+ Create, update, and query action records. Every agent action is a governed decision with a full audit trail capturing intent, reasoning, and outcome for compliance and review.
203
+
204
+ ### claw.createAction(action)
205
+ Create a new action record. The agent's agentId, agentName, and swarmId are automatically attached.
206
+
207
+ If `hitlMode` is set to `'wait'` and the action requires approval, this method will not return until the action is approved or denied (or it times out).
208
+
209
+ **Parameters:**
210
+ | Parameter | Type | Required | Description |
211
+ |-----------|------|----------|-------------|
212
+ | action_type | string | Yes | One of: build, deploy, post, apply, security, message, api, calendar, research, review, fix, refactor, test, config, monitor, alert, cleanup, sync, migrate, other |
213
+ | declared_goal | string | Yes | What this action aims to accomplish |
214
+ | action_id | string | No | Custom action ID (auto-generated act_ UUID if omitted) |
215
+ | reasoning | string | No | Why the agent decided to take this action |
216
+ | authorization_scope | string | No | What permissions were granted |
217
+ | trigger | string | No | What triggered this action |
218
+ | systems_touched | string[] | No | Systems this action interacts with |
219
+ | input_summary | string | No | Summary of input data |
220
+ | parent_action_id | string | No | Parent action if this is a sub-action |
221
+ | reversible | boolean | No | Whether this action can be undone (default: true) |
222
+ | risk_score | number | No | Risk score 0-100 (default: 0) |
223
+ | confidence | number | No | Confidence level 0-100 (default: 50) |
224
+
225
+ **Returns:** `Promise<{ action: Object, action_id: string }>`
226
+
227
+ **Example:**
228
+ ```javascript
229
+ const { action_id } = await claw.createAction({
230
+ action_type: 'deploy',
231
+ declared_goal: 'Deploy auth service to production',
232
+ risk_score: 70,
233
+ systems_touched: ['kubernetes', 'auth-service'],
234
+ reasoning: 'Scheduled release after QA approval',
235
+ });
236
+ ```
237
+
238
+ ### claw.waitForApproval(actionId, options?)
239
+ Manual poll for human approval. Only needed if `hitlMode` is `'off'`.
240
+
241
+ **Parameters:**
242
+ | Parameter | Type | Required | Description |
243
+ |-----------|------|----------|-------------|
244
+ | actionId | string | Yes | The action_id to poll |
245
+ | options.timeout | number | No | Max wait time in ms (default: 300000 / 5 min) |
246
+ | options.interval | number | No | Poll interval in ms (default: 5000) |
247
+
248
+ **Returns:** `Promise<{ action: Object, action_id: string }>`
249
+ **Throws:** `ApprovalDeniedError` if denied.
250
+
251
+ ### claw.updateOutcome(actionId, outcome)
252
+ Update the outcome of an existing action. Automatically sets timestamp_end if not provided.
253
+
254
+ **Parameters:**
255
+ | Parameter | Type | Required | Description |
256
+ |-----------|------|----------|-------------|
257
+ | actionId | string | Yes | The action_id to update |
258
+ | status | string | No | New status: completed, failed, cancelled |
259
+ | output_summary | string | No | What happened |
260
+ | side_effects | string[] | No | Unintended consequences |
261
+ | artifacts_created | string[] | No | Files, records, etc. created |
262
+ | error_message | string | No | Error details if failed |
263
+ | duration_ms | number | No | How long it took in milliseconds |
264
+ | cost_estimate | number | No | Estimated cost in USD |
265
+
266
+ **Returns:** `Promise<{ action: Object }>`
267
+
268
+ ### claw.track(actionDef, fn)
269
+ 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.
270
+
271
+ **Parameters:**
272
+ | Parameter | Type | Required | Description |
273
+ |-----------|------|----------|-------------|
274
+ | actionDef | Object | Yes | Action definition (same params as createAction) |
275
+ | fn | Function | Yes | Async function to execute. Receives { action_id } as argument. |
276
+
277
+ **Returns:** `Promise<*> (the return value of fn)`
278
+
279
+ ### claw.getActions(filters?)
280
+ Get a list of actions with optional filters. Returns paginated results with stats.
281
+
282
+ **Parameters:**
283
+ | Parameter | Type | Required | Description |
284
+ |-----------|------|----------|-------------|
285
+ | agent_id | string | No | Filter by agent |
286
+ | swarm_id | string | No | Filter by swarm |
287
+ | status | string | No | Filter by status (running, completed, failed, cancelled) |
288
+ | action_type | string | No | Filter by type |
289
+ | risk_min | number | No | Minimum risk score |
290
+ | limit | number | No | Max results (default: 50) |
291
+ | offset | number | No | Pagination offset (default: 0) |
292
+
293
+ **Returns:** `Promise<{ actions: Object[], total: number, stats: Object }>`
294
+
295
+ ### claw.getAction(actionId)
296
+ Get a single action with its associated open loops and assumptions.
297
+
298
+ **Parameters:**
299
+ | Parameter | Type | Required | Description |
300
+ |-----------|------|----------|-------------|
301
+ | actionId | string | Yes | The action_id to retrieve |
302
+
303
+ **Returns:** `Promise<{ action: Object, open_loops: Object[], assumptions: Object[] }>`
304
+
305
+ ### claw.getActionTrace(actionId)
306
+ Get root-cause trace for an action, including its assumptions, open loops, parent chain, and related actions.
307
+
308
+ **Parameters:**
309
+ | Parameter | Type | Required | Description |
310
+ |-----------|------|----------|-------------|
311
+ | actionId | string | Yes | The action_id to trace |
312
+
313
+ **Returns:** `Promise<{ action: Object, trace: Object }>`
314
+
315
+ ---
316
+
317
+ ## Evaluation Framework
318
+
319
+ Track output quality automatically with 5 built-in scorer types. No LLM required for most scorers.
320
+
321
+ ### claw.createScorer({ name, scorerType, config, description })
322
+ Create a new evaluation scorer.
323
+
324
+ **Parameters:**
325
+ | Parameter | Type | Required | Description |
326
+ |-----------|------|----------|-------------|
327
+ | name | string | Yes | Scorer name |
328
+ | scorerType | string | Yes | regex, keywords, numeric_range, custom_function, or llm_judge |
329
+ | config | Object | Yes | Configuration for the scorer |
330
+ | description | string | No | Purpose of this scorer |
331
+
332
+ **Returns:** `Promise<Object>`
333
+
334
+ **Example:**
335
+ ```javascript
336
+ await claw.createScorer({
337
+ name: 'JSON Validator',
338
+ scorerType: 'regex',
339
+ config: { pattern: '^\\{.*\\}$' },
340
+ });
341
+ ```
342
+
343
+ ### claw.getScorers()
344
+ List all available scorers.
345
+
346
+ **Returns:** `Promise<{ scorers: Object[], llm_available: boolean }>`
347
+
348
+ ### claw.getEvalRuns(filters?)
349
+ List evaluation runs with status and result summaries.
350
+
351
+ **Parameters:**
352
+ | Parameter | Type | Required | Description |
353
+ |-----------|------|----------|-------------|
354
+ | status | string | No | running, completed, failed |
355
+ | limit | number | No | Max results |
356
+
357
+ **Returns:** `Promise<{ runs: Object[] }>`
358
+
359
+ ### claw.getEvalStats(filters?)
360
+ Get aggregate evaluation statistics across scorers and agents.
361
+
362
+ **Parameters:**
363
+ | Parameter | Type | Required | Description |
364
+ |-----------|------|----------|-------------|
365
+ | agent_id | string | No | Filter by agent |
366
+ | scorer_name | string | No | Filter by scorer |
367
+ | days | number | No | Lookback period |
368
+
369
+ **Returns:** `Promise<Object>`
370
+
371
+ ---
372
+
373
+ ## Prompt Management
374
+
375
+ Version-controlled prompt templates with mustache variable rendering.
376
+
377
+ ### claw.createPromptTemplate({ name, content, category })
378
+ Create a new prompt template.
379
+
380
+ **Parameters:**
381
+ | Parameter | Type | Required | Description |
382
+ |-----------|------|----------|-------------|
383
+ | name | string | Yes | Template name |
384
+ | content | string | Yes | Template content with {{variables}} |
385
+ | category | string | No | Optional grouping category |
386
+
387
+ **Returns:** `Promise<Object>`
388
+
389
+ ### claw.getPromptTemplate(templateId)
390
+ Get a template by ID, including its current active version.
391
+
392
+ **Returns:** `Promise<Object>`
393
+
394
+ ### claw.renderPrompt({ template_id, variables, action_id })
395
+ Render a template with variables on the server. Optionally link to an action for usage tracking.
396
+
397
+ **Parameters:**
398
+ | Parameter | Type | Required | Description |
399
+ |-----------|------|----------|-------------|
400
+ | template_id | string | Yes | Template ID |
401
+ | variables | Object | Yes | Mustache variables |
402
+ | action_id | string | No | Link to an action |
403
+
404
+ **Returns:** `Promise<{ rendered: string }>`
405
+
406
+ ### claw.listPromptVersions(templateId)
407
+ List all versions of a prompt template.
408
+
409
+ **Returns:** `Promise<Object[]>`
410
+
411
+ ### claw.activatePromptVersion(templateId, versionId)
412
+ Set a specific version as the active one for a template.
413
+
414
+ **Returns:** `Promise<Object>`
415
+
416
+ ---
417
+
418
+ ## User Feedback
419
+
420
+ Collect and analyze human feedback on agent actions.
421
+
422
+ ### claw.submitFeedback({ action_id, agent_id, rating, comment, category, tags })
423
+ Submit feedback for a specific action.
424
+
425
+ **Parameters:**
426
+ | Parameter | Type | Required | Description |
427
+ |-----------|------|----------|-------------|
428
+ | action_id | string | Yes | Action ID |
429
+ | agent_id | string | No | Agent ID |
430
+ | rating | number | Yes | Rating 1-5 |
431
+ | comment | string | No | Optional text feedback |
432
+ | category | string | No | Optional category |
433
+ | tags | string[] | No | Optional tags |
434
+
435
+ **Returns:** `Promise<Object>`
436
+
437
+ ### claw.getFeedback(feedbackId)
438
+ Retrieve a single feedback entry.
439
+
440
+ **Returns:** `Promise<Object>`
441
+
442
+ ### claw.getFeedbackStats({ agent_id })
443
+ Get feedback statistics, including average rating and sentiment trends.
444
+
445
+ **Returns:** `Promise<Object>`
446
+
447
+ ---
448
+
449
+ ## Behavioral Drift
450
+
451
+ Monitor agent behavior deviations from statistical baselines using z-scores.
452
+
453
+ ### claw.computeDriftBaselines({ agent_id, lookback_days })
454
+ Establish statistical baselines for an agent's behavior metrics.
455
+
456
+ **Returns:** `Promise<Object>`
457
+
458
+ ### claw.detectDrift({ agent_id, window_days })
459
+ Run drift detection against the established baselines.
460
+
461
+ **Returns:** `Promise<Object>`
462
+
463
+ ### claw.listDriftAlerts(filters?)
464
+ List behavioral drift alerts with severity and status.
465
+
466
+ **Returns:** `Promise<Object[]>`
467
+
468
+ ---
469
+
470
+ ## Compliance Exports
471
+
472
+ Generate evidence packages for SOC 2, NIST AI RMF, EU AI Act, and ISO 42001.
473
+
474
+ ### claw.createComplianceExport({ name, frameworks, format, window_days })
475
+ Generate a compliance export bundle.
476
+
477
+ **Returns:** `Promise<Object>`
478
+
479
+ ### claw.getComplianceExport(exportId)
480
+ Get the status and details of a compliance export.
481
+
482
+ **Returns:** `Promise<Object>`
483
+
484
+ ### claw.listComplianceExports({ limit })
485
+ List recent compliance exports.
486
+
487
+ **Returns:** `Promise<Object[]>`
488
+
489
+ ---
490
+
491
+ ## Learning Analytics
492
+
493
+ Track agent improvement velocity, maturity levels, and learning curves per skill.
494
+
495
+ ### claw.getLearningVelocity({ agent_id })
496
+ Get agent improvement rate over time.
497
+
498
+ **Returns:** `Promise<Object>`
499
+
500
+ ### claw.getMaturityLevels()
501
+ Get the 6-level maturity model distribution for the agent.
502
+
503
+ **Returns:** `Promise<Object>`
504
+
505
+ ### claw.getLearningCurves({ agent_id, action_type })
506
+ Get performance improvement curves for a specific skill/action type.
507
+
508
+ **Returns:** `Promise<Object>`
509
+
510
+ ---
511
+
512
+ ## Scoring Profiles
513
+
514
+ User-defined weighted quality scoring with 3 composite methods, 8 data sources, risk templates, and auto-calibration. Zero LLM required.
515
+
516
+ ### claw.createScoringProfile({ name, action_type, composite_method, dimensions })
517
+ Create a scoring profile with optional inline dimensions.
518
+
519
+ **Parameters:**
520
+ | Parameter | Type | Required | Description |
521
+ |-----------|------|----------|-------------|
522
+ | name | string | Yes | Profile name |
523
+ | action_type | string | No | Filter to specific action type (null = all) |
524
+ | composite_method | string | No | weighted_average (default), minimum, or geometric_mean |
525
+ | dimensions | Array | No | Inline dimension definitions (name, data_source, weight, scale) |
526
+
527
+ **Returns:** `Promise<Object>`
528
+
529
+ **Example:**
530
+ ```javascript
531
+ const profile = await dc.createScoringProfile({
532
+ name: 'deploy-quality',
533
+ action_type: 'deploy',
534
+ composite_method: 'weighted_average',
535
+ dimensions: [
536
+ { name: 'Speed', data_source: 'duration_ms', weight: 0.3,
537
+ scale: [
538
+ { label: 'excellent', operator: 'lt', value: 30000, score: 100 },
539
+ { label: 'good', operator: 'lt', value: 60000, score: 75 },
540
+ { label: 'poor', operator: 'gte', value: 60000, score: 20 },
541
+ ]},
542
+ { name: 'Reliability', data_source: 'confidence', weight: 0.7,
543
+ scale: [
544
+ { label: 'excellent', operator: 'gte', value: 0.9, score: 100 },
545
+ { label: 'poor', operator: 'lt', value: 0.7, score: 25 },
546
+ ]},
547
+ ],
548
+ });
549
+ ```
550
+
551
+ ### claw.scoreWithProfile(profile_id, action)
552
+ Score a single action against a profile. Returns composite score + per-dimension breakdown.
553
+
554
+ **Parameters:**
555
+ | Parameter | Type | Required | Description |
556
+ |-----------|------|----------|-------------|
557
+ | profile_id | string | Yes | Profile to score against |
558
+ | action | Object | Yes | Action data object |
559
+
560
+ **Returns:** `Promise<Object>`
561
+
562
+ ### claw.batchScoreWithProfile(profile_id, actions)
563
+ Score multiple actions at once. Returns per-action results + summary.
564
+
565
+ **Returns:** `Promise<Object>`
566
+
567
+ ### claw.createRiskTemplate({ name, base_risk, rules })
568
+ Create a rule-based risk template. Replaces hardcoded agent risk numbers.
569
+
570
+ **Returns:** `Promise<Object>`
571
+
572
+ ### claw.autoCalibrate({ action_type, lookback_days })
573
+ Analyze historical action data to suggest scoring thresholds from percentile distribution.
574
+
575
+ **Returns:** `Promise<Object>`
576
+
577
+ ---
578
+
579
+ ## Agent Presence & Health
580
+
581
+ Monitor agent uptime and status in real-time. Use heartbeats to detect when an agent crashes or loses network connectivity.
582
+
583
+ ### claw.heartbeat(options?)
584
+ Report agent presence and health to the dashboard.
585
+
586
+ **Parameters:**
587
+ | Parameter | Type | Required | Description |
588
+ |-----------|------|----------|-------------|
589
+ | options.status | string | No | Agent status: 'online', 'busy', 'error' (default: 'online') |
590
+ | options.currentTaskId | string | No | The ID of the task currently being executed |
591
+ | options.metadata | Object | No | Optional key-value pairs for additional context |
592
+
593
+ **Returns:** `Promise<{ status: string, timestamp: string }>`
594
+
595
+ ### claw.startHeartbeat(options?)
596
+ Start an automatic heartbeat timer that reports 'online' every minute.
597
+
598
+ **Parameters:**
599
+ | Parameter | Type | Required | Description |
600
+ |-----------|------|----------|-------------|
601
+ | options.interval | number | No | Heartbeat interval in milliseconds (default: 60000 / 1 min) |
602
+ | options.status | string | No | Status to report |
603
+
604
+ **Example:**
605
+ ```javascript
606
+ // Start reporting presence automatically
607
+ claw.startHeartbeat();
608
+
609
+ // Later, stop it
610
+ claw.stopHeartbeat();
611
+ ```
612
+
613
+ ### claw.stopHeartbeat()
614
+ Stop the automatic heartbeat timer.
615
+
616
+ ---
617
+
618
+ ## Real-Time Flight Recorder
619
+
620
+ Stream actions live to the dashboard as they happen.
621
+
622
+ ### claw.track(actionDef, fn)
623
+ (Already documented above) - Use `track()` to automatically emit `running` events at start and `completed`/`failed` events at finish. These show up instantly on the "Flight Recorder" dashboard.
624
+
625
+ ---
626
+
627
+ ## Real-Time Events
628
+
629
+ Subscribe to server-sent events (SSE) for instant push notifications. Eliminates polling for approvals, policy changes, and task assignments.
630
+
631
+ ### claw.events()
632
+
633
+ Open a persistent SSE connection. Returns a chainable handle with `.on(event, callback)` and `.close()`.
634
+
635
+ **Supported events:** `action.created`, `action.updated`, `message.created`, `policy.updated`, `task.assigned`, `task.completed`
636
+
637
+ ```javascript
638
+ const stream = claw.events();
639
+
640
+ stream
641
+ .on('action.created', (data) => console.log('New action:', data.action_id))
642
+ .on('action.updated', (data) => {
643
+ if (data.status === 'running') console.log('Approved:', data.action_id);
644
+ })
645
+ .on('policy.updated', (data) => console.log('Policy changed:', data.change_type))
646
+ .on('task.assigned', (data) => console.log('Task routed:', data.task?.title))
647
+ .on('task.completed', (data) => console.log('Task done:', data.task?.task_id))
648
+ .on('error', (err) => console.error('Stream error:', err));
649
+
650
+ // When done:
651
+ stream.close();
652
+ ```
653
+
654
+ ### claw.waitForApproval(actionId, { useEvents: true })
655
+
656
+ SSE-powered approval waiting. Resolves instantly when the operator approves/denies instead of polling every 5 seconds.
657
+
658
+ ```javascript
659
+ // SSE mode (instant, recommended)
660
+ const { action } = await claw.waitForApproval('act_abc', { useEvents: true });
661
+
662
+ // Polling mode (default, backward-compatible)
663
+ const { action } = await claw.waitForApproval('act_abc');
664
+ ```
665
+
666
+ | Parameter | Type | Default | Description |
667
+ |-----------|------|---------|-------------|
668
+ | actionId | string | Yes | Action ID to watch |
669
+ | options.timeout | number | 300000 | Max wait time (ms) |
670
+ | options.interval | number | 5000 | Poll interval (polling mode only) |
671
+ | options.useEvents | boolean | false | Use SSE instead of polling |
672
+
673
+ ---
674
+
675
+ ## Token & Cost Analytics
676
+
677
+ Track token usage and estimated costs for every action. DashClaw automatically aggregates these into "Cost per Goal" metrics.
678
+
679
+ **Usage:**
680
+ Pass `tokens_in`, `tokens_out`, and `model` when creating or updating actions.
681
+
682
+ ```javascript
683
+ await claw.createAction({
684
+ action_type: 'generation',
685
+ declared_goal: 'Generate blog post',
686
+ model: 'gpt-4o',
687
+ tokens_in: 1500,
688
+ tokens_out: 400,
689
+ // cost_estimate is auto-calculated on the server if model is known
690
+ });
691
+ ```
692
+
693
+ **Supported Models for Auto-Pricing:**
694
+ - GPT-4o, GPT-4-Turbo
695
+ - Claude 3.5 Sonnet, Claude 3 Opus, Claude 3 Haiku
696
+ - Llama 3 (70b, 8b)
697
+
698
+ ---
699
+
700
+ ## Loops & Assumptions
701
+
702
+ Track unresolved dependencies and log what your agents assume. Catch drift before it causes failures.
703
+
704
+ ### claw.registerOpenLoop(loop)
705
+ Register an open loop (unresolved dependency, pending approval, etc.) for an action.
706
+
707
+ **Parameters:**
708
+ | Parameter | Type | Required | Description |
709
+ |-----------|------|----------|-------------|
710
+ | action_id | string | Yes | Parent action ID |
711
+ | loop_type | string | Yes | One of: followup, question, dependency, approval, review, handoff, other |
712
+ | description | string | Yes | What needs to be resolved |
713
+ | priority | string | No | One of: low, medium, high, critical (default: medium) |
714
+ | owner | string | No | Who is responsible for resolving this |
715
+
716
+ **Returns:** `Promise<{ loop: Object, loop_id: string }>`
717
+
718
+ ### claw.resolveOpenLoop(loopId, status, resolution?)
719
+ Resolve or cancel an open loop.
720
+
721
+ **Parameters:**
722
+ | Parameter | Type | Required | Description |
723
+ |-----------|------|----------|-------------|
724
+ | loopId | string | Yes | The loop_id to resolve |
725
+ | status | string | Yes | "resolved" or "cancelled" |
726
+ | resolution | string | No | Resolution description (required when resolving) |
727
+
728
+ **Returns:** `Promise<{ loop: Object }>`
729
+
730
+ ### claw.registerAssumption(assumption)
731
+ Register an assumption made during an action. Track what your agent assumes so you can validate or invalidate later.
732
+
733
+ **Parameters:**
734
+ | Parameter | Type | Required | Description |
735
+ |-----------|------|----------|-------------|
736
+ | action_id | string | Yes | Parent action ID |
737
+ | assumption | string | Yes | The assumption being made |
738
+ | basis | string | No | Evidence or reasoning for the assumption |
739
+ | validated | boolean | No | Whether this has been validated (default: false) |
740
+
741
+ **Returns:** `Promise<{ assumption: Object, assumption_id: string }>`
742
+
743
+ ### claw.getAssumption(assumptionId)
744
+ Get a single assumption by ID.
745
+
746
+ **Parameters:**
747
+ | Parameter | Type | Required | Description |
748
+ |-----------|------|----------|-------------|
749
+ | assumptionId | string | Yes | The assumption_id to retrieve |
750
+
751
+ **Returns:** `Promise<{ assumption: Object }>`
752
+
753
+ ### claw.validateAssumption(assumptionId, validated, invalidated_reason?)
754
+ Validate or invalidate an assumption. When invalidating, a reason is required.
755
+
756
+ **Parameters:**
757
+ | Parameter | Type | Required | Description |
758
+ |-----------|------|----------|-------------|
759
+ | assumptionId | string | Yes | The assumption_id to update |
760
+ | validated | boolean | Yes | true to validate, false to invalidate |
761
+ | invalidated_reason | string | No | Required when invalidating (validated = false) |
762
+
763
+ **Returns:** `Promise<{ assumption: Object }>`
764
+
765
+ ### claw.getOpenLoops(filters?)
766
+ Get open loops with optional filters. Returns paginated results with stats.
767
+
768
+ **Parameters:**
769
+ | Parameter | Type | Required | Description |
770
+ |-----------|------|----------|-------------|
771
+ | status | string | No | Filter by status: open, resolved, cancelled |
772
+ | loop_type | string | No | Filter by loop type |
773
+ | priority | string | No | Filter by priority |
774
+ | limit | number | No | Max results (default: 50) |
775
+
776
+ **Returns:** `Promise<{ loops: Object[], total: number, stats: Object }>`
777
+
778
+ ### claw.getDriftReport(filters?)
779
+ Get drift report for assumptions with risk scoring. Shows which assumptions are stale, unvalidated, or contradicted by outcomes.
780
+
781
+ **Parameters:**
782
+ | Parameter | Type | Required | Description |
783
+ |-----------|------|----------|-------------|
784
+ | action_id | string | No | Filter by action |
785
+ | limit | number | No | Max results (default: 50) |
786
+
787
+ **Returns:** `Promise<{ assumptions: Object[], drift_summary: Object }>`
788
+
789
+ ---
790
+
791
+ ## Signals
792
+
793
+ Automatic detection of problematic agent behavior. Seven signal types fire based on action patterns - no configuration required.
794
+
795
+ ### claw.getSignals()
796
+ 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.
797
+
798
+ **Returns:** `Promise<{ signals: Object[], counts: { red: number, amber: number, total: number } }>`
799
+
800
+ ### Signal Types
801
+ - **autonomy_spike**: Agent taking too many actions without human checkpoints
802
+ - **high_impact_low_oversight**: Critical actions without sufficient review
803
+ - **repeated_failures**: Same action type failing multiple times
804
+ - **stale_loop**: Open loops unresolved past their expected timeline
805
+ - **assumption_drift**: Assumptions becoming stale or contradicted by outcomes
806
+ - **stale_assumption**: Assumptions not validated within expected timeframe
807
+ - **stale_running_action**: Actions stuck in running state for over 4 hours
808
+
809
+ ---
810
+
811
+ ## Behavior Guard
812
+
813
+ Guard is the heart of DashClaw. Every action can be checked against policies before execution. Returns allow, warn, block, or require_approval based on configured guard policies.
814
+
815
+ ### claw.guard(context, options?)
816
+ 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.
817
+
818
+ **Parameters:**
819
+ | Parameter | Type | Required | Description |
820
+ |-----------|------|----------|-------------|
821
+ | context.action_type | string | Yes | The type of action being proposed |
822
+ | context.risk_score | number | No | Risk score 0-100 |
823
+ | context.systems_touched | string[] | No | Systems this action will affect |
824
+ | context.reversible | boolean | No | Whether the action can be undone |
825
+ | context.declared_goal | string | No | What the action accomplishes |
826
+ | options.includeSignals | boolean | No | Also check live risk signals (adds latency) |
827
+
828
+ **Returns:** `Promise<{ decision: string, reasons: string[], warnings: string[], matched_policies: string[], evaluated_at: string }>`
829
+
830
+ ### claw.getGuardDecisions(filters?)
831
+ Retrieve recent guard evaluation decisions for audit and review.
832
+
833
+ **Parameters:**
834
+ | Parameter | Type | Required | Description |
835
+ |-----------|------|----------|-------------|
836
+ | filters.decision | string | No | Filter by decision: allow, warn, block, require_approval |
837
+ | filters.limit | number | No | Max results (default 20, max 100) |
838
+ | filters.offset | number | No | Pagination offset |
839
+
840
+ **Returns:** `Promise<{ decisions: Object[], total: number, stats: Object }>`
841
+
842
+ ---
843
+
844
+ ## Dashboard Data
845
+
846
+ Push data from your agent directly to the DashClaw dashboard. All methods auto-attach the agent's agentId.
847
+
848
+ ### claw.reportTokenUsage(usage)
849
+ Report a token usage snapshot for this agent.
850
+
851
+ **Parameters:**
852
+ | Parameter | Type | Required | Description |
853
+ |-----------|------|----------|-------------|
854
+ | tokens_in | number | Yes | Input tokens consumed |
855
+ | tokens_out | number | Yes | Output tokens generated |
856
+ | context_used | number | No | Context window tokens used |
857
+ | context_max | number | No | Context window max capacity |
858
+ | model | string | No | Model name |
859
+
860
+ **Returns:** `Promise<{snapshot: Object}>`
861
+
862
+ ### claw.wrapClient(llmClient, options?)
863
+ Wrap an Anthropic or OpenAI client to auto-report token usage after every call. Returns the same client instance for fluent usage. Streaming calls (where response lacks `.usage`) are safely ignored.
864
+
865
+ **Parameters:**
866
+ | Parameter | Type | Required | Description |
867
+ |-----------|------|----------|-------------|
868
+ | llmClient | Object | Yes | An Anthropic or OpenAI SDK client instance |
869
+ | options.provider | string | No | Force `'anthropic'` or `'openai'` if auto-detect fails |
870
+
871
+ **Returns:** The wrapped client (same instance)
872
+
873
+ **Example (Anthropic):**
874
+ ```javascript
875
+ import Anthropic from '@anthropic-ai/sdk';
876
+ import { DashClaw } from 'dashclaw';
877
+
878
+ const claw = new DashClaw({ baseUrl: 'http://localhost:3000', agentId: 'my-agent', apiKey: '...' });
879
+ const anthropic = claw.wrapClient(new Anthropic());
880
+
881
+ const msg = await anthropic.messages.create({
882
+ model: 'claude-sonnet-4-20250514',
883
+ max_tokens: 1024,
884
+ messages: [{ role: 'user', content: 'Hello' }],
885
+ });
886
+ // Token usage auto-reported to DashClaw
887
+ ```
888
+
889
+ **Example (OpenAI):**
890
+ ```javascript
891
+ import OpenAI from 'openai';
892
+
893
+ const openai = claw.wrapClient(new OpenAI());
894
+
895
+ const chat = await openai.chat.completions.create({
896
+ model: 'gpt-4o',
897
+ messages: [{ role: 'user', content: 'Hello' }],
898
+ });
899
+ // Token usage auto-reported to DashClaw
900
+ ```
901
+
902
+ ### claw.recordDecision(entry)
903
+ Record a decision for the learning database. Track what your agent decides and why.
904
+
905
+ **Parameters:**
906
+ | Parameter | Type | Required | Description |
907
+ |-----------|------|----------|-------------|
908
+ | decision | string | Yes | What was decided |
909
+ | context | string | No | Context around the decision |
910
+ | reasoning | string | No | Why this decision was made |
911
+ | outcome | string | No | "success", "failure", or "pending" |
912
+ | confidence | number | No | Confidence level 0-100 |
913
+
914
+ **Returns:** `Promise<{ decision: Object }>`
915
+
916
+ ### claw.getRecommendations(filters?)
917
+ Get adaptive recommendations synthesized from scored historical episodes.
918
+
919
+ **Parameters:**
920
+ | Parameter | Type | Required | Description |
921
+ |-----------|------|----------|-------------|
922
+ | filters.action_type | string | No | Filter by action type |
923
+ | filters.agent_id | string | No | Override agent scope (defaults to SDK agent) |
924
+ | filters.include_inactive | boolean | No | Include disabled recommendations (admin/service only) |
925
+ | filters.track_events | boolean | No | Record fetched telemetry (default true) |
926
+ | filters.include_metrics | boolean | No | Include computed metrics in response |
927
+ | filters.lookback_days | number | No | Lookback window for include_metrics |
928
+ | filters.limit | number | No | Max results (default 50) |
929
+
930
+ **Returns:** `Promise<{ recommendations: Object[], metrics?: Object, total: number }>`
931
+
932
+ ### claw.getRecommendationMetrics(filters?)
933
+ Get recommendation telemetry and effectiveness deltas.
934
+
935
+ **Parameters:**
936
+ | Parameter | Type | Required | Description |
937
+ |-----------|------|----------|-------------|
938
+ | filters.action_type | string | No | Filter by action type |
939
+ | filters.agent_id | string | No | Override agent scope (defaults to SDK agent) |
940
+ | filters.lookback_days | number | No | Lookback window (default 30) |
941
+ | filters.limit | number | No | Max recommendations to evaluate (default 100) |
942
+ | filters.include_inactive | boolean | No | Include disabled recommendations (admin/service only) |
943
+
944
+ **Returns:** `Promise<{ metrics: Object[], summary: Object, lookback_days: number }>`
945
+
946
+ ### claw.recordRecommendationEvents(events)
947
+ Write recommendation telemetry events (single event or batch).
948
+
949
+ **Returns:** `Promise<{ created: Object[], created_count: number }>`
950
+
951
+ ### claw.setRecommendationActive(recommendationId, active)
952
+ Enable or disable one recommendation.
953
+
954
+ **Returns:** `Promise<{ recommendation: Object }>`
955
+
956
+ ### claw.rebuildRecommendations(options?)
957
+ Recompute recommendations from recent learning episodes.
958
+
959
+ **Parameters:**
960
+ | Parameter | Type | Required | Description |
961
+ |-----------|------|----------|-------------|
962
+ | options.action_type | string | No | Restrict rebuild to one action type |
963
+ | options.lookback_days | number | No | Episode history window (default 30) |
964
+ | options.min_samples | number | No | Minimum samples per recommendation (default 5) |
965
+ | options.episode_limit | number | No | Episode scan cap (default 5000) |
966
+ | options.action_id | string | No | Score this action before rebuilding |
967
+
968
+ **Returns:** `Promise<{ recommendations: Object[], total: number, episodes_scanned: number }>`
969
+
970
+ ### claw.recommendAction(action)
971
+ Apply top recommendation hints to an action payload without mutating the original object.
972
+
973
+ **Returns:** `Promise<{ action: Object, recommendation: Object|null, adapted_fields: string[] }>`
974
+
975
+ ### claw.createGoal(goal)
976
+ Create a goal in the goals tracker.
977
+
978
+ **Parameters:**
979
+ | Parameter | Type | Required | Description |
980
+ |-----------|------|----------|-------------|
981
+ | title | string | Yes | Goal title |
982
+ | category | string | No | Goal category |
983
+ | description | string | No | Detailed description |
984
+ | target_date | string | No | Target completion date (ISO string) |
985
+ | progress | number | No | Progress 0-100 |
986
+ | status | string | No | "active", "completed", or "paused" |
987
+
988
+ **Returns:** `Promise<{ goal: Object }>`
989
+
990
+ ### claw.recordContent(content)
991
+ Record content creation (articles, posts, documents).
992
+
993
+ **Parameters:**
994
+ | Parameter | Type | Required | Description |
995
+ |-----------|------|----------|-------------|
996
+ | title | string | Yes | Content title |
997
+ | platform | string | No | Platform (e.g., "linkedin", "twitter") |
998
+ | status | string | No | "draft" or "published" |
999
+ | url | string | No | Published URL |
1000
+
1001
+ **Returns:** `Promise<{ content: Object }>`
1002
+
1003
+ ### claw.recordInteraction(interaction)
1004
+ Record a relationship interaction (message, meeting, email).
1005
+
1006
+ **Parameters:**
1007
+ | Parameter | Type | Required | Description |
1008
+ |-----------|------|----------|-------------|
1009
+ | summary | string | Yes | What happened |
1010
+ | contact_name | string | No | Contact name (auto-resolves to contact_id) |
1011
+ | contact_id | string | No | Direct contact ID |
1012
+ | direction | string | No | "inbound" or "outbound" |
1013
+ | type | string | No | Interaction type (e.g., "message", "meeting", "email") |
1014
+ | platform | string | No | Platform used |
1015
+
1016
+ **Returns:** `Promise<{ interaction: Object }>`
1017
+
1018
+ ### claw.reportConnections(connections)
1019
+ Report active connections/integrations for this agent.
1020
+
1021
+ **Parameters:**
1022
+ | Parameter | Type | Required | Description |
1023
+ |-----------|------|----------|-------------|
1024
+ | connections | Object[] | Yes | Array of connection objects |
1025
+ | connections[].provider | string | Yes | Service name (e.g., "anthropic", "github") |
1026
+ | connections[].authType | string | No | Auth method |
1027
+ | connections[].planName | string | No | Plan name |
1028
+ | connections[].status | string | No | Connection status |
1029
+ | connections[].metadata | Object|string | No | Optional metadata |
1030
+
1031
+ **Returns:** `Promise<{ connections: Object[], created: number }>`
1032
+
1033
+ ### claw.createCalendarEvent(event)
1034
+ Create a calendar event.
1035
+
1036
+ **Parameters:**
1037
+ | Parameter | Type | Required | Description |
1038
+ |-----------|------|----------|-------------|
1039
+ | summary | string | Yes | Event title/summary |
1040
+ | start_time | string | Yes | Start time (ISO string) |
1041
+ | end_time | string | No | End time (ISO string) |
1042
+ | location | string | No | Event location |
1043
+ | description | string | No | Event description |
1044
+
1045
+ **Returns:** `Promise<{event: Object}>`
1046
+
1047
+ ### claw.recordIdea(idea)
1048
+ Record an idea or inspiration for later review.
1049
+
1050
+ **Parameters:**
1051
+ | Parameter | Type | Required | Description |
1052
+ |-----------|------|----------|-------------|
1053
+ | title | string | Yes | Idea title |
1054
+ | description | string | No | Detailed description |
1055
+ | category | string | No | Category |
1056
+ | score | number | No | Priority/quality score 0-100 |
1057
+ | status | string | No | "pending", "in_progress", "shipped", "rejected" |
1058
+ | source | string | No | Where this idea came from |
1059
+
1060
+ **Returns:** `Promise<{idea: Object}>`
1061
+
1062
+ ### claw.reportMemoryHealth(report)
1063
+ Report a memory health snapshot with entities and topics.
1064
+
1065
+ **Parameters:**
1066
+ | Parameter | Type | Required | Description |
1067
+ |-----------|------|----------|-------------|
1068
+ | health | Object | Yes | Health metrics (must include `score` 0-100) |
1069
+ | entities | Object[] | No | Key entities found in memory |
1070
+ | topics | Object[] | No | Topics/themes found in memory |
1071
+
1072
+ **Returns:** `Promise<{snapshot: Object, entities_count: number, topics_count: number}>`
1073
+
1074
+ ---
1075
+
1076
+ ## Session Handoffs
1077
+
1078
+ ### claw.createHandoff(handoff)
1079
+ Create a session handoff document summarizing work done, decisions made, and next priorities.
1080
+
1081
+ **Parameters:**
1082
+ | Parameter | Type | Required | Description |
1083
+ |-----------|------|----------|-------------|
1084
+ | summary | string | Yes | Session summary |
1085
+ | session_date | string | No | Date string (defaults to today) |
1086
+ | key_decisions | string[] | No | Key decisions made this session |
1087
+ | open_tasks | string[] | No | Tasks still open |
1088
+ | mood_notes | string | No | User mood/energy observations |
1089
+ | next_priorities | string[] | No | What to focus on next |
1090
+
1091
+ **Returns:** `Promise<{handoff: Object, handoff_id: string}>`
1092
+
1093
+ ### claw.getHandoffs(filters?)
1094
+ Get handoffs for this agent with optional date and limit filters.
1095
+
1096
+ **Parameters:**
1097
+ | Parameter | Type | Required | Description |
1098
+ |-----------|------|----------|-------------|
1099
+ | date | string | No | Filter by session_date |
1100
+ | limit | number | No | Max results |
1101
+
1102
+ **Returns:** `Promise<{handoffs: Object[], total: number}>`
1103
+
1104
+ ### claw.getLatestHandoff()
1105
+ Get the most recent handoff for this agent. Useful for resuming context at the start of a new session.
1106
+
1107
+ **Returns:** `Promise<{handoff: Object|null}>`
1108
+
1109
+ **Example:**
1110
+ ```javascript
1111
+ const { handoff } = await claw.getLatestHandoff();
1112
+ if (handoff) {
1113
+ console.log('Last session:', handoff.summary);
1114
+ console.log('Next priorities:', handoff.next_priorities);
1115
+ }
1116
+ ```
1117
+
1118
+ ---
1119
+
1120
+ ## Context Manager
1121
+
1122
+ Capture key points and organize context into threads for long-running topics.
1123
+
1124
+ ### claw.captureKeyPoint(point)
1125
+ Capture a key point from the current session for later recall.
1126
+
1127
+ **Parameters:**
1128
+ | Parameter | Type | Required | Description |
1129
+ |-----------|------|----------|-------------|
1130
+ | content | string | Yes | The key point content |
1131
+ | category | string | No | decision, task, insight, question, general |
1132
+ | importance | number | No | Importance 1-10 (default 5) |
1133
+ | session_date | string | No | Date string (defaults to today) |
1134
+
1135
+ **Returns:** `Promise<{point: Object, point_id: string}>`
1136
+
1137
+ ### claw.createThread(thread)
1138
+ Create a context thread for tracking a topic across multiple entries.
1139
+
1140
+ **Parameters:**
1141
+ | Parameter | Type | Required | Description |
1142
+ |-----------|------|----------|-------------|
1143
+ | name | string | Yes | Thread name (unique per agent per org) |
1144
+ | summary | string | No | Initial summary |
1145
+
1146
+ **Returns:** `Promise<{thread: Object, thread_id: string}>`
1147
+
1148
+ ### claw.getKeyPoints(filters?)
1149
+ Get key points with optional filters.
1150
+
1151
+ **Parameters:**
1152
+ | Parameter | Type | Required | Description |
1153
+ |-----------|------|----------|-------------|
1154
+ | category | string | No | Filter by category: decision, task, insight, question, general |
1155
+ | session_date | string | No | Filter by date (YYYY-MM-DD) |
1156
+ | limit | number | No | Max results |
1157
+
1158
+ **Returns:** `Promise<{points: Object[], total: number}>`
1159
+
1160
+ ### claw.addThreadEntry(threadId, content, entryType?)
1161
+ Add an entry to an existing thread.
1162
+
1163
+ **Parameters:**
1164
+ | Parameter | Type | Required | Description |
1165
+ |-----------|------|----------|-------------|
1166
+ | threadId | string | Yes | The thread ID |
1167
+ | content | string | Yes | Entry content |
1168
+ | entryType | string | No | Entry type (default: "note") |
1169
+
1170
+ **Returns:** `Promise<{entry: Object, entry_id: string}>`
1171
+
1172
+ ### claw.closeThread(threadId, summary?)
1173
+ Close a context thread with an optional final summary.
1174
+
1175
+ **Parameters:**
1176
+ | Parameter | Type | Required | Description |
1177
+ |-----------|------|----------|-------------|
1178
+ | threadId | string | Yes | The thread ID to close |
1179
+ | summary | string | No | Final summary for the thread |
1180
+
1181
+ **Returns:** `Promise<{thread: Object}>`
1182
+
1183
+ ### claw.getThreads(filters?)
1184
+ Get context threads with optional filters.
1185
+
1186
+ **Parameters:**
1187
+ | Parameter | Type | Required | Description |
1188
+ |-----------|------|----------|-------------|
1189
+ | status | string | No | Filter by status: active, closed |
1190
+ | limit | number | No | Max results |
1191
+
1192
+ **Returns:** `Promise<{threads: Object[], total: number}>`
1193
+
1194
+ ### claw.getContextSummary()
1195
+ Get a combined context summary containing today's key points and all active threads. Convenience method that calls `getKeyPoints()` and `getThreads()` in parallel.
1196
+
1197
+ **Returns:** `Promise<{points: Object[], threads: Object[]}>`
1198
+
1199
+ **Example:**
1200
+ ```javascript
1201
+ const { points, threads } = await claw.getContextSummary();
1202
+ console.log(`${points.length} key points today, ${threads.length} active threads`);
1203
+ ```
1204
+
1205
+ ---
1206
+
1207
+ ## Automation Snippets
1208
+
1209
+ Save, search, and reuse code snippets across agent sessions.
1210
+
1211
+ ### claw.saveSnippet(snippet)
1212
+ Save or update a reusable code snippet. Upserts on name.
1213
+
1214
+ **Parameters:**
1215
+ | Parameter | Type | Required | Description |
1216
+ |-----------|------|----------|-------------|
1217
+ | name | string | Yes | Snippet name (unique per org) |
1218
+ | code | string | Yes | The snippet code |
1219
+ | description | string | No | What this snippet does |
1220
+ | language | string | No | Programming language |
1221
+ | tags | string[] | No | Tags for categorization |
1222
+
1223
+ **Returns:** `Promise<{snippet: Object, snippet_id: string}>`
1224
+
1225
+ **Example:**
1226
+ ```javascript
1227
+ await claw.saveSnippet({
1228
+ name: 'fetch-with-retry',
1229
+ code: 'async function fetchRetry(url, n = 3) { ... }',
1230
+ language: 'javascript',
1231
+ tags: ['fetch', 'retry'],
1232
+ });
1233
+ ```
1234
+
1235
+ ### claw.getSnippet(snippetId)
1236
+ Fetch a single snippet by ID.
1237
+
1238
+ **Parameters:**
1239
+ | Parameter | Type | Required | Description |
1240
+ |-----------|------|----------|-------------|
1241
+ | snippetId | string | Yes | The snippet ID |
1242
+
1243
+ **Returns:** `Promise<{snippet: Object}>`
1244
+
1245
+ **Example:**
1246
+ ```javascript
1247
+ const { snippet } = await claw.getSnippet('sn_abc123');
1248
+ console.log(snippet.name, snippet.language);
1249
+ ```
1250
+
1251
+ ### claw.getSnippets(filters?)
1252
+ Search and list snippets.
1253
+
1254
+ **Parameters:**
1255
+ | Parameter | Type | Required | Description |
1256
+ |-----------|------|----------|-------------|
1257
+ | search | string | No | Search name/description |
1258
+ | tag | string | No | Filter by tag |
1259
+ | language | string | No | Filter by language |
1260
+ | limit | number | No | Max results |
1261
+
1262
+ **Returns:** `Promise<{snippets: Object[], total: number}>`
1263
+
1264
+ **Example:**
1265
+ ```javascript
1266
+ const { snippets } = await claw.getSnippets({ language: 'javascript' });
1267
+ ```
1268
+
1269
+ ### claw.useSnippet(snippetId)
1270
+ Mark a snippet as used (increments use_count).
1271
+
1272
+ **Parameters:**
1273
+ | Parameter | Type | Required | Description |
1274
+ |-----------|------|----------|-------------|
1275
+ | snippetId | string | Yes | Snippet ID |
1276
+
1277
+ **Returns:** `Promise<{snippet: Object}>`
1278
+
1279
+ **Example:**
1280
+ ```javascript
1281
+ await claw.useSnippet('sn_abc123');
1282
+ ```
1283
+
1284
+ ### claw.deleteSnippet(snippetId)
1285
+ Delete a snippet.
1286
+
1287
+ **Parameters:**
1288
+ | Parameter | Type | Required | Description |
1289
+ |-----------|------|----------|-------------|
1290
+ | snippetId | string | Yes | Snippet ID |
1291
+
1292
+ **Returns:** `Promise<{deleted: boolean, id: string}>`
1293
+
1294
+ **Example:**
1295
+ ```javascript
1296
+ await claw.deleteSnippet('sn_abc123');
1297
+ ```
1298
+
1299
+ ---
1300
+
1301
+ ## User Preferences
1302
+
1303
+ Track user observations, learned preferences, mood/energy, and approach effectiveness across sessions.
1304
+
1305
+ ### claw.logObservation(obs)
1306
+ Log a user observation (what you noticed about the user's behavior or preferences).
1307
+
1308
+ **Parameters:**
1309
+ | Parameter | Type | Required | Description |
1310
+ |-----------|------|----------|-------------|
1311
+ | observation | string | Yes | The observation text |
1312
+ | category | string | No | Category tag |
1313
+ | importance | number | No | Importance 1-10 |
1314
+
1315
+ **Returns:** `Promise<{observation: Object, observation_id: string}>`
1316
+
1317
+ **Example:**
1318
+ ```javascript
1319
+ await claw.logObservation({
1320
+ observation: 'User prefers concise responses over detailed explanations',
1321
+ category: 'communication',
1322
+ importance: 8,
1323
+ });
1324
+ ```
1325
+
1326
+ ### claw.setPreference(pref)
1327
+ Set a learned user preference. Use this to record patterns you detect about how the user likes to work.
1328
+
1329
+ **Parameters:**
1330
+ | Parameter | Type | Required | Description |
1331
+ |-----------|------|----------|-------------|
1332
+ | preference | string | Yes | The preference description |
1333
+ | category | string | No | Category tag |
1334
+ | confidence | number | No | Confidence 0-100 |
1335
+
1336
+ **Returns:** `Promise<{preference: Object, preference_id: string}>`
1337
+
1338
+ ### claw.logMood(entry)
1339
+ Log user mood/energy for a session. Helps track patterns in productivity and satisfaction.
1340
+
1341
+ **Parameters:**
1342
+ | Parameter | Type | Required | Description |
1343
+ |-----------|------|----------|-------------|
1344
+ | mood | string | Yes | Mood description (e.g., "focused", "frustrated") |
1345
+ | energy | string | No | Energy level (e.g., "high", "low") |
1346
+ | notes | string | No | Additional notes |
1347
+
1348
+ **Returns:** `Promise<{mood: Object, mood_id: string}>`
1349
+
1350
+ ### claw.trackApproach(entry)
1351
+ Track an approach and whether it succeeded or failed. Builds a knowledge base of what works.
1352
+
1353
+ **Parameters:**
1354
+ | Parameter | Type | Required | Description |
1355
+ |-----------|------|----------|-------------|
1356
+ | approach | string | Yes | The approach description |
1357
+ | context | string | No | Context for when to use this approach |
1358
+ | success | boolean | No | true = worked, false = failed, undefined = just recording |
1359
+
1360
+ **Returns:** `Promise<{approach: Object, approach_id: string}>`
1361
+
1362
+ ### claw.getPreferenceSummary()
1363
+ Get a summary of all user preference data including observations, preferences, moods, and approaches.
1364
+
1365
+ **Returns:** `Promise<{summary: Object}>`
1366
+
1367
+ ### claw.getApproaches(filters?)
1368
+ Get tracked approaches with success/fail counts.
1369
+
1370
+ **Parameters:**
1371
+ | Parameter | Type | Required | Description |
1372
+ |-----------|------|----------|-------------|
1373
+ | limit | number | No | Max results |
1374
+
1375
+ **Returns:** `Promise<{approaches: Object[], total: number}>`
1376
+
1377
+ ---
1378
+
1379
+ ## Daily Digest
1380
+
1381
+ ### claw.getDailyDigest(date?)
1382
+ Get a daily activity digest aggregated from all data sources (actions, decisions, handoffs, context, etc.).
1383
+
1384
+ **Parameters:**
1385
+ | Parameter | Type | Required | Description |
1386
+ |-----------|------|----------|-------------|
1387
+ | date | string | No | Date string YYYY-MM-DD (defaults to today) |
1388
+
1389
+ **Returns:** `Promise<{date: string, digest: Object, summary: Object}>`
1390
+
1391
+ **Example:**
1392
+ ```javascript
1393
+ const { digest, summary } = await claw.getDailyDigest('2025-01-15');
1394
+ console.log(`Actions: ${summary.actions_count}, Decisions: ${summary.decisions_count}`);
1395
+ ```
1396
+
1397
+ ---
1398
+
1399
+ ## Security Scanning
1400
+
1401
+ Scan text for sensitive data before sending it anywhere. The scanner detects API keys, tokens, PII, and other secrets.
1402
+
1403
+ ### claw.scanContent(text, destination?)
1404
+ Scan text for sensitive data. Returns findings and redacted text. Does NOT store the original content.
1405
+
1406
+ **Parameters:**
1407
+ | Parameter | Type | Required | Description |
1408
+ |-----------|------|----------|-------------|
1409
+ | text | string | Yes | Text to scan |
1410
+ | destination | string | No | Where this text is headed (for context) |
1411
+
1412
+ **Returns:** `Promise<{clean: boolean, findings_count: number, findings: Object[], redacted_text: string}>`
1413
+
1414
+ **Example:**
1415
+ ```javascript
1416
+ const result = await claw.scanContent(
1417
+ 'Deploy with key sk-abc123xyz to production',
1418
+ 'slack'
1419
+ );
1420
+ if (!result.clean) {
1421
+ console.log(`Found ${result.findings_count} issues`);
1422
+ console.log('Safe version:', result.redacted_text);
1423
+ }
1424
+ ```
1425
+
1426
+ ### claw.reportSecurityFinding(text, destination?)
1427
+ Scan text and store finding metadata for audit trails. The original content is never stored, only the finding metadata.
1428
+
1429
+ **Parameters:**
1430
+ | Parameter | Type | Required | Description |
1431
+ |-----------|------|----------|-------------|
1432
+ | text | string | Yes | Text to scan |
1433
+ | destination | string | No | Where this text is headed |
1434
+
1435
+ **Returns:** `Promise<{clean: boolean, findings_count: number, findings: Object[], redacted_text: string}>`
1436
+
1437
+ ### claw.scanPromptInjection(text, options?)
1438
+ Scan text for prompt injection attacks — role overrides, delimiter injection, instruction smuggling, data exfiltration attempts, and encoding evasion. Returns risk level and actionable recommendation.
1439
+
1440
+ **Parameters:**
1441
+ | Parameter | Type | Required | Description |
1442
+ |-----------|------|----------|-------------|
1443
+ | text | string | Yes | Text to scan for injection attacks |
1444
+ | options.source | string | No | Where this text came from (e.g. user_input, tool_output, retrieval) |
1445
+
1446
+ **Returns:** `Promise<{clean: boolean, risk_level: string, recommendation: string, findings_count: number, critical_count: number, categories: string[], findings: Object[]}>`
1447
+
1448
+ **Example:**
1449
+ ```javascript
1450
+ const result = await claw.scanPromptInjection(userMessage, { source: 'user_input' });
1451
+ if (result.recommendation === 'block') {
1452
+ console.error(`Blocked: ${result.findings_count} injection patterns detected`);
1453
+ } else if (result.recommendation === 'warn') {
1454
+ console.warn(`Warning: ${result.categories.join(', ')} detected`);
1455
+ }
1456
+ ```
1457
+
1458
+ ---
1459
+
1460
+ ## Agent Messaging
1461
+
1462
+ ### claw.sendMessage(params)
1463
+ Send a message to another agent or broadcast.
1464
+
1465
+ **Parameters:**
1466
+ | Parameter | Type | Required | Description |
1467
+ |-----------|------|----------|-------------|
1468
+ | to | string | No | Target agent ID (null = broadcast) |
1469
+ | type | string | No | info, action, lesson, question, status |
1470
+ | subject | string | No | Subject line (max 200 chars) |
1471
+ | body | string | Yes | Message body (max 2000 chars) |
1472
+ | threadId | string | No | Thread ID to attach to |
1473
+ | urgent | boolean | No | Mark as urgent |
1474
+ | docRef | string | No | Reference to a shared doc ID |
1475
+ | attachments | Array<{filename, mime_type, data}> | No | File attachments (base64, max 3, max 5MB each) |
1476
+
1477
+ **Returns:** `Promise<{message: Object, message_id: string}>`
1478
+
1479
+ ### claw.getInbox(params?)
1480
+ Get inbox messages for this agent.
1481
+
1482
+ **Parameters:**
1483
+ | Parameter | Type | Required | Description |
1484
+ |-----------|------|----------|-------------|
1485
+ | type | string | No | Filter by message type |
1486
+ | unread | boolean | No | Only unread messages |
1487
+ | threadId | string | No | Filter by thread |
1488
+ | limit | number | No | Max messages to return (default: 50) |
1489
+
1490
+ **Returns:** `Promise<{messages: Object[], total: number, unread_count: number}>`
1491
+
1492
+ ### claw.getSentMessages(params?)
1493
+ Get messages sent by this agent.
1494
+
1495
+ **Parameters:**
1496
+ | Parameter | Type | Required | Description |
1497
+ |-----------|------|----------|-------------|
1498
+ | type | string | No | Filter by message type |
1499
+ | threadId | string | No | Filter by thread |
1500
+ | limit | number | No | Max messages to return (default: 50) |
1501
+
1502
+ **Returns:** `Promise<{messages: Object[], total: number}>`
1503
+
1504
+ ### claw.getMessages(params?)
1505
+ Flexible message query supporting inbox, sent, or all directions.
1506
+
1507
+ **Parameters:**
1508
+ | Parameter | Type | Required | Description |
1509
+ |-----------|------|----------|-------------|
1510
+ | direction | string | No | 'inbox' (default), 'sent', or 'all' |
1511
+ | type | string | No | Filter by message type |
1512
+ | unread | boolean | No | Only unread messages (inbox direction only) |
1513
+ | threadId | string | No | Filter by thread |
1514
+ | limit | number | No | Max messages to return (default: 50) |
1515
+
1516
+ **Returns:** `Promise<{messages: Object[], total: number, unread_count: number}>`
1517
+
1518
+ ### claw.getMessage(messageId)
1519
+ Fetch a single message by ID.
1520
+
1521
+ **Parameters:**
1522
+ | Parameter | Type | Required | Description |
1523
+ |-----------|------|----------|-------------|
1524
+ | messageId | string | Yes | Message ID |
1525
+
1526
+ **Returns:** `Promise<{message: Object}>`
1527
+
1528
+ ### claw.markRead(messageIds)
1529
+ Mark messages as read.
1530
+
1531
+ **Parameters:**
1532
+ | Parameter | Type | Required | Description |
1533
+ |-----------|------|----------|-------------|
1534
+ | messageIds | string[] | Yes | Array of message IDs to mark read |
1535
+
1536
+ **Returns:** `Promise<{updated: number}>`
1537
+
1538
+ ### claw.archiveMessages(messageIds)
1539
+ Archive messages.
1540
+
1541
+ **Parameters:**
1542
+ | Parameter | Type | Required | Description |
1543
+ |-----------|------|----------|-------------|
1544
+ | messageIds | string[] | Yes | Array of message IDs to archive |
1545
+
1546
+ **Returns:** `Promise<{updated: number}>`
1547
+
1548
+ ### claw.broadcast(params)
1549
+ Broadcast a message to all agents in the organization.
1550
+
1551
+ **Parameters:**
1552
+ | Parameter | Type | Required | Description |
1553
+ |-----------|------|----------|-------------|
1554
+ | type | string | No | Message type (default: "info") |
1555
+ | subject | string | No | Subject line |
1556
+ | body | string | Yes | Message body |
1557
+ | threadId | string | No | Thread ID |
1558
+
1559
+ **Returns:** `Promise<{message: Object, message_id: string}>`
1560
+
1561
+ ### claw.createMessageThread(params)
1562
+ Create a new message thread for multi-turn conversations between agents.
1563
+
1564
+ **Parameters:**
1565
+ | Parameter | Type | Required | Description |
1566
+ |-----------|------|----------|-------------|
1567
+ | name | string | Yes | Thread name |
1568
+ | participants | string[] | No | Agent IDs (null = open to all) |
1569
+
1570
+ **Returns:** `Promise<{thread: Object, thread_id: string}>`
1571
+
1572
+ ### claw.getMessageThreads(params?)
1573
+ List message threads.
1574
+
1575
+ **Parameters:**
1576
+ | Parameter | Type | Required | Description |
1577
+ |-----------|------|----------|-------------|
1578
+ | status | string | No | Filter by status: open, resolved, archived |
1579
+ | limit | number | No | Max threads to return (default: 20) |
1580
+
1581
+ **Returns:** `Promise<{threads: Object[], total: number}>`
1582
+
1583
+ ### claw.resolveMessageThread(threadId, summary?)
1584
+ Resolve (close) a message thread with an optional summary.
1585
+
1586
+ **Parameters:**
1587
+ | Parameter | Type | Required | Description |
1588
+ |-----------|------|----------|-------------|
1589
+ | threadId | string | Yes | Thread ID to resolve |
1590
+ | summary | string | No | Resolution summary |
1591
+
1592
+ **Returns:** `Promise<{thread: Object}>`
1593
+
1594
+ ### claw.saveSharedDoc(params)
1595
+ Create or update a shared workspace document. Upserts by name.
1596
+
1597
+ **Parameters:**
1598
+ | Parameter | Type | Required | Description |
1599
+ |-----------|------|----------|-------------|
1600
+ | name | string | Yes | Document name (unique per org) |
1601
+ | content | string | Yes | Document content |
1602
+
1603
+ **Returns:** `Promise<{doc: Object, doc_id: string}>`
1604
+
1605
+ ### claw.getAttachmentUrl(attachmentId)
1606
+
1607
+ Get a URL to download an attachment.
1608
+
1609
+ | Parameter | Type | Description |
1610
+ |---|---|---|
1611
+ | `attachmentId` | `string` | Attachment ID (`att_*`) |
1612
+
1613
+ **Returns:** `string`: URL to fetch the attachment binary
1614
+
1615
+ ---
1616
+
1617
+ ### claw.getAttachment(attachmentId)
1618
+
1619
+ Download an attachment as a Buffer.
1620
+
1621
+ | Parameter | Type | Description |
1622
+ |---|---|---|
1623
+ | `attachmentId` | `string` | Attachment ID (`att_*`) |
1624
+
1625
+ **Returns:** `Promise<{ data: Buffer, filename: string, mimeType: string }>`
1626
+
1627
+ ```js
1628
+ const inbox = await claw.getInbox();
1629
+ for (const msg of inbox.messages) {
1630
+ for (const att of msg.attachments || []) {
1631
+ const { data, filename } = await claw.getAttachment(att.id);
1632
+ fs.writeFileSync(filename, data);
1633
+ }
1634
+ }
1635
+ ```
1636
+
1637
+ ---
1638
+
1639
+ ## Agent Pairing
1640
+
1641
+ Pair agents with user accounts via public key registration and approval flow.
1642
+
1643
+ ### claw.createPairing(options)
1644
+ Create an agent pairing request. Returns a link the user can click to approve the pairing.
1645
+
1646
+ **Parameters:**
1647
+ | Parameter | Type | Required | Description |
1648
+ |-----------|------|----------|-------------|
1649
+ | publicKeyPem | string | Yes | PEM public key (SPKI format) to register for this agent |
1650
+ | algorithm | string | No | Signing algorithm (default: "RSASSA-PKCS1-v1_5") |
1651
+ | agentName | string | No | Agent name override |
1652
+
1653
+ **Returns:** `Promise<{pairing: Object, pairing_url: string}>`
1654
+
1655
+ ### claw.getPairing(pairingId)
1656
+ Fetch a pairing request by ID.
1657
+
1658
+ **Parameters:**
1659
+ | Parameter | Type | Required | Description |
1660
+ |-----------|------|----------|-------------|
1661
+ | pairingId | string | Yes | Pairing ID |
1662
+
1663
+ **Returns:** `Promise<{pairing: Object}>`
1664
+
1665
+ ### claw.createPairingFromPrivateJwk(privateJwk, options?)
1666
+ Convenience method that derives the public PEM from a private JWK and creates a pairing request.
1667
+
1668
+ **Parameters:**
1669
+ | Parameter | Type | Required | Description |
1670
+ |-----------|------|----------|-------------|
1671
+ | privateJwk | Object | Yes | Private key in JWK format |
1672
+ | options.agentName | string | No | Agent name override |
1673
+
1674
+ **Returns:** `Promise<{pairing: Object, pairing_url: string}>`
1675
+
1676
+ ### claw.approveAction(actionId, decision, reasoning?)
1677
+ Approve or deny a pending action as a human operator.
1678
+
1679
+ **Parameters:**
1680
+ | Parameter | Type | Required | Description |
1681
+ |-----------|------|----------|-------------|
1682
+ | actionId | string | Yes | Action ID to approve or deny |
1683
+ | decision | string | Yes | 'allow' or 'deny' |
1684
+ | reasoning | string | No | Optional explanation for the decision |
1685
+
1686
+ **Returns:** `Promise<{action: Object}>`
1687
+
1688
+ ### claw.getPendingApprovals(params?)
1689
+ Get all actions currently waiting for human approval.
1690
+
1691
+ **Parameters:**
1692
+ | Parameter | Type | Required | Description |
1693
+ |-----------|------|----------|-------------|
1694
+ | limit | number | No | Max results (default: 20) |
1695
+ | offset | number | No | Pagination offset |
1696
+
1697
+ **Returns:** `Promise<{actions: Object[], total: number}>`
1698
+
1699
+ ### claw.waitForPairing(pairingId, options?)
1700
+ Poll a pairing request until it is approved or expired.
1701
+
1702
+ **Parameters:**
1703
+ | Parameter | Type | Required | Description |
1704
+ |-----------|------|----------|-------------|
1705
+ | pairingId | string | Yes | The pairing ID to poll |
1706
+ | options.timeout | number | No | Max wait time in ms (default: 300000 / 5 min) |
1707
+ | options.interval | number | No | Poll interval in ms (default: 2000) |
1708
+
1709
+ **Returns:** `Promise<Object>` (the approved pairing object)
1710
+
1711
+ **Throws:** `Error` if pairing expires or times out.
1712
+
1713
+ **Example:**
1714
+ ```javascript
1715
+ const { pairing, pairing_url } = await claw.createPairing({
1716
+ publicKeyPem: myPublicKeyPem,
1717
+ });
1718
+ console.log('Approve pairing at:', pairing_url);
1719
+
1720
+ const approved = await claw.waitForPairing(pairing.id);
1721
+ console.log('Pairing approved!', approved.status);
1722
+ ```
1723
+
1724
+ ---
1725
+
1726
+ ## Identity Binding
1727
+
1728
+ Register and manage agent public keys for cryptographic identity verification.
1729
+
1730
+ ### claw.registerIdentity(identity)
1731
+ Register or update an agent's public key for identity verification. Requires admin API key.
1732
+
1733
+ **Parameters:**
1734
+ | Parameter | Type | Required | Description |
1735
+ |-----------|------|----------|-------------|
1736
+ | agent_id | string | Yes | Agent ID to register |
1737
+ | public_key | string | Yes | PEM public key (SPKI format) |
1738
+ | algorithm | string | No | Signing algorithm (default: "RSASSA-PKCS1-v1_5") |
1739
+
1740
+ **Returns:** `Promise<{identity: Object}>`
1741
+
1742
+ ### claw.getIdentities()
1743
+ List all registered agent identities for this organization.
1744
+
1745
+ **Returns:** `Promise<{identities: Object[]}>`
1746
+
1747
+ ---
1748
+
1749
+ ## Organization Management
1750
+
1751
+ Manage organizations and API keys. All methods require admin API key.
1752
+
1753
+ ### claw.getOrg()
1754
+ Get the current organization's details.
1755
+
1756
+ **Returns:** `Promise<{organizations: Object[]}>`
1757
+
1758
+ ### claw.createOrg(org)
1759
+ Create a new organization with an initial admin API key.
1760
+
1761
+ **Parameters:**
1762
+ | Parameter | Type | Required | Description |
1763
+ |-----------|------|----------|-------------|
1764
+ | name | string | Yes | Organization name |
1765
+ | slug | string | Yes | URL-safe slug (lowercase alphanumeric + hyphens) |
1766
+
1767
+ **Returns:** `Promise<{organization: Object, api_key: Object}>`
1768
+
1769
+ ### claw.getOrgById(orgId)
1770
+ Get organization details by ID.
1771
+
1772
+ **Parameters:**
1773
+ | Parameter | Type | Required | Description |
1774
+ |-----------|------|----------|-------------|
1775
+ | orgId | string | Yes | Organization ID |
1776
+
1777
+ **Returns:** `Promise<{organization: Object}>`
1778
+
1779
+ ### claw.updateOrg(orgId, updates)
1780
+ Update organization details.
1781
+
1782
+ **Parameters:**
1783
+ | Parameter | Type | Required | Description |
1784
+ |-----------|------|----------|-------------|
1785
+ | orgId | string | Yes | Organization ID |
1786
+ | updates | Object | Yes | Fields to update (name, slug) |
1787
+
1788
+ **Returns:** `Promise<{organization: Object}>`
1789
+
1790
+ ### claw.getOrgKeys(orgId)
1791
+ List API keys for an organization.
1792
+
1793
+ **Parameters:**
1794
+ | Parameter | Type | Required | Description |
1795
+ |-----------|------|----------|-------------|
1796
+ | orgId | string | Yes | Organization ID |
1797
+
1798
+ **Returns:** `Promise<{keys: Object[]}>`
1799
+
1800
+ ---
1801
+
1802
+ ## Activity Logs
1803
+
1804
+ ### claw.getActivityLogs(filters?)
1805
+ Get activity/audit logs for the organization.
1806
+
1807
+ **Parameters:**
1808
+ | Parameter | Type | Required | Description |
1809
+ |-----------|------|----------|-------------|
1810
+ | action | string | No | Filter by action type |
1811
+ | actor_id | string | No | Filter by actor |
1812
+ | resource_type | string | No | Filter by resource type |
1813
+ | before | string | No | Before timestamp (ISO string) |
1814
+ | after | string | No | After timestamp (ISO string) |
1815
+ | limit | number | No | Max results (default: 50, max: 200) |
1816
+ | offset | number | No | Pagination offset |
1817
+
1818
+ **Returns:** `Promise<{logs: Object[], stats: Object, pagination: Object}>`
1819
+
1820
+ ---
1821
+
1822
+ ## Webhooks
1823
+
1824
+ Subscribe to DashClaw events and receive real-time notifications.
1825
+
1826
+ ### claw.getWebhooks()
1827
+ List all webhooks for this organization.
1828
+
1829
+ **Returns:** `Promise<{webhooks: Object[]}>`
1830
+
1831
+ ### claw.createWebhook(webhook)
1832
+ Create a new webhook subscription.
1833
+
1834
+ **Parameters:**
1835
+ | Parameter | Type | Required | Description |
1836
+ |-----------|------|----------|-------------|
1837
+ | url | string | Yes | Webhook endpoint URL |
1838
+ | events | string[] | No | Event types to subscribe to |
1839
+
1840
+ **Returns:** `Promise<{webhook: Object}>`
1841
+
1842
+ ### claw.deleteWebhook(webhookId)
1843
+ Delete a webhook.
1844
+
1845
+ **Parameters:**
1846
+ | Parameter | Type | Required | Description |
1847
+ |-----------|------|----------|-------------|
1848
+ | webhookId | string | Yes | Webhook ID |
1849
+
1850
+ **Returns:** `Promise<{deleted: boolean}>`
1851
+
1852
+ ### claw.testWebhook(webhookId)
1853
+ Send a test event to a webhook to verify connectivity.
1854
+
1855
+ **Parameters:**
1856
+ | Parameter | Type | Required | Description |
1857
+ |-----------|------|----------|-------------|
1858
+ | webhookId | string | Yes | Webhook ID |
1859
+
1860
+ **Returns:** `Promise<{delivery: Object}>`
1861
+
1862
+ ### claw.getWebhookDeliveries(webhookId)
1863
+ Get delivery history for a webhook.
1864
+
1865
+ **Parameters:**
1866
+ | Parameter | Type | Required | Description |
1867
+ |-----------|------|----------|-------------|
1868
+ | webhookId | string | Yes | Webhook ID |
1869
+
1870
+ **Returns:** `Promise<{deliveries: Object[]}>`
1871
+
1872
+ ---
1873
+
1874
+ ## Bulk Sync
1875
+
1876
+ ### claw.syncState(state)
1877
+ Push multiple data categories in a single request. Accepts connections, memory, goals, learning, content, inspiration, context_points, context_threads, handoffs, preferences, and snippets.
1878
+
1879
+ **Returns:** `Promise<{results: Object, total_synced: number, total_errors: number, duration_ms: number}>`
1880
+
1881
+ ---
1882
+
1883
+ ## Policy Testing
1884
+
1885
+ Run guardrails tests, generate compliance proof reports, and import policy packs.
1886
+
1887
+ ### claw.testPolicies()
1888
+ Run guardrails tests against all active policies. Returns pass/fail results per policy.
1889
+
1890
+ **Returns:** `Promise<{ results: Object[], total: number, passed: number, failed: number }>`
1891
+
1892
+ **Example:**
1893
+ ```javascript
1894
+ const report = await claw.testPolicies();
1895
+ console.log(`${report.passed}/${report.total} policies passed`);
1896
+ for (const r of report.results.filter(r => !r.passed)) {
1897
+ console.log(`FAIL: ${r.policy}: ${r.reason}`);
1898
+ }
1899
+ ```
1900
+
1901
+ ### claw.getProofReport(options?)
1902
+ Generate a compliance proof report summarizing guard decisions, policy evaluations, and audit evidence.
1903
+
1904
+ **Parameters:**
1905
+ | Parameter | Type | Required | Description |
1906
+ |-----------|------|----------|-------------|
1907
+ | format | string | No | Output format: "json" (default) or "md" |
1908
+
1909
+ **Returns:** `Promise<{ report: Object|string }>`
1910
+
1911
+ ### claw.importPolicies({ pack?, yaml? })
1912
+ Import a policy pack or raw YAML. Admin only. Replaces or merges into active policies.
1913
+
1914
+ **Parameters:**
1915
+ | Parameter | Type | Required | Description |
1916
+ |-----------|------|----------|-------------|
1917
+ | pack | string | No | Named policy pack: enterprise-strict, smb-safe, startup-growth, development |
1918
+ | yaml | string | No | Raw YAML policy definition |
1919
+
1920
+ **Returns:** `Promise<{ imported: number, policies: Object[] }>`
1921
+
1922
+ ---
1923
+
1924
+ ## Compliance Engine
1925
+
1926
+ Map policies to regulatory frameworks, run gap analysis, and generate compliance reports.
1927
+
1928
+ ### claw.mapCompliance(framework)
1929
+ Map active policies to framework controls. Returns a control-by-control coverage matrix.
1930
+
1931
+ **Parameters:**
1932
+ | Parameter | Type | Required | Description |
1933
+ |-----------|------|----------|-------------|
1934
+ | framework | string | Yes | Target framework: soc2, iso27001, gdpr, nist-ai-rmf, imda-agentic |
1935
+
1936
+ **Returns:** `Promise<{ framework: string, controls: Object[], coverage_pct: number }>`
1937
+
1938
+ **Example:**
1939
+ ```javascript
1940
+ const { controls, coverage_pct } = await claw.mapCompliance('soc2');
1941
+ console.log(`SOC 2 coverage: ${coverage_pct}%`);
1942
+ for (const ctrl of controls.filter(c => !c.covered)) {
1943
+ console.log(`Gap: ${ctrl.id}: ${ctrl.name}`);
1944
+ }
1945
+ ```
1946
+
1947
+ ### claw.analyzeGaps(framework)
1948
+ Run gap analysis with remediation plan. Identifies missing controls and suggests policy changes.
1949
+
1950
+ **Parameters:**
1951
+ | Parameter | Type | Required | Description |
1952
+ |-----------|------|----------|-------------|
1953
+ | framework | string | Yes | Target framework: soc2, iso27001, gdpr, nist-ai-rmf, imda-agentic |
1954
+
1955
+ **Returns:** `Promise<{ framework: string, gaps: Object[], remediation_plan: Object[] }>`
1956
+
1957
+ ### claw.getComplianceReport(framework, options?)
1958
+ Generate a full compliance report and save a point-in-time snapshot.
1959
+
1960
+ **Parameters:**
1961
+ | Parameter | Type | Required | Description |
1962
+ |-----------|------|----------|-------------|
1963
+ | framework | string | Yes | Target framework |
1964
+ | options.format | string | No | Output format: "json" (default) or "md" |
1965
+
1966
+ **Returns:** `Promise<{ report: Object|string, snapshot_id: string }>`
1967
+
1968
+ ### claw.listFrameworks()
1969
+ List all available compliance frameworks with metadata.
1970
+
1971
+ **Returns:** `Promise<{ frameworks: Object[] }>`
1972
+
1973
+ ### claw.getComplianceEvidence(options?)
1974
+ Get live guard decision evidence for compliance audits. Returns timestamped decision records.
1975
+
1976
+ **Parameters:**
1977
+ | Parameter | Type | Required | Description |
1978
+ |-----------|------|----------|-------------|
1979
+ | options.window | string | No | Time window: "7d" (default), "30d", "90d" |
1980
+
1981
+ **Returns:** `Promise<{ evidence: Object[], window: string, total: number }>`
1982
+
1983
+ ---
1984
+
1985
+ ## Task Routing
1986
+
1987
+ Route tasks to agents based on capabilities, availability, and workload. Manage the agent pool and monitor routing health.
1988
+
1989
+ ### claw.listRoutingAgents(filters?)
1990
+ List registered routing agents with optional status filter.
1991
+
1992
+ **Parameters:**
1993
+ | Parameter | Type | Required | Description |
1994
+ |-----------|------|----------|-------------|
1995
+ | filters.status | string | No | Filter by status: available, busy, offline |
1996
+
1997
+ **Returns:** `Promise<{ agents: Object[], total: number }>`
1998
+
1999
+ ### claw.registerRoutingAgent(agent)
2000
+ Register a new agent in the routing pool.
2001
+
2002
+ **Parameters:**
2003
+ | Parameter | Type | Required | Description |
2004
+ |-----------|------|----------|-------------|
2005
+ | name | string | Yes | Agent display name |
2006
+ | capabilities | string[] | No | List of skills/capabilities |
2007
+ | maxConcurrent | number | No | Max concurrent tasks (default: 1) |
2008
+ | endpoint | string | No | Agent callback endpoint URL |
2009
+
2010
+ **Returns:** `Promise<{ agent: Object, agent_id: string }>`
2011
+
2012
+ ### claw.getRoutingAgent(agentId)
2013
+ Get a single routing agent with current metrics.
2014
+
2015
+ **Parameters:**
2016
+ | Parameter | Type | Required | Description |
2017
+ |-----------|------|----------|-------------|
2018
+ | agentId | string | Yes | The routing agent ID |
2019
+
2020
+ **Returns:** `Promise<{ agent: Object, metrics: Object }>`
2021
+
2022
+ ### claw.updateRoutingAgentStatus(agentId, status)
2023
+ Update a routing agent's availability status.
2024
+
2025
+ **Parameters:**
2026
+ | Parameter | Type | Required | Description |
2027
+ |-----------|------|----------|-------------|
2028
+ | agentId | string | Yes | The routing agent ID |
2029
+ | status | string | Yes | New status: available, busy, offline |
2030
+
2031
+ **Returns:** `Promise<{ agent: Object }>`
2032
+
2033
+ ### claw.deleteRoutingAgent(agentId)
2034
+ Remove an agent from the routing pool.
2035
+
2036
+ **Parameters:**
2037
+ | Parameter | Type | Required | Description |
2038
+ |-----------|------|----------|-------------|
2039
+ | agentId | string | Yes | The routing agent ID |
2040
+
2041
+ **Returns:** `Promise<{ deleted: boolean, id: string }>`
2042
+
2043
+ ### claw.listRoutingTasks(filters?)
2044
+ List routing tasks with optional filters.
2045
+
2046
+ **Parameters:**
2047
+ | Parameter | Type | Required | Description |
2048
+ |-----------|------|----------|-------------|
2049
+ | filters.status | string | No | Filter by status: pending, assigned, completed, failed |
2050
+ | filters.agent_id | string | No | Filter by assigned agent |
2051
+ | filters.limit | number | No | Max results (default: 50) |
2052
+ | filters.offset | number | No | Pagination offset |
2053
+
2054
+ **Returns:** `Promise<{ tasks: Object[], total: number }>`
2055
+
2056
+ ### claw.submitRoutingTask(task)
2057
+ Submit a task for automatic routing to the best available agent.
2058
+
2059
+ **Parameters:**
2060
+ | Parameter | Type | Required | Description |
2061
+ |-----------|------|----------|-------------|
2062
+ | title | string | Yes | Task title |
2063
+ | description | string | No | Detailed description |
2064
+ | requiredSkills | string[] | No | Skills needed to handle this task |
2065
+ | urgency | string | No | low, medium, high, critical (default: medium) |
2066
+ | timeoutSeconds | number | No | Task timeout in seconds |
2067
+ | maxRetries | number | No | Max retry attempts on failure |
2068
+ | callbackUrl | string | No | URL to notify on completion |
2069
+
2070
+ **Returns:** `Promise<{ task: Object, task_id: string, assigned_agent: Object|null }>`
2071
+
2072
+ **Example:**
2073
+ ```javascript
2074
+ const { task_id, assigned_agent } = await claw.submitRoutingTask({
2075
+ title: 'Analyze quarterly metrics',
2076
+ description: 'Pull Q4 data and generate summary report',
2077
+ requiredSkills: ['data-analysis', 'reporting'],
2078
+ urgency: 'high',
2079
+ timeoutSeconds: 600,
2080
+ callbackUrl: 'https://hooks.example.com/task-done',
2081
+ });
2082
+ console.log(`Task ${task_id} assigned to ${assigned_agent?.name ?? 'queue'}`);
2083
+ ```
2084
+
2085
+ ### claw.completeRoutingTask(taskId, result?)
2086
+ Mark a routing task as completed with optional result payload.
2087
+
2088
+ **Parameters:**
2089
+ | Parameter | Type | Required | Description |
2090
+ |-----------|------|----------|-------------|
2091
+ | taskId | string | Yes | The task ID |
2092
+ | result | Object | No | Task result data |
2093
+
2094
+ **Returns:** `Promise<{ task: Object }>`
2095
+
2096
+ ### claw.getRoutingStats()
2097
+ Get aggregate routing statistics (throughput, latency, agent utilization).
2098
+
2099
+ **Returns:** `Promise<{ stats: Object }>`
2100
+
2101
+ ### claw.getRoutingHealth()
2102
+ Get routing system health status and diagnostics.
2103
+
2104
+ **Returns:** `Promise<{ healthy: boolean, agents: Object, tasks: Object, latency: Object }>`
2105
+
2106
+ ---
2107
+
2108
+ ## Agent Schedules
2109
+
2110
+ Define recurring tasks and cron-based schedules for agents.
2111
+
2112
+ ### claw.listAgentSchedules(filters?)
2113
+ List agent schedules, optionally filtered by agent.
2114
+
2115
+ ```javascript
2116
+ const { schedules } = await claw.listAgentSchedules({ agent_id: 'forge' });
2117
+ ```
2118
+
2119
+ **Parameters:**
2120
+ | Parameter | Type | Required | Description |
2121
+ |-----------|------|----------|-------------|
2122
+ | filters.agent_id | string | No | Filter by agent ID |
2123
+
2124
+ **Returns:** `Promise<{ schedules: Object[] }>`
2125
+
2126
+ ### claw.createAgentSchedule(schedule)
2127
+ Create a new agent schedule entry.
2128
+
2129
+ ```javascript
2130
+ const { schedule } = await claw.createAgentSchedule({
2131
+ agent_id: 'forge',
2132
+ name: 'Build projects',
2133
+ cron_expression: '0 */6 * * *',
2134
+ description: 'Check for pending builds every 6 hours'
2135
+ });
2136
+ ```
2137
+
2138
+ **Parameters:**
2139
+ | Parameter | Type | Required | Description |
2140
+ |-----------|------|----------|-------------|
2141
+ | schedule.agent_id | string | Yes | Agent this schedule belongs to |
2142
+ | schedule.name | string | Yes | Schedule name |
2143
+ | schedule.cron_expression | string | Yes | Cron expression (e.g. `0 */6 * * *`) |
2144
+ | schedule.description | string | No | Human-readable description |
2145
+ | schedule.enabled | boolean | No | Whether schedule is active (default: true) |
2146
+
2147
+ **Returns:** `Promise<{ schedule: Object }>`
2148
+
2149
+ ---
2150
+
2151
+ ## Error Handling
2152
+
2153
+ All SDK methods throw on non-2xx responses. Errors include `status` (HTTP code) and `details` (when available).
2154
+
2155
+ ```javascript
2156
+ try {
2157
+ await claw.createAction({ ... });
2158
+ } catch (err) {
2159
+ if (err.status === 401) {
2160
+ console.error('Invalid API key');
2161
+ } else {
2162
+ console.error(`Action failed: \${err.message}`);
2163
+ }
2164
+ }
2165
+ ```