@cultured_computer/sight 0.8.0 → 0.8.1

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/README.md CHANGED
@@ -1,11 +1,17 @@
1
1
  # Sight
2
2
 
3
- The capture SDK and CLI for Sight. It records one turn per model call made
4
- inside a session scope: the person's message, the reply it prompted, the
5
- plumbing (model, tokens, latency, tool names, finish reason, cost when
6
- reported). Capture is out of band; responses are never modified or
7
- delayed. The record is one published, versioned shape. Docs:
8
- https://sight.cultured.computer/docs
3
+ The capture SDK and CLI for Sight. It records each model call your assistant
4
+ makes inside a session as one turn (the person's message, the reply, model,
5
+ tokens, latency) and sends it to the Sight API without changing or delaying
6
+ the response.
7
+
8
+ Full documentation: https://sight.cultured.computer/docs
9
+
10
+ ## Requirements
11
+
12
+ - Node 20.6 or later. Server-side only; never ship the key to a browser.
13
+ - A Sight API key with the `ingest` capability, set as `SIGHT_API_KEY`.
14
+ - TypeScript types, an ESM build and a CommonJS build are included.
9
15
 
10
16
  ## Install
11
17
 
@@ -13,37 +19,18 @@ https://sight.cultured.computer/docs
13
19
  npm install @cultured_computer/sight
14
20
  ```
15
21
 
16
- Requirements:
17
-
18
- - Node 20.6 or later.
19
- - Server-side Node only; never ship the key to a browser.
20
- - TypeScript types ship with the package. ESM and CommonJS builds are both
21
- included.
22
-
23
22
  ## Quickstart
24
23
 
25
- A complete example that captures one turn per model call:
26
-
27
24
  ```ts
28
25
  import OpenAI from "openai";
29
26
  import { Sight, wrapOpenAI } from "@cultured_computer/sight";
30
27
 
31
- Sight.init({
32
- apiKey: process.env.SIGHT_API_KEY!,
33
- deployment: "my-assistant",
34
- });
35
-
28
+ Sight.init({ apiKey: process.env.SIGHT_API_KEY!, deployment: "my-assistant" });
36
29
  const openai = wrapOpenAI(new OpenAI());
37
30
 
38
- export async function reply(
39
- conversationId: string,
40
- userId: string,
41
- userMessage: string,
42
- ): Promise<string> {
43
- Sight.startSession({ externalId: conversationId, externalUserId: userId });
31
+ export async function reply(conversationId: string, userMessage: string) {
44
32
  // The person's message. It is sent with the turn captured next.
45
33
  Sight.userInputSubmit(conversationId, userMessage);
46
-
47
34
  // A model call is captured only inside a session scope.
48
35
  return Sight.withSession(conversationId, async () => {
49
36
  const res = await openai.chat.completions.create({
@@ -55,391 +42,107 @@ export async function reply(
55
42
  }
56
43
  ```
57
44
 
58
- On the first accepted turn the SDK prints one line on stderr with a link to
59
- the session in the dashboard.
60
-
61
- Notes:
62
-
63
- - `apiKey` is a key with the `ingest` capability (access word `ingest`,
64
- `both` or `app`), minted by an owner on the dashboard's API Keys page
65
- (shown once) and set as `SIGHT_API_KEY`. Sign-in is allowlisted; without
66
- a dashboard, redeem a provisioning token with `sight account create`.
67
- The endpoint defaults to `https://fieldwork-ingest.fly.dev`; override it
68
- with `endpoint` only for self-hosting or staging.
69
- - `init` runs once at startup. `deployment` identifies the configuration this
70
- traffic belongs to; all measurement is per deployment.
71
- - `Sight.withSession(id, fn)` is required for autocapture. `id` is the
72
- session's external id (one conversation). A model call made outside any
73
- session scope is not captured. The first such call in a process prints one
74
- warning naming `Sight.withSession(id, fn)`; later ones log only with
75
- `debug: true`.
76
- - `startSession` is optional. Use it to attach `externalUserId`, a stable,
77
- pseudonymous user id you supply. Return metrics key on the user id;
78
- sessions without it still capture, but return behaviour is not computable.
79
- - `wrapOpenAI` does not read the person's message from the request. Record
80
- it with `Sight.userInputSubmit(sessionId, text)` before the model call.
81
-
82
- ## Headless project setup
83
-
84
- Provider setup requires an explicitly issued **management** provisioning token
85
- (`--access manage`), not an ordinary ingest, Studio, or combined token. It grants
86
- only `providers:write`, allowing provider-key replacement and budget changes.
87
- With that administrative token, connect your own OpenRouter key without a browser:
88
-
89
- ```bash
90
- export SIGHT_PROVISION_TOKEN='<one-time management token from Sight>'
91
- export OPENROUTER_API_KEY='<your OpenRouter API key>'
92
-
93
- npx @cultured_computer/sight account create --openrouter --budget 25
94
- ```
95
-
96
- The provisioning token and OpenRouter key are read only from the environment,
97
- not command-line arguments. The Sight key is returned once and saved to
98
- `~/.config/sight/machine.json` with mode `0600`; it is never printed. Sight
99
- checks the OpenRouter key against OpenRouter, seals it before database storage,
100
- and records the monthly budget. Check the safe, redacted state later with:
101
-
102
- ```bash
103
- npx @cultured_computer/sight openrouter status
104
- ```
105
-
106
- If OpenRouter setup fails after account creation, the Sight credential remains
107
- saved. Fix the key or budget and retry only that step:
108
-
109
- ```bash
110
- export OPENROUTER_API_KEY='<your OpenRouter API key>'
111
- npx @cultured_computer/sight openrouter connect --budget 25
112
- ```
113
-
114
- For an existing project, ask its owner for a separate **Provider administration
115
- only** key, or have the operator mint one with `scripts/mint-key.mjs --access manage`.
116
- Set it as `SIGHT_API_KEY` for `openrouter connect`. Use a separate `studio` or
117
- `both` key for execution; management keys do not authorize runs or ingest.
118
- Existing tokens and keys are never upgraded. An ordinary provisioning token
119
- can still be redeemed with `account create` without `--openrouter`.
120
- Redemption is one-time for the project, so a second provisioning token cannot
121
- add an execution key after admin provisioning. The owner must mint the separate
122
- ingest/Studio key in API Keys after claiming the project, or the operator must
123
- mint it with `scripts/mint-key.mjs --access ingest`, `studio`, or `both`.
124
-
125
- Use `SIGHT_API_KEY` from your secret manager in the application process. The
126
- local `machine.json` is a CLI credential store, not a project `.env` file and
127
- is never copied into your repository automatically.
128
-
129
- ## Pull your own data out: the CLI, from your terminal
130
-
131
- The `sight` CLI also carries out data from projects you **own**, with no
132
- dashboard click-through and no session cookie to juggle. Sign the terminal in
133
- once against the browser session you already hold, then export any deployment
134
- you own as RLDS JSONL:
135
-
136
- ```bash
137
- # one-time: sign this terminal in (prints a code, opens your browser to approve)
138
- npx @cultured_computer/sight auth login
139
-
140
- # then pull a deployment's full record
141
- npx @cultured_computer/sight export --project <slug> --deployment <slug> --out data.jsonl
142
-
143
- # or pull the readings: the per-turn judge labels (closure, backward-pass, ...)
144
- npx @cultured_computer/sight export --project <slug> --deployment <slug> --readings --out readings.jsonl
145
-
146
- # sign out when you're done
147
- npx @cultured_computer/sight auth logout
148
- ```
149
-
150
- - `auth login` prints a short code and opens your browser to the `/device`
151
- approval page (RFC 8628 device authorization). You approve as yourself on a
152
- browser you are already signed into: same identity, same role, same rules as
153
- your dashboard session. The token is stored at
154
- `~/.config/sight/credentials.json` (mode `0600`).
155
- - `export` streams the deployment's sessions and turns as RLDS JSONL, the same
156
- Tier-2 redacted shape the dashboard produces. It is owner-only: the token is
157
- your session, so the carry-out gate is exactly the dashboard's. Members read
158
- in-product; owners carry the dataset out.
159
- - `--readings` pulls the graded reads instead of the record: one line per
160
- per-turn judge label (closure, backward-pass, and the rest), with the rubric
161
- version and judge-model pin. These are the re-computable evidence layer over
162
- the record, not part of the versioned record schema.
163
- - `--out <file>` writes to a file; omit it to stream to stdout.
164
-
165
- One more CLI door, for a different shape: `sight connect` attaches Sight to a
166
- buzz community you don't serve as a read-only observer (invite-code
167
- authorization, no account needed up front). A side lane, not the install:
168
- the walkthrough lives at
169
- [Connect your buzz community](https://sight.cultured.computer/docs/connect-your-room).
170
-
171
- ## What autocapture records
172
-
173
- Autocapture turns each model call made inside `Sight.withSession(id, fn)`
174
- into one turn. There are three paths. A model call seen by more than one
175
- path is one turn.
176
-
177
- ### OpenAI: wrap the client
178
-
179
- The path to use for OpenAI. It does not depend on module format, load
180
- order, or the `openai` version.
181
-
182
- ```ts
183
- const openai = wrapOpenAI(new OpenAI());
184
- // Wrap before or after Sight.init(); order does not matter.
185
- ```
186
-
187
- Covers `chat.completions.create` and `responses.create`, streaming included.
188
-
189
- Provider is read from the client's `baseURL`:
190
-
191
- | `baseURL` host | Provider |
192
- |---|---|
193
- | none, or `api.openai.com` | `openai` |
194
- | `openrouter.ai` | `openrouter` |
195
- | `*.openai.azure.com` | `azure` |
196
- | `*.inceptionlabs.ai`, or a model name starting with `mercury` | `inception` |
197
- | any other host | not sent |
198
-
199
- A streamed call through a wrapped client also records:
200
-
201
- - First-token time: milliseconds from the start of the request to the first
202
- chunk that carries output. Chat Completions: a non-empty
203
- `delta.content`, a non-empty `delta.refusal`, or a `delta.tool_calls`
204
- entry. The opening chunk that carries only the role is not a token.
205
- Responses API: the first `response.output_text.delta`,
206
- `response.refusal.delta` or `response.function_call_arguments.delta`, or
207
- a `response.output_item.added` whose item is a `function_call`.
208
- - Tool names and count of streamed tool calls.
209
-
210
- A call that is not streamed has no first-token time; the field is not sent.
211
- A stream that ends before any output has none either.
212
-
213
- ### Vercel AI SDK (`ai`)
214
-
215
- Verified with `ai` 7.0.17 (telemetry integration) and `ai` 6.0.300
216
- (OpenTelemetry spans). `ai` 3 to 5 are not verified.
217
-
218
- `ai` 7: nothing to add. `init` registers a telemetry integration with `ai`,
219
- and `ai` 7 sends every call to a registered integration; no per-call flag.
220
-
221
- ```ts
222
- import { generateText } from "ai";
223
-
224
- Sight.init({ apiKey: process.env.SIGHT_API_KEY!, deployment: "my-assistant" });
225
-
226
- await Sight.withSession(conversationId, () =>
227
- generateText({ model, system, messages }),
228
- );
229
- ```
230
-
231
- Covers `generateText`, `streamText`, `generateObject`, `streamObject` and
232
- `ToolLoopAgent`.
233
-
234
- - Turn unit: one model call. A tool loop of N model calls is N turns. Each
235
- carries the text of that reply (none when the model only requested tools)
236
- and the names of the tools it requested. The outer `generateText` call is
237
- not a turn.
238
- - Streaming: one turn when the model call's stream ends, with the full text
239
- and the time to the first output. A stream nobody reads captures nothing.
240
- - A model call that throws is one turn with the error message and no reply.
241
- An aborted stream is one turn with error `aborted` and no reply. A stream
242
- that fails part way is one turn with the partial text, finish reason
243
- `error` and an error field.
244
- - `generateObject` and `streamObject`: the reply is the JSON text the model
245
- produced.
246
- - Session: the `Sight.withSession` scope the call started in. Outside any
247
- scope, name the session on the call, either way:
248
-
249
- ```ts
250
- import { sightTelemetry } from "@cultured_computer/sight";
251
-
252
- // 1. On the integration, for this call.
253
- generateText({
254
- model,
255
- prompt,
256
- telemetry: { integrations: sightTelemetry({ sessionId: conversationId }) },
257
- });
258
-
259
- // 2. In runtimeContext. `ai` passes a runtimeContext key to telemetry only
260
- // when includeRuntimeContext names it. Keys read: sightSessionId, then
261
- // sessionId.
262
- generateText({
263
- model,
264
- prompt,
265
- runtimeContext: { sightSessionId: conversationId },
266
- telemetry: { includeRuntimeContext: { sightSessionId: true } },
267
- });
268
- ```
269
-
270
- An explicit scope wins over both. `telemetry.integrations` on a call
271
- replaces the registered integrations for that call (an `ai` rule): to keep
272
- another integration on that call, list it next to `sightTelemetry(...)`.
273
- With no scope and no session id the call is skipped and the one
274
- no-session warning prints.
275
- - `telemetry: { isEnabled: false }` on a call turns capture off for it.
276
- `recordOutputs: false` drops the reply text. `recordInputs: false` drops
277
- the person's message and the system prompt hash.
278
- - Registration: `init` loads `ai` and calls its `registerTelemetry()`.
279
- On Node 22.13 or later (`ai` 7 itself needs Node 22) this is done before
280
- `init` returns. On older Node it completes a moment later and a call made
281
- in the same tick as `init` is missed. If the SDK cannot resolve your `ai` (some bundles), register it
282
- yourself, once:
283
-
284
- ```ts
285
- import { registerTelemetry } from "ai";
286
- import { sightTelemetry } from "@cultured_computer/sight";
287
-
288
- registerTelemetry(sightTelemetry());
289
- ```
290
-
291
- Registering both ways is safe: it is registered once.
292
- - With `@ai-sdk/otel` also registered, the span it emits for a model call
293
- and the Sight integration's turn are one turn (matched on the provider
294
- response id).
295
-
296
- What an `ai` 7 turn carries: reply text (text parts only; reasoning, tool
297
- input and tool output are never part of it), the model id the provider
298
- returned, the provider id as `ai` names it (for example `openai.responses`),
299
- input and output tokens, cache read and cache write tokens, tool names and
300
- count, finish reason, the model call's response time, time to first output
301
- for streams, the person's message (same rule as below), a `turnId`.
302
- Not carried: cost; the error message of a stream that fails part way (the
303
- events do not include it); the partial text of an aborted stream.
304
-
305
- `ai` 6: it sends no events to the integration's model-call hooks. It emits
306
- OpenTelemetry spans, and only for calls that set the flag:
307
-
308
- ```ts
309
- await Sight.withSession(conversationId, () =>
310
- generateText({ model, prompt, experimental_telemetry: { isEnabled: true } }),
311
- );
312
- ```
313
-
314
- The span processor (next section) captures its model-call spans:
315
- `ai.generateText.doGenerate`, `ai.streamText.doStream`,
316
- `ai.generateObject.doGenerate`, `ai.streamObject.doStream`. Same turn unit.
317
- The outer `ai.generateText` span and `ai.toolCall` spans are not turns.
318
- Outside a scope, the session id is read from
319
- `experimental_telemetry.metadata.sightSessionId`, then `.sessionId`.
320
-
321
- ### Instrumented libraries: OpenTelemetry spans
322
-
323
- From `init`, the SDK enables module instrumentation for the OpenAI SDK, the
324
- Anthropic SDK and LangChain (LangGraph runs through the LangChain
325
- instrumentation), and captures the model-call spans they emit. Each adapter
326
- does nothing if its library is not installed.
327
-
328
- Limits:
329
-
330
- - OpenAI module patching attaches only under CommonJS, only when `openai`
331
- loads after `init`, and only for openai v4. If it did not attach and no
332
- client has been wrapped, the SDK prints one warning at startup. Under ESM
333
- or openai v5 and later, wrap the client.
334
- - Anthropic module patching has the same CommonJS and load-order limits and
335
- no startup check. Confirm capture with `debug: true`.
336
- - LiteLLM (Python) is not captured.
337
-
338
- Any OpenTelemetry instrumentation that emits GenAI spans through the global
339
- tracer provider is captured the same way. A span becomes a turn when
340
- `gen_ai.operation.name` is `chat`, `generate_content` or `text_completion`,
341
- or when it is one of the `ai` 6 model-call spans named above (identified by
342
- `ai.operationId`). Spans for `embeddings`, `invoke_agent`, `create_agent`,
343
- workflows and `execute_tool` are not turns.
344
-
345
- Attributes read from a span (the current name first, then the fallbacks):
346
-
347
- | Field | Attributes |
348
- |---|---|
349
- | Provider | `gen_ai.provider.name`, `gen_ai.system`, `gen_ai.provider`, `ai.model.provider` |
350
- | Model | `gen_ai.response.model`, `ai.response.model`, `gen_ai.request.model`, `ai.model.id` |
351
- | Requested model | `gen_ai.request.model`, `ai.model.id` |
352
- | Cost | `gen_ai.usage.cost` |
353
- | Reply text | `ai.response.text` when present; otherwise the text parts of `gen_ai.output.messages`; otherwise `ai.response.object` |
354
- | The person's message | last user message of `gen_ai.input.messages`, or of `ai.prompt.messages` |
355
- | Input tokens | `gen_ai.usage.input_tokens`, `gen_ai.usage.prompt_tokens`, `ai.usage.inputTokens`, `ai.usage.promptTokens` |
356
- | Output tokens | `gen_ai.usage.output_tokens`, `gen_ai.usage.completion_tokens`, `ai.usage.outputTokens`, `ai.usage.completionTokens` |
357
- | Cache read tokens | `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_read_input_tokens`, `ai.usage.inputTokenDetails.cacheReadTokens`, `ai.usage.cachedInputTokens` |
358
- | Cache creation tokens | `gen_ai.usage.cache_creation.input_tokens`, `gen_ai.usage.cache_creation_input_tokens`, `ai.usage.inputTokenDetails.cacheWriteTokens` |
359
- | Tool names and count | `tool_call` parts of `gen_ai.output.messages`; `toolName` of each entry in `ai.response.toolCalls`; child `execute_tool` spans (`gen_ai.tool.name`); `gen_ai.response.tool_names`, `gen_ai.response.tool_calls_count` |
360
- | Finish reason | first of `gen_ai.response.finish_reasons`, `ai.response.finishReason` |
361
- | Time to first token | `ai.response.msToFirstChunk`, `ai.stream.msToFirstChunk` |
362
- | Session (fallback) | `gen_ai.conversation.id`, `ai.telemetry.metadata.sightSessionId`, `ai.telemetry.metadata.sessionId` |
363
-
364
- Rules:
365
-
366
- - Session: the `Sight.withSession` scope first. With no scope, the first
367
- session attribute in the table that the span carries is the session id.
368
- - A span is not a second turn for a model call another path captures: a
369
- span started inside an `ai` 7 model call that the Sight integration
370
- handles is skipped, and so is a span whose `gen_ai.response.id` (or
371
- `ai.response.id`) the integration reported for the same call. A wrapped
372
- OpenAI client called inside such a model call passes through uncaptured.
373
- Not covered: two instrumentations that both emit a span for one call
374
- outside `ai` (for example a patched and a wrapped OpenAI client used
375
- together); those are two turns.
376
- - The person's message is sent as `userInput.text` only when the request's
377
- last message is the person's and carries text, and only when no text
378
- recorded with `userInputSubmit` is pending for that turn. Explicit input
379
- wins. A turn's person text is the message that prompted its reply.
380
- - The reply is stored as plain text. A structured message array is parsed;
381
- reasoning and tool parts are not part of the reply text.
382
-
383
- ### Fields on every autocaptured turn
384
-
385
- Model, provider, input and output tokens, latency, tool names and count,
386
- finish reason, error message, cache read tokens when the provider reports
387
- them, the reply text, the requested model, a `turnId`.
388
-
389
- First-token time: sent for a streamed call through a wrapped OpenAI client
390
- and for an `ai` stream. Not sent for a call that is not streamed, and not
391
- sent by the bundled OpenAI, Anthropic and LangChain instrumentations, which
392
- do not report it on the span.
393
-
394
- Cost, in this order:
395
-
396
- 1. Reported by the provider. When the response usage carries a cost
397
- (OpenRouter's `usage.cost`; `gen_ai.usage.cost` on a span), the SDK sends
398
- it and the turn stores it as reported. A reported cost of 0 is stored
399
- as 0. On an OpenRouter bring-your-own-key call the cost is sent only
400
- when `cost_details.upstream_inference_cost` is reported too, as the sum
401
- of the two. The `ai` 7 integration sends no cost.
402
- 2. Estimated from the price catalogue. With no reported cost, the server
403
- computes the cost from the turn's token counts when the turn's provider
404
- and model name exactly one catalogue price in effect at the turn's time.
405
- The match is exact string equality on provider and model: the response
406
- model first, then the requested model (OpenRouter turns: the response
407
- model only). Cached tokens are priced at the catalogue's cached rate.
408
- The estimate is a list price, not a billed amount.
409
- 3. Unavailable. In every other case the turn has no cost: no token counts,
410
- an unknown provider or model, more than one matching catalogue entry,
411
- no price in effect at the turn's time, or cached tokens with no cached
412
- rate in the catalogue or no known counting convention. An unavailable
413
- cost is empty, never 0.
414
-
415
- Each turn records which of the three applied on its `probe_meta`:
416
- `costSource` is `provider` or `catalogue:<price version id>`, or absent
417
- with `costUnavailable` naming the reason.
418
-
419
- Not sent by autocapture: reasoning tokens.
420
-
421
- ### Delivery
422
-
423
- - Capture never blocks your LLM path. Send failures log in debug mode and
424
- are otherwise swallowed.
425
- - Invalid input to any capture method logs one warning line naming the
426
- first invalid field and is dropped.
427
- - A rate-limited send (429) is retried once after `Retry-After`.
428
- - Sessions are created lazily on the first captured turn.
429
-
430
- ## Capture a turn manually
45
+ After the first accepted turn, stderr prints one line with a link to the
46
+ session: `Sight: first session captured -> <url>`.
47
+ Walkthrough: [Get started](https://sight.cultured.computer/docs/get-started).
48
+
49
+ ## What you must do for a turn to be captured
50
+
51
+ | Step | Call | Without it |
52
+ | --- | --- | --- |
53
+ | Initialise once at startup | `Sight.init({ apiKey, deployment })` | Nothing is captured. `init` throws on an invalid configuration; no other Sight call throws on bad input. |
54
+ | Scope each conversation | `Sight.withSession(id, fn)` around the model call; `id` is your conversation id | The call is not captured. The first such call in a process prints one warning. |
55
+ | Record the person's message | `Sight.userInputSubmit(id, text)` before the model call | A wrapped OpenAI client's turn has no person's message. The span and `ai` paths read the last user message of the request. |
56
+ | Use a key that may send | A key with the `ingest` capability (access `ingest`, `both` or `app`) | The API answers `403` and the turn is dropped. One warning prints. |
57
+
58
+ - `Sight.withSession(id, fn)` is required for autocapture.
59
+ - `deployment` names the configuration the traffic belongs to. The API host
60
+ defaults to `https://api.cultured.computer`; set `endpoint` only for a
61
+ self-hosted or staging API.
62
+ - Keys are created by a project owner on the dashboard's API Keys page and
63
+ shown once. No dashboard access: ask the project owner for a key. See
64
+ [Keys and access](https://sight.cultured.computer/docs/keys-and-access).
65
+ - Optional: `Sight.startSession({ externalId, externalUserId })` attaches a
66
+ stable, pseudonymous user id, which ties one person's sessions together.
67
+
68
+ ## Capture paths
69
+
70
+ | Path | What you add | Verified with | What it sends that others do not |
71
+ | --- | --- | --- | --- |
72
+ | OpenAI client | `wrapOpenAI(new OpenAI())`, before or after `init` | Tests use stand-in clients for `chat.completions.create` and `responses.create`, streaming included; type-checked against `openai` 6.45.0 | First-token time on streams; cost when the response reports one (`usage.cost`); provider read from the client's `baseURL` |
73
+ | Vercel AI SDK, `ai` 7 | Nothing; `init` registers a telemetry integration | `ai` 7.0.17 | One turn per model call in a tool loop; cache write tokens; time to first output on streams. No cost is sent. |
74
+ | Vercel AI SDK, `ai` 6 | `experimental_telemetry: { isEnabled: true }` on each call | `ai` 6.0.300 | Time to first chunk on streams |
75
+ | OpenTelemetry GenAI spans | Any instrumentation that emits spans with `gen_ai.operation.name` of `chat`, `generate_content` or `text_completion` | Span fixtures in this package's tests | Cost from `gen_ai.usage.cost`; with no scope, the session id from `gen_ai.conversation.id` |
76
+ | OpenAI, Anthropic, LangChain module instrumentation | Nothing; `init` enables it. CommonJS only. | Not covered by this package's tests; confirm with `debug: true` | No first-token time |
77
+ | Anything else (LiteLLM, raw HTTP) | `Sight.captureTurn`, below | | |
78
+
79
+ - For OpenAI, wrap the client: it works under ESM and CommonJS, in any load
80
+ order.
81
+ - `ai` 3 to 5 are not verified.
82
+ - `ai` 7 outside a scope: pass `telemetry: { integrations: sightTelemetry({ sessionId }) }` on the call.
83
+ - An `ai` 7 model call that is also seen as a span or by a wrapped client is
84
+ one turn. A client that is both wrapped and module-patched sends one turn
85
+ per call, the wrapped client's: it has the first-token time and the
86
+ reported cost.
87
+ - Span capture uses the tracer provider `init` registers. If your process
88
+ registered a global tracer provider first, span capture may not attach;
89
+ the wrapped client and the `ai` 7 integration do not depend on it.
90
+
91
+ Details per path: [Integration paths](https://sight.cultured.computer/docs/integration-paths).
92
+
93
+ ## What every captured turn carries
94
+
95
+ | Field | Payload key | Sent when |
96
+ | --- | --- | --- |
97
+ | Reply text | `response.text` | The model returned text. Reasoning and tool arguments are not part of it. |
98
+ | The person's message | `userInput.text` | Recorded with `userInputSubmit`, or read from the request's last user message (span and `ai` paths). Explicit input wins. |
99
+ | Model, requested model | `probe_model`, `probe_request_model` | The path reports them (`ai` 7: model only) |
100
+ | Provider | `probe_provider` | Known. A wrapped client with an unrecognised `baseURL` sends none. |
101
+ | Input and output tokens | `probe_tokens_input`, `probe_tokens_output` | The provider reports usage |
102
+ | Cache read tokens | `probe_cache_read_input_tokens` | The provider reports them |
103
+ | Latency | `probe_latency_ms` | Autocapture measures it |
104
+ | First-token time | `probe_first_token_ms` | Wrapped OpenAI streams and `ai` streams only |
105
+ | Tool names and count | `probe_tool_names`, `probe_tool_calls` | The model requested tools |
106
+ | Finish reason, error | `probe_finish_reason`, `probe_error` | Reported, or the call failed |
107
+ | Cost | `probe_cost_usd` | The provider reports one. Otherwise the server estimates it from its price catalogue when the provider and model match one price; otherwise the turn has no cost (empty, never 0). |
108
+ | Turn identity | `turnId`, `turnIndex` | Always |
109
+
110
+ Every captured turn is sent with a `turnId`: a fresh UUID per turn. A retried
111
+ send carries the same `turnId`. `turnIndex` is a per-session counter held in
112
+ the process.
113
+
114
+ The exported record has a published JSON Schema, shipped in this package as
115
+ `@cultured_computer/sight/schema/record-v1`. See
116
+ [The record](https://sight.cultured.computer/docs/what-it-captures) and
117
+ [Data format](https://sight.cultured.computer/docs/data-format).
118
+
119
+ ## What is not sent
120
+
121
+ Autocapture does not send:
122
+
123
+ - Anything from a model call made outside a session scope.
124
+ - The system prompt text. Autocapture sends its SHA-256 hash as the session's
125
+ version tag, unless you set `environmentConfigHash` yourself.
126
+ - Earlier messages of the request. At most the last user message is read.
127
+ - Reasoning text, tool arguments and tool results. Tool names and a count are sent.
128
+ - Your provider API key and request headers.
129
+ - Turns excluded by `sampleRate` (default 1.0, every turn).
130
+
131
+ Text is sent as your process holds it. Personal data is scrubbed on the
132
+ server before storage: [Privacy & retention](https://sight.cultured.computer/docs/data-and-privacy).
133
+
134
+ ## Manual capture
431
135
 
432
136
  For calls autocapture does not see:
433
137
 
434
138
  ```ts
435
139
  await Sight.captureTurn({
436
140
  sessionExternalId: conversationId,
437
- turnIndex: 0,
141
+ turnIndex: 0, // position in the session, starting at 0
438
142
  userInput: { text: userMessage },
439
143
  payload: {
440
144
  response: { text: replyText },
441
145
  probe_model: "my-model",
442
- probe_provider: "my-provider",
443
146
  probe_tokens_input: 412,
444
147
  probe_tokens_output: 96,
445
148
  probe_latency_ms: 840,
@@ -447,188 +150,83 @@ await Sight.captureTurn({
447
150
  });
448
151
  ```
449
152
 
450
- - `deploymentSlug` is optional. It defaults to the `deployment` given to
451
- `init`; an explicit value wins.
452
- - `turnIndex` is the turn's position in the session, starting at 0. You
453
- supply it. (Autocapture counts per session inside the process.)
454
- - The turn is checked against the wire schema before it is sent. An invalid turn logs one warning
455
- line and is not sent.
456
-
457
- ## Turn identity
458
-
459
- Every captured turn is sent with a `turnId`: a fresh UUID per logical turn.
460
- The SDK's own retry of a send re-sends the same `turnId`. Autocapture's
461
- `turnIndex` is a counter held in the process, so two processes capturing
462
- one session, or one process restarted, send the same `turnIndex` with
463
- different `turnId`s. To supply your own identity on a manual capture, pass
464
- `turnId` (a UUID) to `captureTurn`.
465
-
466
- ## Attach outcomes
467
-
468
- Call these wherever the outcome becomes known; they join back by session id,
469
- even hours later, from a webhook or CRM callback.
470
-
471
- ```ts
472
- // A user reporting a persona break.
473
- await Sight.flagPersonaBreak({
474
- sessionExternalId: sessionId,
475
- note: "sounded robotic",
476
- });
477
-
478
- // Your own downstream outcome: a resolved ticket, a rating, a conversion.
479
- await Sight.emitOutcomeEvent({
480
- sessionExternalId: sessionId,
481
- kind: "ticket_resolved",
482
- detail: { ticketId: "ZD-88213" },
483
- });
484
- ```
485
-
486
- ## Capture environment events
487
-
488
- Deployments that run alongside a non-dialogue channel (a stimulus feed, a
489
- game state stream, an editor buffer) can record that channel's events
490
- against the conversation:
491
-
492
- ```ts
493
- await Sight.captureEnvironmentEvents(events, {
494
- clock_source: "my-event-clock",
495
- skew_bound_ms: 25,
496
- rule_version: "v1",
497
- });
498
- ```
499
-
500
- The envelope is generalized: `source_type` and `event` are free strings whose
501
- meaning is defined per deployment. The instrument attaches events to turns by
502
- time (the next turn's state corner, plus the causing turn's outcome corner
503
- when the event carries a `causeProvenance` turn reference) and never
504
- interprets them.
505
-
506
- ## Capture spans
507
-
508
- Deployments that keep their own sub-turn structure (tool calls, retrieval
509
- steps, per-call model usage inside a single turn) can ship it as spans:
510
-
511
- ```ts
512
- await Sight.captureSpans(
513
- [
514
- {
515
- contractVersion: 2,
516
- deploymentSlug: "my-agent",
517
- sessionExternalId: sessionId,
518
- turnIndex: 3,
519
- spanType: "tool_call",
520
- spanId: "lookup-3",
521
- parentSpanId: null,
522
- name: "lookup_order",
523
- status: "ok",
524
- startedAt: "2026-07-22T00:00:01.200Z",
525
- endedAt: "2026-07-22T00:00:01.380Z",
526
- durationMs: 180,
527
- model: null,
528
- provider: null,
529
- tokensInput: null,
530
- tokensOutput: null,
531
- costUsd: null,
532
- error: null,
533
- input: { state: "captured", value: { orderId: "ord_123" } },
534
- output: { state: "captured", value: { status: "shipped" } },
535
- intervals: [
536
- {
537
- kind: "active",
538
- startedAt: "2026-07-22T00:00:01.200Z",
539
- endedAt: "2026-07-22T00:00:01.280Z",
540
- },
541
- {
542
- kind: "waiting",
543
- startedAt: "2026-07-22T00:00:01.280Z",
544
- endedAt: "2026-07-22T00:00:01.380Z",
545
- },
546
- ],
547
- attributes: { toolName: "lookup_order", argKeys: ["orderId"] },
548
- },
549
- ],
550
- { clock_source: "my-agent-clock", skew_bound_ms: 25, rule_version: "v1" },
551
- );
552
- ```
553
-
554
- A span lands on the turn you name, or on the session's latest turn at/under
555
- its `startedAt` when `turnIndex` is omitted. Parent structure rides the
556
- batch: give a span a caller-local `spanId` and reference it from a sibling's
557
- `parentSpanId`. In contract v2 every operational key is present; use `null`
558
- for an unknown model, token count, cost, end time, or parent. Input and output
559
- use explicit `captured`, `empty`, `not_captured`, `redacted`, or `unavailable`
560
- states, so absence is never guessed from attributes. `attributes` are metadata
561
- only. Optional `intervals` record internal `active`, `waiting`, `retry`, and
562
- `error` windows. Every interval requires its own `startedAt` and `endedAt` and
563
- must stay within the span; when intervals are omitted, the waterfall does not
564
- invent them from status, names, or retry counters. Status is always explicit
565
- `ok` or `error`; the historical `unset` state
566
- is reserved for contract-v1 rows. The unversioned v1 shape remains accepted for older SDK callers and is
567
- read through a legacy adapter. `Sight.captureSpan(span)` is the single-span
568
- form.
569
-
570
- Run and Session trace views render recorded `tool_call` and `llm_call` spans
571
- with their explicit status and payload states. To display a provider-exposed
572
- reasoning **summary** and a caller-measured context budget, attach these
573
- optional attributes to the relevant span:
574
-
575
- ```ts
576
- attributes: {
577
- "sight.reasoning.summary": "The recorded provider summary",
578
- "sight.reasoning.duration_ms": 7000,
579
- "gen_ai.usage.cache_read_input_tokens": 31500,
580
- "sight.context.used_tokens": 40372,
581
- "sight.context.limit_tokens": 100000,
582
- }
583
- ```
584
-
585
- Do not supply hidden reasoning or manufacture a summary from the reply.
586
- Summary strings pass through the same span PII scrub; they are dropped when
587
- redaction is unavailable. Budget values are recorded per call, not accumulated
588
- Run spend, and both values are required for the gauge. Missing cached-token
589
- usage is not zero usage. Tool arguments/results belong in the versioned
590
- `input`/`output` payloads, not attributes; completion of a model call never
591
- establishes that a requested tool ran successfully.
592
-
593
- ## Scope
594
-
595
- Sight is a measurement system: it reports what a deployment did. It does not
596
- modify responses, and it does not estimate what a different response would
597
- have produced. Counterfactual evaluation requires logged propensities or a
598
- live experiment.
599
-
600
- ## The record schema
601
-
602
- Everything Sight captures exports in one published, versioned shape:
603
- `schema/sight-record-v1.schema.json`, shipped in this package
604
- (`@cultured_computer/sight/schema/record-v1`). One JSON line per
605
- session; each turn carries the fixed four-field envelope: the
606
- situation, the assistant's move, how the person took it, and what
607
- followed, on both sides of the exchange, with provenance and
608
- redaction built into the shape. A CI test keeps the schema and the
609
- export bytes in lockstep. Formats that standardize the agent log stop
610
- at the assistant's half; this one records the exchange and its
611
- consequences. See [Data format](https://sight.cultured.computer/docs/data-format).
612
-
613
- ## Docs
614
-
615
- - [Get started](https://sight.cultured.computer/docs/get-started):
616
- install, initialise, verify capture, the turn identity contract.
617
- - [Keys and access](https://sight.cultured.computer/docs/keys-and-access):
618
- the seven access words and which host takes which key.
619
- - [Integration paths](https://sight.cultured.computer/docs/integration-paths):
620
- what each capture path sends.
621
- - [SDK reference](https://sight.cultured.computer/docs/sdk-reference):
622
- the full method surface.
623
- - [CLI](https://sight.cultured.computer/docs/cli): every verb.
624
- - [HTTP API](https://sight.cultured.computer/docs/http-api): every route
625
- on the capture host and the Field API.
626
- - [Privacy & retention](https://sight.cultured.computer/docs/data-and-privacy):
627
- what is scrubbed, by what, and what is kept.
628
- - [Serve a SOUL.md](https://sight.cultured.computer/docs/serve-a-soul-md):
629
- the Field API, which this package has no client or CLI verbs for.
630
- - [Status](https://sight.cultured.computer/docs/where-it-stands): built,
631
- operator-run, not built.
153
+ An invalid turn logs one warning naming the first invalid field and is not
154
+ sent. Pass `turnId` (a UUID) to supply your own identity.
155
+ Reference: [SDK reference](https://sight.cultured.computer/docs/sdk-reference).
156
+
157
+ ## Outcomes, events, spans
158
+
159
+ All of these join to a session by its id and can be called later, from a
160
+ webhook or a callback.
161
+
162
+ | Method | Records | Docs |
163
+ | --- | --- | --- |
164
+ | `Sight.emitOutcomeEvent({ sessionExternalId, kind, detail? })` | Your own outcome: a resolved ticket, a conversion | [Outcome helpers](https://sight.cultured.computer/docs/sdk-reference#outcome-helpers) |
165
+ | `Sight.flagPersonaBreak({ sessionExternalId, note?, turnIndex? })` | A person's report that a reply was out of character | [Outcome helpers](https://sight.cultured.computer/docs/sdk-reference#outcome-helpers) |
166
+ | `Sight.userThumbs(id, "up" \| "down")`, `Sight.userRating(id, 1..5)` | Feedback, sent with the next captured turn | [Outcome helpers](https://sight.cultured.computer/docs/sdk-reference#outcome-helpers) |
167
+ | `Sight.endSession({ externalId, endedReason?, outcome? })` | Why the session ended, and an outcome known at close | [Sessions](https://sight.cultured.computer/docs/sdk-reference#sessions) |
168
+ | `Sight.captureSpans(spans, alignment?)` | Steps inside a turn: tool calls, model calls. At most 50 per call. | [Spans](https://sight.cultured.computer/docs/sdk-reference#spans) |
169
+ | `Sight.captureEnvironmentEvents(events, alignment?)` | Events from a channel beside the conversation. At most 100 per call. | [Environment events](https://sight.cultured.computer/docs/sdk-reference#environment-events) |
170
+ | `Sight.shutdown()` | Nothing; waits for sends in flight. Await it before a short-lived process exits. | [SDK reference](https://sight.cultured.computer/docs/sdk-reference) |
171
+
172
+ ## The CLI
173
+
174
+ `npx @cultured_computer/sight <verb>`. `sight --help` lists flags and
175
+ environment variables. Secrets are read from the environment, never from a flag.
176
+
177
+ | Verb | What it does | Key or login needed |
178
+ | --- | --- | --- |
179
+ | `sight auth login` | Signs this terminal in: prints a link, you approve it in your browser | Your dashboard sign-in |
180
+ | `sight auth logout` | Deletes the stored login token | None |
181
+ | `sight export --project <slug> --deployment <slug>` | Writes a deployment's record as JSONL (`--out <file>`, default stdout) | `auth login`; owner role on the project |
182
+ | `sight conditions --session <id>` | Prints one session's detector checks as NDJSON | A key with `studio:run`: `SIGHT_API_KEY`, or the key saved by `account create` |
183
+ | `sight account create` | Redeems a one-time token and saves the key to `~/.config/sight/machine.json` (mode `0600`) | `SIGHT_PROVISION_TOKEN` |
184
+ | `sight openrouter connect --budget <usd>` | Connects your OpenRouter key (`OPENROUTER_API_KEY`) to the project | A key with `providers:write` |
185
+ | `sight openrouter status` | Prints the stored connection: status, last four characters, budget | A key with `studio:run` or `providers:write` |
186
+ | `sight connect <relay-url> --invite <code>` | See [Connect your room](https://sight.cultured.computer/docs/connect-your-room) | An invite code |
187
+
188
+ Every flag: [CLI](https://sight.cultured.computer/docs/cli).
189
+
190
+ ## Serving a profile
191
+
192
+ - The Field API serves a profile on the same host, `https://api.cultured.computer`, with keys from the same API Keys page.
193
+ - This package has no client and no CLI verbs for it.
194
+ - Docs: [Serve a SOUL.md](https://sight.cultured.computer/docs/serve-a-soul-md).
195
+
196
+ ## Troubleshooting
197
+
198
+ Failed sends never throw. The first send the API rejects prints one
199
+ warning on stderr without `debug`: once per process for `401`, once for
200
+ `403`, once for any other `4xx` except `429`. Set `debug: true` on `init`
201
+ to log every failed send as `[sight] ingest failed status=<code>`.
202
+
203
+ | Symptom | Cause | Fix |
204
+ | --- | --- | --- |
205
+ | Nothing captured; stderr shows `[sight] call not captured (...): no session scope.` | The model call ran outside a session scope | Wrap it in `Sight.withSession(id, fn)` |
206
+ | Nothing captured, no warning | The send failed with a server or network error, or the client is not on a capture path | Set `debug: true` and read the status it logs |
207
+ | `[sight] the API rejected the key (401). Nothing is being captured.` | The key is missing, mistyped or revoked | Set `SIGHT_API_KEY` to a current key |
208
+ | `[sight] this key cannot capture (403): it lacks the ingest capability.` | The key lacks the `ingest` capability | Use a key with access `ingest`, `both` or `app` |
209
+ | `[sight] the API rejected a turn (400) and it was dropped.` (or `413`) | The API refused that request body | Set `debug: true` to log every failed send; check the turn's fields and size |
210
+ | `status=429`, or one `[sight] rate limited (429)` line | Over the project's request limit (600 per minute by default). Each limited send is retried once after `Retry-After`, then dropped. | Send fewer requests per minute, or ask for a higher limit |
211
+ | The first-session line is not printed | No turn has been accepted yet. The line prints once per process, on stderr. | Fix the rows above |
212
+ | `ai` 6 calls are not captured | `ai` 6 emits telemetry only for calls that opt in | Add `experimental_telemetry: { isEnabled: true }` to the call |
213
+ | An `ai` 7 call made right after `init` is missed | On Node below 22.13 the integration registers a moment after `init` returns | Call `registerTelemetry(sightTelemetry())` yourself, once (`registerTelemetry` is from `ai`) |
214
+ | `[sight] OpenAI module patching did not attach` | The client is not wrapped | `wrapOpenAI(new OpenAI())` |
215
+
216
+ ## Versions and compatibility
217
+
218
+ | Library | `peerDependencies` range (all optional) | Verified by this package's tests |
219
+ | --- | --- | --- |
220
+ | Node | `engines`: `>=20.6.0` | `ai` 7 itself requires Node 22 |
221
+ | `openai` | `>=4.0.0` | `wrapOpenAI` against stand-in clients; type-checked against 6.45.0 |
222
+ | `ai` | `>=3.0.0` | 7.0.17 and 6.0.300. Versions 3 to 5 are not verified. |
223
+ | `@anthropic-ai/sdk` | `>=0.30.0` | Not covered |
224
+ | `langchain` | `>=1.0.0 <2.0.0` | Not covered |
225
+
226
+ ## Changelog
227
+
228
+ `CHANGELOG.md` ships in the package:
229
+ [browse it on npm](https://www.npmjs.com/package/@cultured_computer/sight?activeTab=code).
632
230
 
633
231
  ## Legal
634
232