@refactorlabs/recount 0.5.5

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.
package/llms.md ADDED
@@ -0,0 +1,437 @@
1
+ # @refactorlabs/recount - SDK reference
2
+
3
+ Application explainability SDK. Wraps async workflows in a **trace** made up of **spans**, then sends everything to the Recount dashboard as an interactive timeline.
4
+
5
+ ## Install & init
6
+
7
+ ```ts
8
+ import recount from '@refactorlabs/recount';
9
+
10
+ // reads RECOUNT_API_KEY / RECOUNT_ENVIRONMENT from env automatically
11
+ // call init() only to override
12
+ recount.init({ apiKey: 'bec_...', environment: 'production', debug: true });
13
+ ```
14
+
15
+ If no API key is found, the SDK disables itself. All calls become no-ops with no errors thrown.
16
+
17
+ ## Traces
18
+
19
+ ```ts
20
+ await recount.startTrace(name, options?, async () => { ... });
21
+ ```
22
+
23
+ Options: `input: JsonObject`, `metadata: Record<string, string|number|boolean|null>`, `environment: string`, `retentionPeriod: '1d'|'7d'|'30d'|'90d'|'1y'` (default `'30d'`)
24
+
25
+ The trace is sent when the callback resolves or throws.
26
+
27
+ ## Span types \- when to use each
28
+
29
+ | Type | Use for |
30
+ | --------- | ------------------------------------------------------------------------------ |
31
+ | `message` | Log-style checkpoints, validation steps, plain text output. Never dropped. |
32
+ | `json` | Structured data with no special rendering \- config, decisions, parsed output. |
33
+ | `table` | Tabular/record data. Use `recount.table()` builder for highlighting/summaries. |
34
+ | `chart` | Numeric trends, comparisons. Use `recount.chart()` builder. |
35
+ | `http` | Outbound HTTP calls. Use `recount.fetch()` for auto-tracing. |
36
+ | `llm` | LLM calls. Use `wrapAnthropic`/`wrapOpenAI` for auto-tracing. |
37
+ | `image` | Images rendered inline \- generated images, screenshots, charts as URLs. |
38
+ | `db` | Database queries. Use `wrapCollection` for MongoDB auto-tracing. |
39
+ | `group` | Bundle related spans under a named collapsible section. |
40
+
41
+ ## Spans
42
+
43
+ ```ts
44
+ // static - set fields manually
45
+ recount.addSpan(type, name, options?);
46
+
47
+ // callback - auto-times and captures return value as output
48
+ const result = await recount.addSpan(type, name, async () => { ... });
49
+
50
+ // callback with options
51
+ await recount.addSpan(type, name, { input: { ... }, alerts: [...] }, async () => { ... });
52
+ ```
53
+
54
+ Options: `description`, `input`, `output`, `durationMs`, `alerts`, `redact`, `public`
55
+ (db spans also accept: `metadata: { table, collection, queryType }`, `redactParams`)
56
+
57
+ ### Empty span dropping
58
+
59
+ Spans with no `input` and no `output` are silently dropped at ingest. Groups with no surviving children are also dropped. If all spans drop, the trace is not sent.
60
+
61
+ | Span type | Drop condition |
62
+ | ------------------------------------------------------ | ---------------------------- |
63
+ | `json`, `table`, `chart`, `http`, `llm`, `image`, `db` | No `input` and no `output` |
64
+ | `group` | All child spans were dropped |
65
+ | `message` | Never dropped |
66
+
67
+ Enable `debug: true` in `recount.init()` to log dropped spans to stdout.
68
+
69
+ ## addGroup
70
+
71
+ Groups related spans under a named collapsible section. Does not count against span quota \- only child spans do. Cannot be nested.
72
+
73
+ ```ts
74
+ recount.addGroup('Data fetching', (g) => {
75
+ g.span('db', 'User lookup', { ... });
76
+ g.span('http', 'Profile enrichment', { ... });
77
+ }, { description: 'Fetches user record and enriches with external profile data' });
78
+ ```
79
+
80
+ Group options:
81
+
82
+ | Option | Type | Description |
83
+ | ----------------- | -------- | --------------------------------------------------------------------------- |
84
+ | `description` | `string` | Short description shown in the dashboard |
85
+ | `limit` | `number` | Keep only the first N child spans |
86
+ | `sample` | `number` | Randomly sample down to N child spans (reservoir, preserves order) |
87
+ | `sampleThreshold` | `number` | Only apply `sample` if child count exceeds this value. Defaults to `sample` |
88
+
89
+ `limit` and `sample` are mutually exclusive; `sample` takes precedence if both are set.
90
+
91
+ ```ts
92
+ // limit: keep first 10 results
93
+ recount.addGroup(
94
+ 'Search results',
95
+ (g) => {
96
+ for (const r of results) g.span('json', r.title, { output: r });
97
+ },
98
+ { limit: 10 }
99
+ );
100
+
101
+ // sample: keep 20 random items, only when more than 100
102
+ recount.addGroup(
103
+ 'Processed items',
104
+ (g) => {
105
+ for (const item of items) g.span('json', item.id, { output: item });
106
+ },
107
+ { sample: 20, sampleThreshold: 100 }
108
+ );
109
+ ```
110
+
111
+ The `g` object exposes `g.span(type, name, options?)` and `g.addMessage(name, text?, opts?)`. Import `SpanGroup` for typing helper functions:
112
+
113
+ ```ts
114
+ import recount, { SpanGroup } from '@refactorlabs/recount';
115
+ ```
116
+
117
+ ## addMessage
118
+
119
+ ```ts
120
+ recount.addMessage(name, text?, { level?: 'info'|'warn'|'error', description?: string, alerts?: SpanAlert[], public?: boolean });
121
+ // text is optional - name alone is enough
122
+ recount.addMessage('Cache warmed');
123
+ ```
124
+
125
+ ## addMetadata
126
+
127
+ Adds key/value pairs to the trace metadata after the trace has started:
128
+
129
+ ```ts
130
+ recount.addMetadata({ Decision: 'approved', Score: 87 });
131
+ ```
132
+
133
+ ## recount.named
134
+
135
+ Sets the span name for the next auto-recorded span from an integration (Anthropic, OpenAI, MongoDB). Applies to exactly one span.
136
+
137
+ ```ts
138
+ const result = await recount.named('Classify intent', () =>
139
+ anthropic.messages.create({ model: 'claude-sonnet-4-6', ... })
140
+ );
141
+ // → llm span named 'Classify intent' instead of 'claude-sonnet-4-6'
142
+ ```
143
+
144
+ ## recount.fetch
145
+
146
+ Drop-in traced fetch \- records method, URL, status, duration as an `http` span:
147
+
148
+ ```ts
149
+ const data = await recount.fetch<T>(name, url, requestInit?, options?);
150
+ // options: { redact?: string[] }
151
+ ```
152
+
153
+ ## Table builder
154
+
155
+ ```ts
156
+ recount.addSpan('table', 'Policy validation', {
157
+ output: recount
158
+ .table('Title') // optional title
159
+ .fromRecords(rows) // or .fromObject(obj) for key/value
160
+ .pick('col1', 'col2') // optional column selection
161
+ .label({ col1: 'Label' }) // optional column label overrides
162
+ .transformValues({ amount: (v) => `$${v}` })
163
+ .highlightRows((row) => 'danger'|'warn'|'success'|'info'|'muted'|null)
164
+ .highlightCells('col', (v) => ...)
165
+ .highlightColumn('col', 'success')
166
+ .appendRow([recount.spanCell('Total', 3)], 'info') // spanning cell
167
+ .summary([{ text: 'Total: $7,590', highlight: 'info' }])
168
+ .redact(['fieldName'])
169
+ .round(2)
170
+ .build()
171
+ });
172
+
173
+ // multiple tables in one span
174
+ output: { tables: [recount.table('A').fromRecords(a).build(), recount.table('B').fromRecords(b).build()] }
175
+ ```
176
+
177
+ Highlights: `'danger' | 'warn' | 'success' | 'info' | 'muted'`
178
+
179
+ **Shorthand methods** (skip the builder chain):
180
+
181
+ ```ts
182
+ // build directly from records
183
+ recount.tableFromRecords({ data: rows, title?: string })
184
+
185
+ // build directly from a key/value object
186
+ recount.tableFromObject({ data: obj, title?: string })
187
+ ```
188
+
189
+ ## Chart builder
190
+
191
+ ```ts
192
+ recount.addSpan('chart', 'Damage breakdown', {
193
+ output: recount
194
+ .chart('bar', 'Title') // types: 'bar'|'line'|'pie'|'scatter'
195
+ .labels(['A', 'B', 'C'])
196
+ .series('Name', [1, 2, 3]) // call multiple times for multi-series
197
+ .referenceLine(750, 'Excess')
198
+ .build()
199
+ });
200
+
201
+ // from records
202
+ recount.chart('bar').fromRecords(rows, 'labelKey', ['series1', 'series2']).build()
203
+
204
+ // multiple charts
205
+ output: { charts: [...] }
206
+ ```
207
+
208
+ **Shorthand method:**
209
+
210
+ ```ts
211
+ recount.chartFromRecords({ type, data, labelKey, seriesKeys, title? })
212
+ ```
213
+
214
+ ## LLM spans
215
+
216
+ ### Auto-tracing (preferred)
217
+
218
+ ```ts
219
+ import { wrapAnthropic } from '@refactorlabs/recount/anthropic';
220
+ const anthropic = wrapAnthropic(new Anthropic());
221
+ // every messages.create() \- streaming or not \- records an llm span automatically
222
+
223
+ import { wrapOpenAI } from '@refactorlabs/recount/openai';
224
+ const openai = wrapOpenAI(new OpenAI());
225
+ // every chat.completions.create() records an llm span automatically
226
+ // for streaming token counts: pass stream_options: { include_usage: true }
227
+
228
+ // use recount.named() to set a custom span name for either
229
+ ```
230
+
231
+ Pass `redact` to strip fields from all spans created by a wrapped client:
232
+
233
+ ```ts
234
+ const anthropic = wrapAnthropic(new Anthropic(), { redact: ['user.ssn'] });
235
+ ```
236
+
237
+ ### Manual spans
238
+
239
+ ```ts
240
+ // chat-style
241
+ recount.addSpan('llm', 'Classify intent', {
242
+ input: {
243
+ messages: [{ role: 'user', content: '...' }],
244
+ system: 'You are a claims assessor.',
245
+ provider: 'anthropic',
246
+ model: 'claude-sonnet-4-6'
247
+ },
248
+ output: {
249
+ response: 'No fraud indicators.',
250
+ inputTokens: 120,
251
+ outputTokens: 8
252
+ },
253
+ durationMs: 340
254
+ });
255
+
256
+ // plain prompt (non-chat APIs)
257
+ recount.addSpan('llm', 'Summarise claim', {
258
+ input: { prompt: 'Summarise: ...', provider: 'openai', model: 'gpt-4o' },
259
+ output: { response: 'Rear-end collision claim for $7,590.' }
260
+ });
261
+ ```
262
+
263
+ ## Image spans
264
+
265
+ ```ts
266
+ // output: generated image
267
+ recount.addSpan('image', 'Generated image', {
268
+ output: { url: 'https://...', label: 'Profile photo' }
269
+ });
270
+
271
+ // input + output: before/after
272
+ recount.addSpan('image', 'Resize', {
273
+ input: { url: 'https://.../original.png', label: 'Original' },
274
+ output: { url: 'https://.../resized.png', label: 'Resized 400×300' }
275
+ });
276
+ ```
277
+
278
+ Dashboard renders images inline; falls back to a clickable link if the URL fails to load.
279
+
280
+ ## Database spans
281
+
282
+ ```ts
283
+ recount.addSpan('db', 'User lookup', {
284
+ metadata: { table: 'users', queryType: 'sql' },
285
+ input: { query: 'SELECT * FROM users WHERE id = $1', params: [userId] },
286
+ output: { rows: 1 },
287
+ redactParams: [userId]
288
+ });
289
+ ```
290
+
291
+ ### MongoDB auto-tracing
292
+
293
+ ```ts
294
+ import { wrapCollection } from '@refactorlabs/recount/mongodb';
295
+ const users = wrapCollection(db.collection('users'), { redact: ['name'] });
296
+ // findOne, find, insertOne, insertMany, updateOne, updateMany,
297
+ // deleteOne, deleteMany, replaceOne, findOneAndUpdate,
298
+ // findOneAndDelete, aggregate, countDocuments \- all traced
299
+ // use recount.named() to set a custom span name
300
+ ```
301
+
302
+ ## Alerts
303
+
304
+ ```ts
305
+ recount.addSpan('table', 'Affordability', {
306
+ alerts: [
307
+ {
308
+ label: 'Max DTI (40%)',
309
+ level: 'error',
310
+ gt: 0.4,
311
+ checks: [{ target: 'Table title', value: dti }]
312
+ },
313
+ {
314
+ label: 'Min income',
315
+ level: 'warn',
316
+ lt: 300,
317
+ checks: [{ value: disposableIncome }]
318
+ }
319
+ ],
320
+ output: recount.table().fromRecords(rows).build()
321
+ });
322
+ ```
323
+
324
+ `target` must match the title passed to `recount.table(title)`. Both `gt` and `lt` can be set on the same rule. At least one check required.
325
+
326
+ ## Redaction
327
+
328
+ ```ts
329
+ // inline sentinel
330
+ output: { email: recount.REDACTED, name: user.name }
331
+
332
+ // field redaction \- exact path from root ('ssn' = root only, 'billing.accountNumber' = one level deep)
333
+ recount.addSpan('json', 'Record', { output: data, redact: ['ssn', 'billing.accountNumber'] });
334
+
335
+ // db param redaction
336
+ recount.addSpan('db', 'User lookup', {
337
+ input: { query: 'SELECT * FROM users WHERE id = $1', params: [userId] },
338
+ redactParams: [userId]
339
+ });
340
+
341
+ // table column redaction
342
+ recount.table().fromObject(obj).redact(['name']).build()
343
+ ```
344
+
345
+ HTTP spans automatically redact `Authorization`, `Cookie`, `X-Api-Key`, and related headers.
346
+
347
+ ## Full example
348
+
349
+ ```ts
350
+ import recount from '@refactorlabs/recount';
351
+
352
+ const damage = [
353
+ { component: 'Rear bumper', severity: 'major', estimatedCost: 2_400 },
354
+ { component: 'Boot lid', severity: 'major', estimatedCost: 3_100 },
355
+ { component: 'Rear lights', severity: 'moderate', estimatedCost: 890 }
356
+ ];
357
+ const total = damage.reduce((s, d) => s + d.estimatedCost, 0);
358
+ const excess = 750;
359
+
360
+ await recount.startTrace(
361
+ 'Insurance claim - CLM-2024-03941',
362
+ {
363
+ metadata: { 'Claim ID': 'CLM-2024-03941' },
364
+ input: recount.tableFromObject({
365
+ data: { 'Claim ID': 'CLM-2024-03941', Vehicle: '2019 Toyota Camry' }
366
+ })
367
+ },
368
+ async () => {
369
+ recount.addSpan('db', 'Policy lookup', {
370
+ description:
371
+ 'Fetches the active policy record for the submitted claim number',
372
+ metadata: { table: 'policies', queryType: 'sql' },
373
+ input: {
374
+ query: 'SELECT * FROM policies WHERE number = $1',
375
+ params: ['POL-8821-AU']
376
+ },
377
+ output: { rows: 1 }
378
+ });
379
+
380
+ recount.addSpan('table', 'Damage assessment', {
381
+ output: recount
382
+ .table()
383
+ .fromRecords(damage)
384
+ .highlightRows((row) =>
385
+ row.severity === 'major'
386
+ ? 'danger'
387
+ : row.severity === 'moderate'
388
+ ? 'warn'
389
+ : 'muted'
390
+ )
391
+ .transformValues({
392
+ estimatedCost: (v) => `$${Number(v).toLocaleString()}`
393
+ })
394
+ .summary([
395
+ { text: `Total: $${total.toLocaleString()}`, highlight: 'info' },
396
+ {
397
+ text: `Settlement: $${(total - excess).toLocaleString()}`,
398
+ highlight: 'success'
399
+ }
400
+ ])
401
+ .build(),
402
+ alerts: [
403
+ {
404
+ label: 'High-value claim (>$5,000)',
405
+ level: 'warn',
406
+ gt: 5_000,
407
+ checks: [{ value: total }]
408
+ }
409
+ ]
410
+ });
411
+
412
+ recount.addSpan('chart', 'Cost breakdown', {
413
+ output: recount
414
+ .chart('bar', 'Repair cost')
415
+ .labels(damage.map((d) => d.component))
416
+ .series(
417
+ 'Cost ($)',
418
+ damage.map((d) => d.estimatedCost)
419
+ )
420
+ .referenceLine(excess, `Excess ($${excess})`)
421
+ .build()
422
+ });
423
+
424
+ recount.addSpan('json', 'Outcome', {
425
+ output: { decision: 'approved', settlement: total - excess }
426
+ });
427
+ }
428
+ );
429
+ ```
430
+
431
+ ## Error handling
432
+
433
+ ```ts
434
+ import { RecountError } from '@refactorlabs/recount';
435
+ ```
436
+
437
+ Network errors are swallowed silently. `RecountError` is thrown only on non-OK API responses (only if using the `Recount` class directly; the default export swallows ingest errors).
package/package.json ADDED
@@ -0,0 +1,117 @@
1
+ {
2
+ "name": "@refactorlabs/recount",
3
+ "version": "0.5.5",
4
+ "description": "Node.js SDK for Recount",
5
+ "homepage": "https://recount.refactor.gg",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://gitlab.com/refactor-labs/recount-node"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "main": "./dist/index.cjs",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "typesVersions": {
19
+ "*": {
20
+ "anthropic": [
21
+ "./dist/integrations/anthropic.d.ts"
22
+ ],
23
+ "openai": [
24
+ "./dist/integrations/openai.d.ts"
25
+ ],
26
+ "mongodb": [
27
+ "./dist/integrations/mongodb.d.ts"
28
+ ]
29
+ }
30
+ },
31
+ "exports": {
32
+ ".": {
33
+ "import": {
34
+ "types": "./dist/index.d.ts",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "require": {
38
+ "types": "./dist/index.d.cts",
39
+ "default": "./dist/index.cjs"
40
+ }
41
+ },
42
+ "./anthropic": {
43
+ "import": {
44
+ "types": "./dist/integrations/anthropic.d.ts",
45
+ "default": "./dist/integrations/anthropic.js"
46
+ },
47
+ "require": {
48
+ "types": "./dist/integrations/anthropic.d.cts",
49
+ "default": "./dist/integrations/anthropic.cjs"
50
+ }
51
+ },
52
+ "./openai": {
53
+ "import": {
54
+ "types": "./dist/integrations/openai.d.ts",
55
+ "default": "./dist/integrations/openai.js"
56
+ },
57
+ "require": {
58
+ "types": "./dist/integrations/openai.d.cts",
59
+ "default": "./dist/integrations/openai.cjs"
60
+ }
61
+ },
62
+ "./mongodb": {
63
+ "import": {
64
+ "types": "./dist/integrations/mongodb.d.ts",
65
+ "default": "./dist/integrations/mongodb.js"
66
+ },
67
+ "require": {
68
+ "types": "./dist/integrations/mongodb.d.cts",
69
+ "default": "./dist/integrations/mongodb.cjs"
70
+ }
71
+ }
72
+ },
73
+ "files": [
74
+ "dist",
75
+ "llms.md",
76
+ "recount-instrument"
77
+ ],
78
+ "scripts": {
79
+ "build": "tsup",
80
+ "dev": "tsup --watch",
81
+ "typecheck": "tsc --noEmit",
82
+ "lint": "eslint .",
83
+ "test": "vitest run",
84
+ "test:watch": "vitest",
85
+ "test:integration": "pnpm build && node test/integration/cjs-singleton.mjs"
86
+ },
87
+ "peerDependencies": {
88
+ "@anthropic-ai/sdk": ">=0.20.0",
89
+ "mongodb": ">=5.0.0",
90
+ "openai": ">=4.0.0"
91
+ },
92
+ "peerDependenciesMeta": {
93
+ "@anthropic-ai/sdk": {
94
+ "optional": true
95
+ },
96
+ "mongodb": {
97
+ "optional": true
98
+ },
99
+ "openai": {
100
+ "optional": true
101
+ }
102
+ },
103
+ "devDependencies": {
104
+ "@eslint/js": "^9.0.0",
105
+ "@anthropic-ai/sdk": "^0.111.0",
106
+ "@types/node": "^26.1.1",
107
+ "eslint": "^9.0.0",
108
+ "globals": "^15.0.0",
109
+ "mongodb": "^7.5.0",
110
+ "openai": "^6.46.0",
111
+ "tsup": "^8.0.0",
112
+ "tsx": "^4.23.1",
113
+ "typescript": "^5.0.0",
114
+ "typescript-eslint": "^8.0.0",
115
+ "vitest": "^4.1.10"
116
+ }
117
+ }