@mainwave/cli 0.7.1 → 0.8.0

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 (124) hide show
  1. package/README.md +4 -1
  2. package/dist/adapters/claude-code.js +10 -3
  3. package/dist/adapters/claude-desktop.js +0 -1
  4. package/dist/adapters/codex-cli.js +0 -1
  5. package/dist/adapters/copilot-chat.js +0 -1
  6. package/dist/adapters/copilot-cli.js +0 -1
  7. package/dist/adapters/cursor-enterprise.js +0 -1
  8. package/dist/adapters/cursor.js +13 -2
  9. package/dist/adapters/index.js +0 -1
  10. package/dist/adapters/types.js +0 -1
  11. package/dist/api/index.js +0 -1
  12. package/dist/api/types.gen.js +0 -1
  13. package/dist/cli.js +0 -1
  14. package/dist/core/apply.js +0 -1
  15. package/dist/core/auth-commands.js +0 -1
  16. package/dist/core/behaviour-hooks.js +0 -1
  17. package/dist/core/browser.js +0 -1
  18. package/dist/core/codecs/cursor-hooks-json.js +0 -1
  19. package/dist/core/codecs/env-file.js +0 -1
  20. package/dist/core/codecs/json-env.js +0 -1
  21. package/dist/core/codecs/json-flat.js +0 -1
  22. package/dist/core/codecs/json-managed.js +0 -1
  23. package/dist/core/codecs/toml-otel.js +0 -1
  24. package/dist/core/codecs/types.js +0 -1
  25. package/dist/core/detect.js +0 -1
  26. package/dist/core/device-login.js +0 -1
  27. package/dist/core/doctor.js +19 -1
  28. package/dist/core/edit.js +9 -5
  29. package/dist/core/effective-settings.js +61 -20
  30. package/dist/core/env-command.js +0 -1
  31. package/dist/core/errors.js +0 -1
  32. package/dist/core/flags.js +0 -1
  33. package/dist/core/format.js +0 -1
  34. package/dist/core/git.js +0 -1
  35. package/dist/core/headers.js +0 -1
  36. package/dist/core/install-hooks.js +3 -3
  37. package/dist/core/interview.js +0 -1
  38. package/dist/core/keys.js +0 -1
  39. package/dist/core/layer-policy.js +2 -1
  40. package/dist/core/markers.js +170 -15
  41. package/dist/core/pinned-use-case.js +0 -1
  42. package/dist/core/platform.js +0 -1
  43. package/dist/core/post-setup.js +0 -1
  44. package/dist/core/prompts.js +0 -1
  45. package/dist/core/settings.js +16 -3
  46. package/dist/core/skills.js +5 -2
  47. package/dist/core/status.js +5 -4
  48. package/dist/core/store.js +0 -1
  49. package/dist/core/tty.js +0 -1
  50. package/dist/core/ucid.js +0 -1
  51. package/dist/core/ui.js +0 -1
  52. package/dist/core/use-case.js +0 -1
  53. package/dist/core/validate.js +0 -1
  54. package/dist/core/verify.js +0 -1
  55. package/dist/core/version.js +0 -1
  56. package/dist/core/wizard.js +3 -7
  57. package/dist/main.js +0 -1
  58. package/hooks/cursor-otlp.mjs +13 -15
  59. package/hooks/github-pr-marker.mjs +22 -11
  60. package/hooks/jira-ticket-marker.mjs +9 -9
  61. package/hooks/linear-ticket-marker.mjs +9 -7
  62. package/hooks/managed-entry.mjs +42 -0
  63. package/hooks/marker-core.mjs +123 -29
  64. package/package.json +4 -3
  65. package/skills/mainwave-instrument-node/SKILL.md +420 -0
  66. package/skills/mainwave-instrument-node/reference/api.md +96 -0
  67. package/skills/mainwave-instrument-node/reference/frameworks.md +82 -0
  68. package/skills/mainwave-instrument-node/reference/troubleshooting.md +152 -0
  69. package/dist/adapters/claude-code.js.map +0 -1
  70. package/dist/adapters/claude-desktop.js.map +0 -1
  71. package/dist/adapters/codex-cli.js.map +0 -1
  72. package/dist/adapters/copilot-chat.js.map +0 -1
  73. package/dist/adapters/copilot-cli.js.map +0 -1
  74. package/dist/adapters/cursor-enterprise.js.map +0 -1
  75. package/dist/adapters/cursor.js.map +0 -1
  76. package/dist/adapters/index.js.map +0 -1
  77. package/dist/adapters/types.js.map +0 -1
  78. package/dist/api/index.js.map +0 -1
  79. package/dist/api/types.gen.js.map +0 -1
  80. package/dist/cli.js.map +0 -1
  81. package/dist/core/apply.js.map +0 -1
  82. package/dist/core/auth-commands.js.map +0 -1
  83. package/dist/core/behaviour-hooks.js.map +0 -1
  84. package/dist/core/browser.js.map +0 -1
  85. package/dist/core/codecs/cursor-hooks-json.js.map +0 -1
  86. package/dist/core/codecs/env-file.js.map +0 -1
  87. package/dist/core/codecs/json-env.js.map +0 -1
  88. package/dist/core/codecs/json-flat.js.map +0 -1
  89. package/dist/core/codecs/json-managed.js.map +0 -1
  90. package/dist/core/codecs/toml-otel.js.map +0 -1
  91. package/dist/core/codecs/types.js.map +0 -1
  92. package/dist/core/detect.js.map +0 -1
  93. package/dist/core/device-login.js.map +0 -1
  94. package/dist/core/doctor.js.map +0 -1
  95. package/dist/core/edit.js.map +0 -1
  96. package/dist/core/effective-settings.js.map +0 -1
  97. package/dist/core/env-command.js.map +0 -1
  98. package/dist/core/errors.js.map +0 -1
  99. package/dist/core/flags.js.map +0 -1
  100. package/dist/core/format.js.map +0 -1
  101. package/dist/core/git.js.map +0 -1
  102. package/dist/core/headers.js.map +0 -1
  103. package/dist/core/install-hooks.js.map +0 -1
  104. package/dist/core/interview.js.map +0 -1
  105. package/dist/core/keys.js.map +0 -1
  106. package/dist/core/layer-policy.js.map +0 -1
  107. package/dist/core/markers.js.map +0 -1
  108. package/dist/core/pinned-use-case.js.map +0 -1
  109. package/dist/core/platform.js.map +0 -1
  110. package/dist/core/post-setup.js.map +0 -1
  111. package/dist/core/prompts.js.map +0 -1
  112. package/dist/core/settings.js.map +0 -1
  113. package/dist/core/skills.js.map +0 -1
  114. package/dist/core/status.js.map +0 -1
  115. package/dist/core/store.js.map +0 -1
  116. package/dist/core/tty.js.map +0 -1
  117. package/dist/core/ucid.js.map +0 -1
  118. package/dist/core/ui.js.map +0 -1
  119. package/dist/core/use-case.js.map +0 -1
  120. package/dist/core/validate.js.map +0 -1
  121. package/dist/core/verify.js.map +0 -1
  122. package/dist/core/version.js.map +0 -1
  123. package/dist/core/wizard.js.map +0 -1
  124. package/dist/main.js.map +0 -1
@@ -0,0 +1,420 @@
1
+ ---
2
+ name: mainwave-instrument-node
3
+ description: Instrument a Node.js / TypeScript AI agent or LLM application with @mainwave/sdk so its runs, tokens, cost, and tool calls arrive in Mainwave. Use when asked to add Mainwave, add tracing/observability to a Node, TypeScript, Next.js, or eve agent, connect a JavaScript app to Mainwave, or when telemetry is configured but no spans are showing up. Covers init placement, the eve helper, OpenTelemetry host wiring, Vercel AI SDK / OpenAI / Anthropic attach paths, use-case identity, flushing on serverless, and verification.
4
+ ---
5
+
6
+ # Instrumenting a Node.js application with Mainwave
7
+
8
+ `@mainwave/sdk` sends OpenTelemetry spans for LLM work to Mainwave over
9
+ OTLP/HTTP. What you add depends on who owns the process's OpenTelemetry setup:
10
+ an eve agent takes one file, a host that already registers OpenTelemetry takes
11
+ one span processor, and an application with no OpenTelemetry takes `init()`.
12
+
13
+ Your job is to choose that path, place the call correctly, bind the work to a
14
+ use case, and then **prove a span arrived**. An instrumentation task that ends
15
+ without verification is not finished.
16
+
17
+ Requires Node 22.13 or newer on 22.x, or 23.5 or newer. `@mainwave/sdk/eve`
18
+ requires Node 24 or newer, as eve itself does. The package is ESM-only.
19
+
20
+ ## 1. Survey before editing
21
+
22
+ Answer these from the codebase, not from assumption:
23
+
24
+ - **Which of the four is called?** Check `package.json` and imports for `eve`,
25
+ `ai` (with `@ai-sdk/otel`), `openai`, `@anthropic-ai/sdk`. More than one can
26
+ apply. Note the installed versions: eve `>=0.66.3 <0.70.0`, `ai` `^7` with
27
+ `@ai-sdk/otel` `^1`, `openai` `>=4.19.0 <8`, `@anthropic-ai/sdk`
28
+ `>=0.51.0 <1`. A version outside its range is not instrumented: report it, do
29
+ not wire around it.
30
+ - **Does the app already register OpenTelemetry?** Search for `@vercel/otel`
31
+ (`registerOTel`), `@opentelemetry/sdk-node` (`NodeSDK`),
32
+ `NodeTracerProvider`, a Next.js `instrumentation.ts`, or an eve
33
+ `agent/instrumentation/` directory. If something registers the tracer
34
+ provider, the app is a **host**: do not call `init()` into it.
35
+ - **Where does the process start?** The server entry, the worker bootstrap, the
36
+ script's first file, the Next.js `instrumentation.ts` `register()`. That is
37
+ where `init()` or the host wiring goes.
38
+ - **ESM or CommonJS, bundled or not, and what runtime?** This picks the attach
39
+ path in section 6. Plain `node app.mjs` is not bundled; Vercel Functions,
40
+ Next.js, and anything built by a bundler are.
41
+ - **What is one "unit of work"?** A ticket triaged, a question answered, an
42
+ invoice processed. It becomes a run, and it is the level a business operator
43
+ reads results at: not one HTTP request, not one LLM call.
44
+
45
+ ## 2. Credentials: never invent them
46
+
47
+ **Never invent an API key or a use-case id.** Both come from the user's Mainwave
48
+ account. Read them from the environment (`MAINWAVE_API_KEY`,
49
+ `MAINWAVE_USE_CASE_ID`); if the key is absent, stop and ask, or have the user
50
+ run:
51
+
52
+ ```bash
53
+ npx @mainwave/cli@latest login
54
+ ```
55
+
56
+ Keys and use cases are visible in the app at `app.mainwave.com`. Put the key in
57
+ the project's existing secret mechanism (the deployment's environment variables,
58
+ an untracked `.env` the project already loads) — **never a literal in source,
59
+ never a committed file.** Do not write `apiKey: '...'` in code: read it from
60
+ `process.env` or leave the option out, because `init()` reads
61
+ `MAINWAVE_API_KEY` itself.
62
+
63
+ ## 3. Install
64
+
65
+ Use the package manager the repo already uses (check the lockfile; never mix):
66
+
67
+ ```bash
68
+ npm install @mainwave/sdk # or: pnpm add @mainwave/sdk / yarn add @mainwave/sdk
69
+ ```
70
+
71
+ `@opentelemetry/api` (`>=1.9.0 <1.10.0`) is a required peer dependency. If the
72
+ app already depends on another version of it, stop and report the conflict.
73
+ The framework and provider packages are optional peers the application already
74
+ installs; **install none of them for the user, and never install an
75
+ OpenInference or Traceloop package**: the SDK carries its own OpenAI and
76
+ Anthropic instrumentation, and a second one traces every call twice.
77
+
78
+ If the install fails with "package not found", report that
79
+ `@mainwave/sdk` is not yet published to npm and stop. Do not substitute another
80
+ package.
81
+
82
+ ## 4. Pick the path
83
+
84
+ | The app is | Path |
85
+ | --------------------------------------------------------------- | ------------------------------------------------------------------- |
86
+ | An eve agent | Section 5a: one instrumentation file, no `init()` |
87
+ | A host that registers OpenTelemetry (`registerOTel`, `NodeSDK`) | Section 5b: `createSpanProcessor()` into the host |
88
+ | Owns its process, no OpenTelemetry of its own | Section 5c: `init()` at process start |
89
+ | Uses none of eve, AI SDK, OpenAI, Anthropic | Section 5c with manual `run()` / `span()`; say no framework applies |
90
+
91
+ Then add the provider attach in section 6 for any of AI SDK, OpenAI, Anthropic
92
+ the app calls. Wiring is **additive**: leave the app's existing OpenTelemetry
93
+ setup in place.
94
+
95
+ ## 5a. eve: one instrumentation file
96
+
97
+ Add `agent/instrumentation/mainwave.ts`:
98
+
99
+ ```ts
100
+ import { mainwave } from '@mainwave/sdk/eve'
101
+
102
+ export default mainwave({ useCaseKey: 'support-agent' })
103
+ ```
104
+
105
+ - **Do not call `init()` in an eve app.** eve owns the tracer provider;
106
+ `mainwave()` adds a span processor to eve's pipeline.
107
+ - **Remove any custom exporter and any span processor that renames eve's root
108
+ span** from `agent/instrumentation/`. With both in place every span arrives
109
+ twice. Keep an existing `otel({ resource: { 'mainwave.ucid': ... } })` and call
110
+ `mainwave()` with no `useCaseId` or `useCaseKey` (and no
111
+ `MAINWAVE_USE_CASE_ID` / `MAINWAVE_USE_CASE_KEY` set), or pass that same id
112
+ as `mainwave({ useCaseId })`. A `useCaseKey` overrides the resource and moves
113
+ the runs to a different use case, so the example above fits a new eve app,
114
+ not a migrating one.
115
+ - If the removed destination had an `exportPolicy`, pass the same policy to
116
+ `mainwave({ exportPolicy })`: eve applies a policy only to the destination
117
+ that declares it, so a policy left in the removed file stops applying and the
118
+ content it redacted starts reaching Mainwave. Keep `tracePolicy` unchanged.
119
+ - If the removed exporter rewrote the model id (an inference-profile ARN, for
120
+ one), pass the same mapping as `mainwave({ modelAliases })`. If it rewrote
121
+ the provider name, drop that rewrite: the SDK does it.
122
+ - The function must run Node 24 or newer with eve `>=0.66.3 <0.70.0`.
123
+ - eve flushes through the request's `waitUntil` on Vercel: add no `flush()`.
124
+ - Do not add `mainwaveTelemetry()` (AI SDK) to an eve app; eve already sends
125
+ those spans.
126
+
127
+ Without an API key `mainwave()` logs one error and eve runs with nothing sent.
128
+
129
+ ## 5b. Hosts: `createSpanProcessor()`
130
+
131
+ OpenTelemetry JavaScript cannot add a processor to a provider that already
132
+ exists, so pass the SDK's processor to whoever registers the provider.
133
+ `@vercel/otel` (for example Next.js `instrumentation.ts`):
134
+
135
+ ```ts
136
+ import { registerOTel } from '@vercel/otel'
137
+ import { createSpanProcessor } from '@mainwave/sdk'
138
+
139
+ export function register(): void {
140
+ registerOTel({
141
+ serviceName: 'invoice-app',
142
+ spanProcessors: ['auto', createSpanProcessor({ useCaseKey: 'invoice-workflow' })],
143
+ })
144
+ }
145
+ ```
146
+
147
+ `NodeSDK`:
148
+
149
+ ```ts
150
+ import { NodeSDK } from '@opentelemetry/sdk-node'
151
+ import { createSpanProcessor } from '@mainwave/sdk'
152
+
153
+ const sdk = new NodeSDK({
154
+ spanProcessors: [createSpanProcessor({ useCaseKey: 'invoice-workflow' })],
155
+ })
156
+ sdk.start()
157
+ ```
158
+
159
+ A plain `NodeTracerProvider` takes
160
+ `new NodeTracerProvider({ spanProcessors: [createSpanProcessor()] })`.
161
+
162
+ - Keep the host's existing exporters and processors; add this one beside them.
163
+ - `createSpanProcessor(options)` takes the `init()` options except `mode`. It
164
+ throws `MainwaveConfigError` for a missing API key.
165
+ - `createSpanProcessor()` is the initialization in host mode. Do not also call
166
+ `init()`: a bare `init()` after `createSpanProcessor({ useCaseKey })` resolves
167
+ a different configuration and throws `MainwaveReinitConflict`.
168
+ - An `init()` call that finds another provider registered, with no
169
+ `createSpanProcessor()` wired in, exports nothing and logs one warning.
170
+ Do not "fix" that by removing the host's provider.
171
+
172
+ ## 5c. Owned mode: `init()` at process start
173
+
174
+ For an application with no OpenTelemetry setup of its own:
175
+
176
+ ```ts
177
+ import { init } from '@mainwave/sdk'
178
+
179
+ init({ useCaseKey: 'invoice-workflow', serviceName: 'invoice-app' })
180
+ ```
181
+
182
+ - **Once per process, at the entry point, before the first `run()`.** A second
183
+ call with an equal configuration does nothing; a different one throws
184
+ `MainwaveReinitConflict`. In a server, initialize at startup, not per request.
185
+ - `init()` reads `MAINWAVE_API_KEY` when `apiKey` is not passed and throws
186
+ `MainwaveConfigError` when neither is set.
187
+ - **`serviceName` is the deployable**, not the agent: `invoice-app`, not
188
+ `ClassifierAgent`. It defaults to `mainwave-app`, which tells the operator
189
+ nothing, so set it (or `OTEL_SERVICE_NAME`).
190
+ - Wrap each unit of work in a run:
191
+
192
+ ```ts
193
+ import { run } from '@mainwave/sdk'
194
+
195
+ await run(`triage-${ticket.id}`, { metadata: { ticketId: ticket.id } }, async (current) => {
196
+ const decision = await classify(ticket) // instrumented calls land inside
197
+ current.end({ status: 'ok', decision, iterations: 2 })
198
+ })
199
+ ```
200
+
201
+ `run(runId, [options], fn)` binds the run across `await`, `Promise.all`, and
202
+ timers, ends it OK when `fn` settles, and on a throw records the error, ends
203
+ it as an error, and rethrows. `run()` is optional: without it each trace is
204
+ its own run. Add it where one unit of work spans several traces.
205
+ `startRun()` returns a handle for work that does not fit one callback; it
206
+ does not set ambient context, so bind with `handle.with(fn)`. `span(name,
207
+ [{ attributes }], fn)` adds a custom span.
208
+
209
+ - Bind at the **root** of the unit of work. Spans started before the bind do not
210
+ inherit it.
211
+ - A trace with no LLM activity is dropped whole. A `run()`, a `span()`, or an
212
+ attached provider call keeps its trace.
213
+
214
+ ## 6. Provider attach paths
215
+
216
+ AI SDK, OpenAI, and Anthropic each have their own path. Pick by what the repo
217
+ calls, and attach after `init()` (owned mode) or after the host wiring (host
218
+ mode). In host mode `createSpanProcessor()` is the initialization: **do not
219
+ call `init()`**. A bare `init()` after `createSpanProcessor({ useCaseKey })`
220
+ resolves a different configuration and throws `MainwaveReinitConflict`.
221
+
222
+ **Vercel AI SDK v7** (`ai` `^7` with `@ai-sdk/otel` `^1`; v5 and v6 are not
223
+ supported, so report that and stop):
224
+
225
+ ```ts
226
+ import { registerTelemetry } from 'ai'
227
+ import { mainwaveTelemetry } from '@mainwave/sdk/ai-sdk'
228
+
229
+ registerTelemetry(mainwaveTelemetry())
230
+ ```
231
+
232
+ Register once. This covers the AI SDK's `generateText`, `streamText`, and
233
+ `embed` calls, including calls through `@ai-sdk/*` provider packages. It writes
234
+ through the global tracer provider; a host whose provider is not the global one
235
+ passes `mainwaveTelemetry({ tracer })`.
236
+
237
+ **OpenAI (`openai`) and Anthropic (`@anthropic-ai/sdk`) called directly:** choose
238
+ by how the app starts.
239
+
240
+ | The app is | Attach |
241
+ | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
242
+ | A plain Node process you start (`node app.mjs`, a worker, a script) | `node --import @mainwave/sdk/register app.mjs` |
243
+ | Bundled, or on Vercel Functions or Next.js, or the flag cannot be set | `instrument({ openai, anthropic })` after the host wiring (host mode, no `init()`), or after `init()` (owned mode) |
244
+ | A host that registers its own OpenTelemetry instrumentations | `new OpenAIInstrumentation()` / `new AnthropicInstrumentation()` from `@mainwave/sdk/openai` / `@mainwave/sdk/anthropic` via `registerInstrumentations` |
245
+
246
+ The loader flag covers static imports, dynamic `import()`, and `require()`,
247
+ for both clients in one process. Put it where the process starts (the
248
+ `start` script, the Dockerfile `CMD`, or `NODE_OPTIONS='--import
249
+ @mainwave/sdk/register'`), and still initialize in the app: `init()` in owned
250
+ mode, or the `createSpanProcessor()` wiring from section 5b in host mode (no
251
+ `init()`). In owned mode, a CommonJS app that calls `init()` before its first
252
+ `require()` of the client needs no flag; a host-mode app needs the flag or
253
+ `instrument()`.
254
+
255
+ The explicit path, for bundled and serverless hosts (on Vercel Functions and in
256
+ bundled apps this is the supported way; do not use the flag there). Owned mode
257
+ calls `init()` first:
258
+
259
+ ```ts
260
+ import * as anthropic from '@anthropic-ai/sdk'
261
+ import * as openai from 'openai'
262
+ import { init, instrument } from '@mainwave/sdk'
263
+
264
+ init()
265
+ instrument({ openai, anthropic })
266
+ ```
267
+
268
+ Host mode (Next.js with `@vercel/otel`, `NodeSDK`) calls `instrument()` after
269
+ the section 5b wiring and never calls `init()`:
270
+
271
+ ```ts
272
+ import * as anthropic from '@anthropic-ai/sdk'
273
+ import * as openai from 'openai'
274
+ import { instrument } from '@mainwave/sdk'
275
+
276
+ // Runs after registerOTel(...) or sdk.start() has received createSpanProcessor().
277
+ instrument({ openai, anthropic })
278
+ ```
279
+
280
+ **Pass every module copy the app loads.** An ES module import and a
281
+ `require()` result are two different copies, and a copy that was not passed is
282
+ not traced: `instrument({ openai: [esm, required] })`. `instrument()` returns
283
+ `{ openai: 'patched' }`, `'already'` (attached before), or `'unrecognized'`
284
+ (what it was given is not the module), and never throws. Read the result: an
285
+ `'unrecognized'` means the wiring is wrong, and a client missing from the
286
+ spans usually means the code calls a copy you did not pass.
287
+
288
+ An ES module app that uses neither the flag nor `instrument()` gets no spans
289
+ from these clients and one not-attached warning naming both options.
290
+ `init({ skipInstrumentations: ['openai'] })` turns the SDK's hooks off when
291
+ another instrumentation for that client is already running (it would trace
292
+ every call twice).
293
+
294
+ ## 7. Use-case identity
295
+
296
+ Mainwave groups runs into use cases. Give the app **one** of:
297
+
298
+ - `useCaseId` (or `MAINWAVE_USE_CASE_ID`): a UUID created in the Mainwave app.
299
+ - `useCaseKey` (or `MAINWAVE_USE_CASE_KEY`): a name you choose; the SDK derives
300
+ the same UUID from the same key every time.
301
+
302
+ **Never both in the same options object**: that throws `MainwaveConfigError`.
303
+ When both environment variables are set, the id wins.
304
+
305
+ - If the user has a use case in the app, use its id. Otherwise ask which one;
306
+ do not make up an id.
307
+ - With neither set, the SDK derives an identity from `serviceName` and the
308
+ telemetry lands in a use case the operator never created. Set one explicitly.
309
+ - Derived ids seed on the API key unless `ucidNamespace` (or
310
+ `MAINWAVE_UCID_NAMESPACE`) is set, so rotating the key changes every derived
311
+ id. Without a namespace the SDK warns once, when the first span carries a
312
+ derived id; if the user has an organization namespace from the app, set it.
313
+ - When one deployable serves several use cases, override per block with
314
+ `useCaseId` / `useCaseKey` on `run()` or `bindIdentity({ ... }, fn)`. A `run()`
315
+ nested in another run ignores them, warns, and keeps the outer run's id.
316
+ `useCaseIdFor('invoice-workflow')` returns the UUID a key derives to; it
317
+ throws `MainwaveConfigError` before `init()` or when the SDK is disabled.
318
+
319
+ ## 8. Flush before the process ends
320
+
321
+ | Host | What the app does |
322
+ | ------------------------------------------- | -------------------------------------------------------------- |
323
+ | eve on Vercel, or an `@vercel/otel` host | nothing |
324
+ | Owned mode on Vercel Functions | nothing; `await flush()` before returning is also safe |
325
+ | Owned mode on any other serverless platform | `await flush()` before the handler returns |
326
+ | Script or job that exits | `await flush()` on every exit path, error path included |
327
+ | Long-lived server or worker | nothing; call `await shutdown()` from your own SIGTERM handler |
328
+
329
+ ```ts
330
+ import { flush, init, run } from '@mainwave/sdk'
331
+
332
+ init({ useCaseKey: 'invoice-workflow' })
333
+
334
+ export async function handler(event: { invoiceId: string }): Promise<{ ok: boolean }> {
335
+ await run(event.invoiceId, async () => {
336
+ // LLM calls
337
+ })
338
+ return { ok: await flush() }
339
+ }
340
+ ```
341
+
342
+ `flush()` resolves `true` when the collector accepted everything, `false` on a
343
+ timeout, a failed export, or a dropped trace, and never rejects. By default the
344
+ SDK installs no signal listener and never calls `process.exit`. Do not add
345
+ either on the SDK's behalf.
346
+
347
+ Vercel Edge runtime is not supported: the SDK does nothing there and logs one
348
+ warning. Tell the user to deploy that route on the Node.js runtime.
349
+
350
+ ## 9. Verify (do not skip this)
351
+
352
+ 1. Get the use-case id: the configured `useCaseId`, or run the application
353
+ once with `MAINWAVE_LOG_LEVEL=info` and copy the id from the line the SDK
354
+ writes to stderr when the first span carries the derived process default
355
+ (from a configured `useCaseKey`, or from `serviceName` when nothing is
356
+ configured): `mainwave: use-case identity resolved: key=... ucid=<uuid>
357
+ ...`. `init()` alone prints no such line; the work must start a span. After
358
+ the first successful export it also writes `mainwave: exported first span
359
+ batch (<n> spans) to <collector url>/v1/traces`.
360
+ If the app uses the eve helper or `createSpanProcessor()`, keeps a valid
361
+ `mainwave.ucid` resource attribute and configures no use-case id or key,
362
+ spans carry that resource id and no `use-case identity resolved` line
363
+ prints: verify the resource id. Owned-mode `init()` ignores a resource
364
+ `mainwave.ucid`, including one set in `OTEL_RESOURCE_ATTRIBUTES`; there the
365
+ logged id is the one sent, with the exceptions below. In either mode, a
366
+ `run()` that passes `agentName` when no use-case id or key is configured
367
+ (and, in host mode, no resource `mainwave.ucid` is kept) sends an id derived
368
+ from `<serviceName>/<agentName>` that no line logs; set a `useCaseId` or
369
+ `useCaseKey` (section 7) before verifying. A `run()` that is not nested in
370
+ another run (a nested run ignores identity options and logs a warning) or a
371
+ `bindIdentity()` that passes its own `useCaseId` or `useCaseKey` sends that
372
+ id instead of the logged one; `useCaseIdFor(key)` returns a key's id. Run
373
+ `verify` for each id the work sends.
374
+ 2. Start the watcher **before** the application does its work, in the
375
+ background or a second terminal, with the id the code actually sends:
376
+
377
+ ```bash
378
+ npx @mainwave/cli@latest verify --ucid <use-case-id> --no-sample --timeout 300
379
+ ```
380
+
381
+ 3. While it is watching, run the application so it does real work.
382
+
383
+ `--no-sample` is required here. Without it the CLI pushes its own synthetic
384
+ trace, which proves the network path but would pass even if the instrumentation
385
+ does nothing. The command counts only spans that start after the command
386
+ starts, so a run made before it began is not seen: for a script, job or
387
+ one-off run, starting `verify` second times out on a working install. It
388
+ watches for 60 s unless `--timeout <seconds>` is given. It reads as the
389
+ signed-in Mainwave user, so make sure the CLI is signed in to the same
390
+ organization as the API key.
391
+
392
+ If nothing arrives, work `reference/troubleshooting.md`.
393
+
394
+ ## Guardrails
395
+
396
+ - **Never put a key in source or a committed file.**
397
+ - **Never install an OpenInference or Traceloop package**, and do not leave one
398
+ wired beside the SDK.
399
+ - **Never let instrumentation change application behavior.** No swapped
400
+ clients, no altered control flow. The SDK never throws into the app after
401
+ `init()` except for invalid caller input; `MAINWAVE_DISABLED=true` turns it
402
+ into a no-op if it must be switched off.
403
+ - **Do not restructure the app to fit the SDK.** If the code has no clean unit
404
+ of work, add a run at the outermost sensible boundary and say so.
405
+ - Content (messages, tool definitions, reasoning) is captured by default. If the
406
+ user handles sensitive data, say so and offer `captureContent: false`; do not
407
+ decide for them.
408
+
409
+ ## Reference
410
+
411
+ - `reference/api.md` - the public surface: exports, options, environment variables.
412
+ - `reference/frameworks.md` - per-framework wiring, supported versions, and what each path covers.
413
+ - `reference/troubleshooting.md` - "no spans are showing up", in the order the causes occur.
414
+
415
+ ## Report at the end
416
+
417
+ Tell the user which files changed, which path you chose (eve, host, owned) and
418
+ why, the attach path for each provider client, the run boundary, the use-case
419
+ identity used, and the verification result. If you guessed at the unit of work
420
+ or the use case, say so plainly: that is the decision they should check.
@@ -0,0 +1,96 @@
1
+ # @mainwave/sdk: public surface
2
+
3
+ Everything importable from `@mainwave/sdk` and its subpaths. Anything else in
4
+ the package is internal: do not import from `dist/` paths.
5
+
6
+ ## Root exports (`@mainwave/sdk`)
7
+
8
+ | Export | Use |
9
+ | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
10
+ | `init(options)` | Owned mode: build a tracer provider and export every LLM trace. Once per process. Throws `MainwaveConfigError` for a missing key |
11
+ | `createSpanProcessor(options)` | Host mode: one processor to pass to the host's provider. Same options as `init()` except `mode` |
12
+ | `run(runId, [options], fn)` | A run around a block; resolves with what `fn` returns |
13
+ | `startRun(runId, [options])` | A run you end yourself; bind a block with `handle.with(fn)`; `handle.end({ status, description, reason, decision, iterations, cost })` |
14
+ | `span(name, [{ attributes }], fn)` | A custom span; `fn` gets the OpenTelemetry `Span` |
15
+ | `bindIdentity({ useCaseId, useCaseKey, agentName }, fn)` | Bind a use case and agent name to every span started inside `fn` |
16
+ | `instrument({ openai, anthropic })` | Attach to the module(s) passed; returns `'patched'`, `'already'` or `'unrecognized'` per client; never throws |
17
+ | `flush({ timeoutMs })` | Send everything buffered; resolves `true` when accepted, `false` otherwise; never rejects. Default 30,000 ms |
18
+ | `shutdown()` | Flush, shut the provider or processor down, remove the SDK's listeners; safe to call twice |
19
+ | `useCaseIdFor(key)` | The UUID a key derives to; throws `MainwaveConfigError` before `init()` or `createSpanProcessor()`, or when disabled |
20
+ | `registerFramework(name, [version])`, `VERSION` | Record a framework name on exported spans (for a custom integration); package version |
21
+ | `MainwaveError`, `MainwaveConfigError`, `MainwaveReinitConflict` | Error classes. Config errors are invalid caller input; reinit conflict is a second `init()` with a different configuration |
22
+
23
+ Before `init()` or `createSpanProcessor()`, `run()`, `startRun()`, `span()` and
24
+ `bindIdentity()` run their callbacks without telemetry and log one warning.
25
+
26
+ ## Subpaths
27
+
28
+ | Import | Provides |
29
+ | ------------------------- | --------------------------------------------------------------------------------- |
30
+ | `@mainwave/sdk/register` | Loader hooks for `node --import`; patches `openai` and `@anthropic-ai/sdk` |
31
+ | `@mainwave/sdk/eve` | `mainwave(options)`: the eve instrumentation destination |
32
+ | `@mainwave/sdk/ai-sdk` | `mainwaveTelemetry(options)`: the AI SDK v7 integration for `registerTelemetry` |
33
+ | `@mainwave/sdk/openai` | `OpenAIInstrumentation` class, for hosts that register their own instrumentations |
34
+ | `@mainwave/sdk/anthropic` | `AnthropicInstrumentation` class, same |
35
+ | `@mainwave/sdk/testing` | `installInMemoryProvider(options)`, `reset()`: in-process span assertions |
36
+
37
+ ## `init()` options
38
+
39
+ Each option has an environment variable; an option wins over its variable. A
40
+ value of the wrong type throws `MainwaveConfigError` naming the option.
41
+
42
+ | Option | Variable | Default |
43
+ | ----------------------- | ---------------------------------------------------- | -------------------------------- |
44
+ | `apiKey` | `MAINWAVE_API_KEY` | none; required unless disabled |
45
+ | `useCaseId` | `MAINWAVE_USE_CASE_ID` | none |
46
+ | `useCaseKey` | `MAINWAVE_USE_CASE_KEY` | none |
47
+ | `ucidNamespace` | `MAINWAVE_UCID_NAMESPACE` | none |
48
+ | `collectorUrl` | `MAINWAVE_COLLECTOR_URL` | `https://collector.mainwave.com` |
49
+ | `serviceName` | `OTEL_SERVICE_NAME` | `mainwave-app` |
50
+ | `deploymentEnvironment` | `MAINWAVE_ENVIRONMENT` | `production` |
51
+ | `disabled` | `MAINWAVE_DISABLED` | `false` |
52
+ | `captureContent` | `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` | `SPAN_ONLY` (content on) |
53
+ | `logLevel` | `MAINWAVE_LOG_LEVEL` | `warn` |
54
+ | `mode` | none | `auto` |
55
+ | `handleSignals` | `MAINWAVE_HANDLE_SIGNALS` | `false` |
56
+ | `skipInstrumentations` | none | none |
57
+
58
+ - `mode`: `auto` is owned mode unless another tracer provider is already
59
+ registered, in which case it falls back to host mode, exports nothing, and
60
+ logs one warning until `createSpanProcessor()` is wired into the host.
61
+ - `useCaseId` and `useCaseKey` as options in the same call throw
62
+ `MainwaveConfigError`.
63
+ - `useCaseId` (or `MAINWAVE_USE_CASE_ID`) must be the use case's UUID as shown
64
+ in the Mainwave app. Anything else (a use-case key, a pasted API key, a UUID
65
+ with surrounding spaces) throws `MainwaveConfigError` from `init()` and
66
+ `createSpanProcessor()` unless the SDK is disabled; `mainwave()` logs one
67
+ error and returns an integration with no processors. To name a use case, set
68
+ `useCaseKey`.
69
+ - A `useCaseId` on `run()`, `startRun()` or `bindIdentity()` that is not a UUID
70
+ is ignored with one warning; spans keep the use case bound around the run
71
+ or block, else the process use case.
72
+ - `collectorUrl`: an `http://` URL to a host that is not loopback (`localhost`,
73
+ `*.localhost`, `127.x.x.x`, `[::1]`) logs one warning, since the API key and
74
+ span data cross the network unencrypted.
75
+ - `captureContent: false` removes every message, instruction, tool definition,
76
+ and reasoning body from exported spans; model, token counts, finish reasons,
77
+ and errors still arrive.
78
+ - `MAINWAVE_DISABLED`: `1`, `true`, `yes`, `on` disable; `0`, `false`, `no`,
79
+ `off` or empty enable; anything else throws `MainwaveConfigError`.
80
+ - `MAINWAVE_LOG_LEVEL`: `error`, `warn`, `info`, `debug`. Logs go to stderr with
81
+ the prefix `mainwave: `.
82
+
83
+ `mainwave(options)` from `@mainwave/sdk/eve` takes the same options except
84
+ `mode`, plus `runAttributes`, `modelAliases` and `exportPolicy`.
85
+
86
+ ## Identity precedence (innermost first)
87
+
88
+ 1. `useCaseId` on `run()` or `bindIdentity()`.
89
+ 2. `useCaseKey` on `run()` or `bindIdentity()`.
90
+ 3. `useCaseId`, else `useCaseKey`, on `init()` or the environment.
91
+ 4. Host mode with nothing above: a valid UUID `mainwave.ucid` on the host's resource.
92
+ 5. `agentName` on a run: derived from `<serviceName>/<agentName>`.
93
+ 6. Nothing configured: derived from `serviceName`.
94
+
95
+ Keys are case-sensitive and trimmed; an empty key or one longer than 256
96
+ characters is invalid.
@@ -0,0 +1,82 @@
1
+ # Per-framework wiring
2
+
3
+ Supported ranges are the optional peer dependencies the application installs.
4
+ A version outside its range is not instrumented and logs one warning with the
5
+ package, version, and range: report it to the user instead of wiring around it.
6
+
7
+ | Framework | Range | Wiring |
8
+ | ------------- | ---------------------------------- | ------------------------------------------------------ |
9
+ | eve | `>=0.66.3 <0.70.0`, Node 24+ | `mainwave()` from `@mainwave/sdk/eve`; no `init()` |
10
+ | Vercel AI SDK | `ai` `^7` with `@ai-sdk/otel` `^1` | `registerTelemetry(mainwaveTelemetry())` |
11
+ | OpenAI | `openai` `>=4.19.0 <8` | loader flag, `instrument({ openai })`, or the class |
12
+ | Anthropic | `@anthropic-ai/sdk` `>=0.51.0 <1` | loader flag, `instrument({ anthropic })`, or the class |
13
+
14
+ AI SDK v5 and v6 are not supported.
15
+
16
+ ## eve
17
+
18
+ One file, `agent/instrumentation/mainwave.ts`, default-exporting `mainwave()`.
19
+ Each eve turn becomes one run named `mainwave.run`. eve's trace policy decides
20
+ content: in production eve records no content for private conversations by
21
+ default, so those runs show no input, output, or reasoning. `captureContent`
22
+ can only remove content from what eve sends. To label outcomes while content is
23
+ withheld, `runAttributes: (turn) => ...` returns `{ output, decision, reason,
24
+ iterations, cost, metadata }` labels (never message text or user identifiers),
25
+ synchronously.
26
+
27
+ ## Vercel AI SDK v7
28
+
29
+ Register once, after `init()` or after `createSpanProcessor()` is wired into the
30
+ host's provider. It covers `generateText`, `streamText` (the `invoke_agent`,
31
+ step, `chat <model>` and `execute_tool` spans) and `embed`. Model calls through
32
+ `@ai-sdk/amazon-bedrock` are reported with provider `aws.bedrock`. In an eve app
33
+ `mainwaveTelemetry()` returns an integration with no callbacks and logs one
34
+ warning. Importing `@mainwave/sdk/ai-sdk` without `ai` or `@ai-sdk/otel`
35
+ installed fails at import with `ERR_MODULE_NOT_FOUND` naming the package.
36
+
37
+ ## OpenAI
38
+
39
+ Traces Chat Completions, Responses, and Embeddings calls and the helpers built
40
+ on them (`chat.completions.parse()`, `chat.completions.stream()`, `runTools()`,
41
+ `responses.parse()`, `responses.stream()`). A client pointed at another
42
+ OpenAI-compatible service through `baseURL` is reported with provider `openai`
43
+ and that service's host and port. The instrumentation keeps the content setting
44
+ in effect when it first attaches: content turned on later stays off until the
45
+ process restarts.
46
+
47
+ ## Anthropic
48
+
49
+ Traces every Messages API call: `messages.create()` with or without
50
+ `stream: true`, `messages.stream()`, `messages.parse()`, `beta.messages.create()`,
51
+ `beta.messages.stream()`, and each model turn of `beta.messages.toolRunner()`.
52
+ `countTokens()`, batches, models, and files make no span. A redacted thinking
53
+ block is recorded as `[redacted thinking]`.
54
+
55
+ ## Attach paths for OpenAI and Anthropic
56
+
57
+ 1. `node --import @mainwave/sdk/register app.mjs` (or `NODE_OPTIONS`): static
58
+ imports, dynamic `import()`, and `require()`. For plain Node processes.
59
+ 2. `instrument({ openai, anthropic })`: bundled apps and serverless functions
60
+ (Vercel Functions, Next.js). Call it after `init()` in owned mode, or after
61
+ the host wiring in host mode, where `createSpanProcessor()` is the
62
+ initialization and `init()` is not called (a bare `init()` after it throws
63
+ `MainwaveReinitConflict`). Pass every copy the app loads; an ES module import
64
+ and a `require()` result are different copies.
65
+ 3. The `OpenAIInstrumentation` / `AnthropicInstrumentation` classes, for a host
66
+ that calls `registerInstrumentations`. ES module imports are then
67
+ intercepted by the host's own OpenTelemetry loader, registered before the
68
+ application starts.
69
+
70
+ A copy attached by two of these ways is instrumented once. Do not add an
71
+ OpenInference or Traceloop instrumentation for these clients: the SDK has its
72
+ own, and a second one traces every call twice. Where one is already installed
73
+ by the app, set `init({ skipInstrumentations: [...] })` for that client instead
74
+ of removing the app's choice, and tell the user.
75
+
76
+ ## No supported framework
77
+
78
+ If the repo calls none of the above, use owned mode with manual `run()` and
79
+ `span()`. Say that no framework wiring applies. A trace made only of HTTP or
80
+ database spans is dropped. A `run()`, an SDK `span()`, or a span carrying
81
+ `gen_ai.*` attributes keeps its trace; a span from the app's own tracer must
82
+ sit inside a `run()` or `span()`.