@cultured_computer/sight 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.
package/dist/index.d.cts CHANGED
@@ -270,7 +270,7 @@ declare const SpanInputV1Schema: z.ZodObject<{
270
270
  error: z.ZodOptional<z.ZodString>;
271
271
  /**
272
272
  * OpenInference / OpenTelemetry gen_ai.*-style attributes. String values
273
- * are Presidio-scrubbed by the worker before storage (see the PII rule
273
+ * are scrubbed of personal data by the worker before storage (see the PII rule
274
274
  * above). Capped at 16k JSON chars per span.
275
275
  */
276
276
  attributes: z.ZodEffects<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>, Record<string, unknown> | undefined, Record<string, unknown> | undefined>;
@@ -684,7 +684,7 @@ declare const SpanInputSchema: z.ZodUnion<[z.ZodEffects<z.ZodObject<{
684
684
  error: z.ZodOptional<z.ZodString>;
685
685
  /**
686
686
  * OpenInference / OpenTelemetry gen_ai.*-style attributes. String values
687
- * are Presidio-scrubbed by the worker before storage (see the PII rule
687
+ * are scrubbed of personal data by the worker before storage (see the PII rule
688
688
  * above). Capped at 16k JSON chars per span.
689
689
  */
690
690
  attributes: z.ZodEffects<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>, Record<string, unknown> | undefined, Record<string, unknown> | undefined>;
@@ -938,7 +938,7 @@ declare const SpansBatchSchema: z.ZodEffects<z.ZodObject<{
938
938
  error: z.ZodOptional<z.ZodString>;
939
939
  /**
940
940
  * OpenInference / OpenTelemetry gen_ai.*-style attributes. String values
941
- * are Presidio-scrubbed by the worker before storage (see the PII rule
941
+ * are scrubbed of personal data by the worker before storage (see the PII rule
942
942
  * above). Capped at 16k JSON chars per span.
943
943
  */
944
944
  attributes: z.ZodEffects<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>, Record<string, unknown> | undefined, Record<string, unknown> | undefined>;
@@ -1222,7 +1222,7 @@ declare const SpansBatchSchema: z.ZodEffects<z.ZodObject<{
1222
1222
  type SpansBatch = z.infer<typeof SpansBatchSchema>;
1223
1223
 
1224
1224
  /**
1225
- * Sight SDK (@cultured-computer/sight) shared types.
1225
+ * Sight SDK (@cultured_computer/sight) shared types.
1226
1226
  */
1227
1227
 
1228
1228
  declare const PersonaConfigSchema: z.ZodObject<{
@@ -1299,7 +1299,7 @@ declare const OutcomeHookSchema: z.ZodObject<{
1299
1299
  type: z.ZodEnum<["numeric", "categorical", "boolean", "duration"]>;
1300
1300
  /**
1301
1301
  * Callback that resolves the outcome for a completed session. Invoked by
1302
- * Probe.endSession() with the session's externalId; a non-null result
1302
+ * Sight.endSession() with the session's externalId; a non-null result
1303
1303
  * lands as an outcome event on the session. Not invoked for sessions
1304
1304
  * swept server-side (no explicit endSession) — use emitOutcomeEvent()
1305
1305
  * for outcomes that become known out of band.
@@ -1319,11 +1319,12 @@ type OutcomeResult = {
1319
1319
  value: string;
1320
1320
  };
1321
1321
  declare const ProbeConfigSchema: z.ZodObject<{
1322
- /** Unkey ingest key. Required. */
1322
+ /** The project's API key (an ingest key from the dashboard). Required. */
1323
1323
  apiKey: z.ZodString;
1324
- /** Deployment slug registered in the Probe backend. Required. */
1324
+ /** Deployment slug: the configuration this traffic belongs to. Required. */
1325
1325
  deployment: z.ZodString;
1326
- /** Ingest endpoint. Defaults to the production ingest service. */
1326
+ /** Ingest endpoint. Defaults to the production ingest service,
1327
+ `https://fieldwork-ingest.fly.dev`. */
1327
1328
  endpoint: z.ZodDefault<z.ZodString>;
1328
1329
  /**
1329
1330
  * Dashboard base URL used by the one-time first-capture announcement
@@ -1407,7 +1408,7 @@ declare const ProbeConfigSchema: z.ZodObject<{
1407
1408
  type: z.ZodEnum<["numeric", "categorical", "boolean", "duration"]>;
1408
1409
  /**
1409
1410
  * Callback that resolves the outcome for a completed session. Invoked by
1410
- * Probe.endSession() with the session's externalId; a non-null result
1411
+ * Sight.endSession() with the session's externalId; a non-null result
1411
1412
  * lands as an outcome event on the session. Not invoked for sessions
1412
1413
  * swept server-side (no explicit endSession) — use emitOutcomeEvent()
1413
1414
  * for outcomes that become known out of band.
@@ -1483,7 +1484,7 @@ declare const ProbeConfigSchema: z.ZodObject<{
1483
1484
  }>;
1484
1485
  type ProbeConfig = z.infer<typeof ProbeConfigSchema>;
1485
1486
  /**
1486
- * The shape callers pass to Probe.init(). This is the schema's INPUT type, so
1487
+ * The shape callers pass to Sight.init(). This is the schema's INPUT type, so
1487
1488
  * fields with a `.default()` (endpoint, sampleRate, debug) are optional here —
1488
1489
  * the defaults are applied by ProbeConfigSchema.parse() inside init(). Use this
1489
1490
  * for the init argument; `ProbeConfig` is the resolved (post-parse) type held
@@ -1515,14 +1516,14 @@ declare const SessionStartSchema: z.ZodObject<{
1515
1516
  */
1516
1517
  openedVia: z.ZodOptional<z.ZodEnum<["link", "notification", "resume", "direct", "share"]>>;
1517
1518
  /**
1518
- * Environmental context — browser / device / locale / tz (P2). Customer-
1519
- * configurable which fields to include. See collectClientContext helper.
1519
+ * Environmental context: browser / device / locale / tz. You choose
1520
+ * which fields to include. See the collectClientContext helper.
1520
1521
  */
1521
1522
  clientContext: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1522
1523
  /**
1523
1524
  * Optional customer metadata attached to the session. Forwarded with the
1524
1525
  * first captured turn merged into `clientContext` under the `metadata`
1525
- * key, so it lands on sessions.probe_session_client_context.
1526
+ * key, so it is stored with the session.
1526
1527
  */
1527
1528
  metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1528
1529
  /**
@@ -1562,7 +1563,7 @@ declare const SessionStartSchema: z.ZodObject<{
1562
1563
  }>;
1563
1564
  type SessionStart = z.infer<typeof SessionStartSchema>;
1564
1565
  /**
1565
- * Session end input (P2). Sent by Probe.endSession() so the worker records
1566
+ * Session end input. Sent by Sight.endSession() so the worker records
1566
1567
  * why a session ended. `outcome` + `outcomeDetail` are the one-call
1567
1568
  * outcome helper: when the deployer knows the outcome at close (a
1568
1569
  * resolved ticket, an escalation, an abandonment), the SDK emits it as an
@@ -1590,7 +1591,7 @@ type CapturedTurn = {
1590
1591
  deploymentSlug: string;
1591
1592
  sessionExternalId: string;
1592
1593
  /**
1593
- * The SDK payload contract version (D2, research-grade consolidation):
1594
+ * The SDK payload contract version:
1594
1595
  * stamped on EVERY captured turn by this SDK; absent on payloads from
1595
1596
  * older SDKs (read as 'envelope-v0-unstamped' downstream). Data lineage
1596
1597
  * across SDK upgrades — additive-only, tolerated-absent.
@@ -1598,12 +1599,21 @@ type CapturedTurn = {
1598
1599
  envelopeVersion?: string;
1599
1600
  /**
1600
1601
  * Customer's user identity. Forwarded by captureTurn from the session
1601
- * state (Probe.startSession({ externalUserId })); the worker persists it
1602
+ * state (Sight.startSession({ externalUserId })); the worker persists it
1602
1603
  * on sessions.external_user_id at first-turn session create. Never
1603
1604
  * defaulted to sessionExternalId — that key identifies the session.
1604
1605
  */
1605
1606
  externalUserId?: string;
1606
1607
  turnIndex: number;
1608
+ /**
1609
+ * The identity of one logical turn: a UUID. The SDK stamps a fresh one
1610
+ * on every captured turn and re-sends the same value when it retries
1611
+ * the send, so the server can tell a re-sent turn (same turnId) from a
1612
+ * different turn that reached the same turnIndex (another process, a
1613
+ * restart). Supply your own only when you already hold a stable UUID for
1614
+ * the turn; a supplied value is sent as given.
1615
+ */
1616
+ turnId?: string;
1607
1617
  /**
1608
1618
  * Persona slug active for this turn. Resolved by the SDK from (in order):
1609
1619
  * turn-level override, session-level from startSession(), init-level default.
@@ -1628,9 +1638,9 @@ type CapturedTurn = {
1628
1638
  reactionNextTurn?: string;
1629
1639
  };
1630
1640
  /**
1631
- * User-side input for this turn. What the human
1632
- * said + UI-level interactivity signals. Text is Presidio-scrubbed
1633
- * server-side before landing on probe_user_reply_text.
1641
+ * The person's input for this turn: the message that prompted this
1642
+ * reply, plus UI-level interactivity signals. The text is scrubbed of
1643
+ * personal data server-side before it is stored.
1634
1644
  */
1635
1645
  userInput?: {
1636
1646
  text?: string;
@@ -1656,7 +1666,7 @@ type CapturedTurn = {
1656
1666
  * User outcome signals:
1657
1667
  * flagged break, explicit rating (1-5), thumbs.
1658
1668
  *
1659
- * `flaggedBreak` is DEPRECATED in favor of Probe.flagPersonaBreak(),
1669
+ * `flaggedBreak` is DEPRECATED in favor of Sight.flagPersonaBreak(),
1660
1670
  * which carries user attribution and emits a 'break' outcome event;
1661
1671
  * the turn-level boolean remains accepted for wire compat only.
1662
1672
  */
@@ -1685,7 +1695,7 @@ type CapturedTurn = {
1685
1695
  };
1686
1696
  /**
1687
1697
  * Session context forwarded on the FIRST captured turn of a session
1688
- * (populated by captureTurn from Probe.startSession state; the worker
1698
+ * (populated by captureTurn from Sight.startSession state; the worker
1689
1699
  * persists both at session find-or-create). Omitted on later turns.
1690
1700
  */
1691
1701
  openedVia?: "link" | "notification" | "resume" | "direct" | "share";
@@ -1703,6 +1713,14 @@ type CapturedTurn = {
1703
1713
  environmentConfigLabel?: string;
1704
1714
  payload: Record<string, unknown>;
1705
1715
  };
1716
+ /**
1717
+ * What `captureTurn` accepts: a captured turn whose `deploymentSlug` may be
1718
+ * omitted. When it is, the `deployment` given to `init` is used; an
1719
+ * explicit value wins.
1720
+ */
1721
+ type CaptureTurnInput = Omit<CapturedTurn, "deploymentSlug"> & {
1722
+ deploymentSlug?: string;
1723
+ };
1706
1724
  declare const FlagPersonaBreakSchema: z.ZodObject<{
1707
1725
  sessionExternalId: z.ZodString;
1708
1726
  note: z.ZodOptional<z.ZodString>;
@@ -1739,7 +1757,7 @@ declare const OutcomeEventEmitSchema: z.ZodObject<{
1739
1757
  type OutcomeEventEmit = z.infer<typeof OutcomeEventEmitSchema>;
1740
1758
 
1741
1759
  /**
1742
- * HTTP client for the Probe ingest API.
1760
+ * HTTP client for the Sight ingest API.
1743
1761
  *
1744
1762
  * Sends captured turns to POST /v1/turns with a Bearer token. Async, fire-and-log:
1745
1763
  * SDK never blocks the customer's LLM path on ingest. Rate-limited sends (429)
@@ -1781,13 +1799,13 @@ declare class IngestClient {
1781
1799
  private shedAnnounced;
1782
1800
  /**
1783
1801
  * Every network send goes through here: adds the per-send timeout and
1784
- * the in-flight cap (audit B1). At the cap, the send is SHED — thrown
1785
- * into the caller's existing fire-and-log catch — rather than queued;
1802
+ * the in-flight cap. At the cap, the send is SHED (thrown into the
1803
+ * caller's existing fire-and-log catch) rather than queued;
1786
1804
  * the first shed per process warns on stderr, the rest debug-log.
1787
1805
  */
1788
1806
  private guardedFetch;
1789
1807
  /**
1790
- * Await all in-flight sends (bounded). Called by Probe.shutdown() so
1808
+ * Await all in-flight sends (bounded). Called by Sight.shutdown() so
1791
1809
  * short-lived processes (serverless, CLI scripts) can actually exit after
1792
1810
  * it — the documented "in-flight sends finish within 15s" only holds while
1793
1811
  * the process lives. Polling is coarse on purpose: sends report through
@@ -1798,7 +1816,7 @@ declare class IngestClient {
1798
1816
  constructor(opts: IngestClientOptions);
1799
1817
  /**
1800
1818
  * Send a turn to the ingest API. Fire-and-log: errors are logged but never
1801
- * thrown. The customer's LLM path never blocks on the Probe.
1819
+ * thrown. The customer's LLM path never blocks on capture.
1802
1820
  */
1803
1821
  sendTurn(turn: CapturedTurn): Promise<void>;
1804
1822
  /**
@@ -1808,7 +1826,7 @@ declare class IngestClient {
1808
1826
  sendFlag(deploymentSlug: string, flag: FlagPersonaBreakInput): Promise<void>;
1809
1827
  /**
1810
1828
  * Send a session-end event to the ingest API. Records why a session ended
1811
- * on the sessions.probe_session_ended_reason column. Fire-and-log.
1829
+ * on the session. Fire-and-log.
1812
1830
  */
1813
1831
  sendSessionEnd(deploymentSlug: string, end: SessionEndInput): Promise<void>;
1814
1832
  /**
@@ -1844,11 +1862,11 @@ declare class IngestClient {
1844
1862
  }
1845
1863
 
1846
1864
  /**
1847
- * Client-context capture helper (P2 per PLAN-2026-07-11).
1865
+ * Client-context capture helper.
1848
1866
  *
1849
1867
  * At session start the SDK optionally collects browser/device/locale/tz
1850
1868
  * metadata to send as SessionStart.clientContext. Customers control which
1851
- * fields land via ProbeConfig.clientContextIncludes; the default is
1869
+ * fields land via the `includes` argument; the default is
1852
1870
  * conservative (locale + timezone + agent kind, no fingerprinting fields).
1853
1871
  *
1854
1872
  * Node-side calls receive process metadata; browser-side calls receive
@@ -1873,7 +1891,7 @@ type ClientContextIncludes = {
1873
1891
  /**
1874
1892
  * Signature-phrase matcher.
1875
1893
  *
1876
- * Per-persona regex matching for voice consistency (Day 1 per PROBE.md §2).
1894
+ * Per-persona regex matching for voice consistency.
1877
1895
  * Customer authors signature phrases at Probe.init({ persona: { signaturePhrases: [...] } }).
1878
1896
  * The SDK edge or a worker computes matches per turn and includes the list
1879
1897
  * of matched slugs in the turn payload.
@@ -1883,9 +1901,7 @@ type ClientContextIncludes = {
1883
1901
  * source string with optional flags. Slug is what appears in the matches
1884
1902
  * array; it is not the pattern.
1885
1903
  *
1886
- * Trivial by design. Voice consistency at the embedding level lives in the
1887
- * Chapter 5 Dream column (PSV representation with per-deployment STEL
1888
- * calibration); this is the Day-1 heuristic that ships from ingest data alone.
1904
+ * Trivial by design: a heuristic computed from the captured text alone.
1889
1905
  */
1890
1906
  type SignaturePhrase = {
1891
1907
  /** Slug that appears in the matches array. Unique per persona. */
@@ -1915,18 +1931,18 @@ type CompiledPhrase = {
1915
1931
  declare function compileSignaturePhrases(phrases: SignaturePhrase[]): CompiledPhrase[];
1916
1932
 
1917
1933
  /**
1918
- * The Probe SDK main entry point.
1934
+ * The Sight SDK class. Exported as `Sight`, and as `Probe` (its earlier
1935
+ * name) for compatibility.
1919
1936
  *
1920
1937
  * Usage:
1921
- * import { Sight } from '@cultured-computer/sight';
1938
+ * import { Sight } from '@cultured_computer/sight';
1922
1939
  *
1923
- * Probe.init({
1924
- * apiKey: process.env.PROBE_API_KEY!,
1940
+ * Sight.init({
1941
+ * apiKey: process.env.SIGHT_API_KEY!,
1925
1942
  * deployment: 'support-agent',
1926
- * persona: { slug: 'casey' },
1927
1943
  * });
1928
1944
  *
1929
- * // Autocapture is now on for any subsequent OpenAI / Anthropic / etc. call.
1945
+ * // Calls made inside Sight.withSession(id, fn) are captured as turns.
1930
1946
  */
1931
1947
 
1932
1948
  type ProbeState = {
@@ -2004,18 +2020,22 @@ type SessionState = {
2004
2020
  };
2005
2021
  declare class Probe {
2006
2022
  /**
2007
- * Initialize the Probe SDK. Call once at process start. Subsequent calls are
2023
+ * Initialize the SDK. Call once at process start. Subsequent calls are
2008
2024
  * no-ops with a warning; re-init requires a shutdown() first.
2009
2025
  */
2010
2026
  static init(config: ProbeConfigInput): void;
2011
2027
  /**
2012
- * Run a callback inside a session context. Every LLM call made inside `fn`
2013
- * (through any instrumented library: OpenAI, Anthropic, LangChain, Vercel
2014
- * AI SDK, etc.) is automatically tagged with `sessionId` and captured as
2015
- * a turn on that session.
2028
+ * Run a callback inside a session scope. Every LLM call made inside `fn`
2029
+ * through a wrapped OpenAI client or an instrumented library is captured
2030
+ * as a turn on the session `sessionId`.
2016
2031
  *
2017
- * Under the hood, this uses OTel Baggage propagation; the shared span
2018
- * processor reads the session ID from baggage when each LLM span ends.
2032
+ * Autocapture needs this scope: a call made outside any session scope is
2033
+ * not captured. The first such call in a process prints one warning;
2034
+ * later ones log only with `debug: true`. (Spans that carry
2035
+ * `gen_ai.conversation.id` are the one exception: with no scope, that id
2036
+ * is used as the session id. An explicit scope always wins.)
2037
+ *
2038
+ * The scope is carried in OpenTelemetry baggage across awaits.
2019
2039
  */
2020
2040
  static withSession<T>(sessionId: string, fn: () => T | Promise<T>): Promise<T>;
2021
2041
  /**
@@ -2050,7 +2070,7 @@ declare class Probe {
2050
2070
  private static preSessionEntry;
2051
2071
  /**
2052
2072
  * Compute a stable SHA-256 hex hash of prompt/config text for use as
2053
- * `environmentConfigHash` on Probe.startSession(). Hash is *identity* —
2073
+ * `environmentConfigHash` on Sight.startSession(). Hash is *identity*:
2054
2074
  * pass the human-readable version alongside as `environmentConfigLabel`
2055
2075
  * for the diff table axis (a card keyed by a3f9c2… is unreadable).
2056
2076
  *
@@ -2083,28 +2103,30 @@ declare class Probe {
2083
2103
  */
2084
2104
  static endSession(externalId: string | SessionEndInput): Promise<void>;
2085
2105
  /**
2086
- * User started typing — records the first-keystroke timestamp for
2087
- * probe_user_first_keystroke_ms derivation on captureTurn. Derivable
2106
+ * The person started typing. Records the first-keystroke time, sent as
2107
+ * `userInput.firstKeystrokeMs` with the next captured turn. Derivable
2088
2108
  * only once a previous agent turn exists; a pre-session typing start
2089
2109
  * buffers the pending-input entry without a firstKeystrokeMs value.
2090
2110
  */
2091
2111
  static userInputStart(externalId: string): void;
2092
2112
  /**
2093
- * User pressed backspace / edited — increments edit_count for
2094
- * probe_user_reply_edit_count.
2113
+ * The person pressed backspace or edited. Increments the edit count,
2114
+ * sent as `userInput.editCount` with the next captured turn.
2095
2115
  */
2096
2116
  static userInputEdit(externalId: string): void;
2097
2117
  /**
2098
- * User submitted their reply. Records the text (Presidio-scrubbed
2099
- * server-side before landing on probe_user_reply_text) plus the submit
2100
- * timestamp, which captureTurn uses to derive probe_agent_reflect_ms
2101
- * (submit → next agent turn) and probe_transition_time_ms (previous
2102
- * agent turn → submit).
2118
+ * The person submitted their message. Records the text (scrubbed of
2119
+ * personal data server-side before it is stored) plus the submit
2120
+ * timestamp. The text and timings are sent with the NEXT captured turn:
2121
+ * a turn's person text is the message that prompted its reply.
2103
2122
  */
2104
2123
  static userInputSubmit(externalId: string, text: string): void;
2105
2124
  /** Attach a thumbs-up/down to the current turn. */
2106
2125
  static userThumbs(externalId: string, thumbs: "up" | "down"): void;
2107
- /** Attach an explicit 1-5 rating to the current turn. */
2126
+ /**
2127
+ * Attach an explicit rating to the current turn: an integer from 1 to 5.
2128
+ * Any other value logs one warning line and is dropped.
2129
+ */
2108
2130
  static userRating(externalId: string, rating: number): void;
2109
2131
  /**
2110
2132
  * Helper: collect client context and pass it to startSession in one call.
@@ -2122,22 +2144,35 @@ declare class Probe {
2122
2144
  */
2123
2145
  static wireOutcomeHook(hook: OutcomeHook): void;
2124
2146
  /**
2125
- * Manually capture a turn. Instrumentation adapters call this internally;
2126
- * exposed for advanced customers who want to bypass autocapture.
2147
+ * Manually capture a turn. For callers that do not use autocapture.
2148
+ *
2149
+ * - `deploymentSlug` may be omitted: the `deployment` given to `init` is
2150
+ * used. An explicit value wins.
2151
+ * - Every turn is sent with a `turnId` (a fresh UUID unless you supply
2152
+ * one). A retried send carries the same `turnId`.
2153
+ * - The turn is validated before it is sent. An invalid turn logs one
2154
+ * warning line naming the first invalid field and is dropped; nothing
2155
+ * is sent.
2127
2156
  *
2128
2157
  * Persona resolution order for the outgoing turn payload:
2129
2158
  * 1. turn.personaSlug (turn-level override)
2130
- * 2. sessions[externalId].personaSlug (from startSession)
2131
- * 3. state.persona.slug (init-level default)
2159
+ * 2. the session's persona (from startSession)
2160
+ * 3. the init-level default
2132
2161
  *
2133
- * Signature-phrase matching runs at the SDK edge when the resolved persona
2162
+ * Signature-phrase matching runs in the SDK when the resolved persona
2134
2163
  * has signature phrases registered. The matched slug list is attached to
2135
2164
  * `turn.signaturePhraseMatches` before send.
2136
2165
  */
2137
- static captureTurn(turn: CapturedTurn): Promise<void>;
2166
+ static captureTurn(turn: CaptureTurnInput): Promise<void>;
2138
2167
  /**
2139
- * Emit a custom outcome event on a session. Populates probe_outcome_events
2140
- * with the customer-supplied `kind` string. Use for
2168
+ * The one capture path. Manual captureTurn calls and autocapture both
2169
+ * land here; autocapture also passes what it observed on the request
2170
+ * (`hints`), applied below under the explicit-input-wins rule.
2171
+ */
2172
+ private static captureWithHints;
2173
+ /**
2174
+ * Emit a custom outcome event on a session, stored with the `kind`
2175
+ * string you supply. Use for
2141
2176
  * customer-defined kinds like "purchase_complete", "handoff_to_human",
2142
2177
  * "character_break_severe". Universal seed kinds (break, escalation,
2143
2178
  * resolution, thumbs_*, rating_*) are also emitted by worker-side
@@ -2221,39 +2256,128 @@ declare class Probe {
2221
2256
  }
2222
2257
 
2223
2258
  /**
2224
- * Explicit OpenAI client wrapping — the autocapture path that cannot miss.
2259
+ * Explicit OpenAI client wrapping: the autocapture path that does not
2260
+ * depend on module format, load order, or the openai version.
2225
2261
  *
2226
- * Module patching (registerOpenAI → @traceloop/instrumentation-openai) only
2227
- * attaches under CommonJS, only when `openai` is loaded after Probe.init(),
2228
- * and only for openai <5 (the instrumentation's declared supportedVersions).
2229
- * A modern ESM app on openai v5+ therefore captures nothing through the
2230
- * patch path, and did so silently until registerOpenAI grew its post-enable
2231
- * verification. wrapOpenAI() is the documented default instead: it wraps
2232
- * the client INSTANCE the customer already holds, which is immune to module
2233
- * format, load order, and library version.
2262
+ * Module patching (the other path) attaches only under CommonJS, only when
2263
+ * `openai` is loaded after Sight.init(), and only for openai <5. wrapOpenAI()
2264
+ * wraps the client instance the caller already holds instead.
2234
2265
  *
2235
2266
  * import OpenAI from 'openai';
2236
- * import { Probe, wrapOpenAI } from '@cultured_computer/sight';
2267
+ * import { Sight, wrapOpenAI } from '@cultured_computer/sight';
2237
2268
  * const openai = wrapOpenAI(new OpenAI());
2269
+ * await Sight.withSession(conversationId, () =>
2270
+ * openai.chat.completions.create({ ... }),
2271
+ * );
2238
2272
  *
2239
2273
  * Covers chat.completions.create and responses.create, streaming included:
2240
2274
  * the stream is teed, chunks reach the caller unchanged, and the turn is
2241
- * emitted when the stream completes. Turns flow through the same session
2242
- * resolution and captureTurn path as the OTel processor, so payload keys
2243
- * are identical downstream.
2275
+ * emitted when the stream completes. A call is captured only inside a
2276
+ * Sight.withSession() scope; the first call outside one prints one warning.
2244
2277
  *
2245
- * Binding: registerAllInstrumentations() binds this module to live Probe
2246
- * state at init. wrapOpenAI() may be called before init — the wrap is
2247
- * inert (pure passthrough) until the binding lands, and warns once if a
2248
- * call happens while unbound so a missing init is never silent.
2278
+ * A streamed call also records the time to the first token: request start
2279
+ * to the first chunk that carries reply text, a refusal, or a tool call.
2280
+ * A non-streamed call has no first-token time and sends none. A cost is
2281
+ * sent only when the response reports one (`usage.cost`).
2282
+ *
2283
+ * wrapOpenAI() may be called before Sight.init(): the wrap passes calls
2284
+ * through untouched until init runs, and warns once if a call happens
2285
+ * before it.
2249
2286
  */
2250
2287
 
2251
2288
  /**
2252
2289
  * Wrap an OpenAI client instance so every chat.completions.create and
2253
- * responses.create call is captured as a Sight turn. Returns the same
2254
- * client. Idempotent; safe to call before Probe.init() (capture starts
2255
- * once init binds).
2290
+ * responses.create call made inside a Sight.withSession() scope is captured
2291
+ * as a turn. Returns the same client. Idempotent; safe to call before
2292
+ * Sight.init() (capture starts once init has run). A call outside any
2293
+ * session scope is not captured; the first one prints one warning.
2256
2294
  */
2257
2295
  declare function wrapOpenAI<T extends object>(client: T): T;
2258
2296
 
2259
- export { type AlignmentProvenance, type CapturedTurn, type EnvironmentEventInput, type OutcomeEventEmit, type OutcomeHook, type OutcomeResult, type PersonaConfig, Probe, type ProbeConfig, type ProbeConfigInput, SPAN_INTERVAL_KINDS, SPAN_PAYLOAD_STATES, SPAN_STATUSES, SPAN_TYPES, SPAN_V2_STATUSES, Probe as Sight, type AlignmentProvenance as SightAlignmentProvenance, type CapturedTurn as SightCapturedTurn, type ProbeConfig as SightConfig, type ProbeConfigInput as SightConfigInput, type EnvironmentEventInput as SightEnvironmentEventInput, type OutcomeEventEmit as SightOutcomeEventEmit, type OutcomeHook as SightOutcomeHook, type OutcomeResult as SightOutcomeResult, type PersonaConfig as SightPersonaConfig, type SpanInput as SightSpanInput, type SpanInputV2 as SightSpanInputV2, type SpansBatch as SightSpansBatch, type SpanInput, SpanInputSchema, type SpanInputV1, SpanInputV1Schema, type SpanInputV2, SpanInputV2Schema, type SpanInterval, type SpanIntervalKind, SpanIntervalSchema, type SpanPayload, SpanPayloadSchema, type SpanPayloadState, type SpanStatus, type SpanType, type SpansBatch, SpansBatchSchema, wrapOpenAI };
2297
+ /**
2298
+ * Vercel AI SDK (`ai`) autocapture.
2299
+ *
2300
+ * `ai` 7 creates no OpenTelemetry spans itself. It calls the telemetry
2301
+ * integrations registered with `registerTelemetry()` (kept on the global
2302
+ * `AI_SDK_TELEMETRY_INTEGRATIONS`), and once one integration is registered
2303
+ * every call emits events with no per-call flag. This file is that
2304
+ * integration: Sight.init() registers it when `ai` 7 is resolvable, and
2305
+ * `sightTelemetry()` exports it for hosts that register it themselves.
2306
+ *
2307
+ * The turn unit is ONE MODEL CALL (one step of `generateText` / `streamText`,
2308
+ * or the single call of `generateObject` / `streamObject`), the same unit
2309
+ * wrapOpenAI and the span processor use. A tool loop of N model calls is N
2310
+ * turns: each carries the text of that reply (which may be empty when the
2311
+ * model only requested tools) and the tool names it requested. The outer
2312
+ * `generateText` operation is never a turn.
2313
+ *
2314
+ * Events used (interface `Telemetry` of `ai` 7):
2315
+ * onStart session scope and runtimeContext of the call
2316
+ * onStepStart runtimeContext of the step
2317
+ * onLanguageModelCallStart request instructions and messages
2318
+ * executeLanguageModelCall marks the provider call (see ai-dedupe.ts)
2319
+ * onLanguageModelCallEnd provider response id (see ai-dedupe.ts)
2320
+ * onStepEnd the turn: reply, model, usage, finish, timing
2321
+ * onObjectStepStart / End the same for generateObject / streamObject
2322
+ * onError / onAbort a model call that failed or was aborted
2323
+ * onEnd releases the per-call state
2324
+ * `onStepFinish` is deliberately not implemented: `ai` 7 sends every step
2325
+ * end to both names, and `ai` 6 (which has no `onStepEnd`) is captured
2326
+ * through its OpenTelemetry spans instead (see otel-processor.ts).
2327
+ *
2328
+ * `ai` 3 to 6 are not handled here. `ai` 6 emits `ai.*` OpenTelemetry spans
2329
+ * when a call sets `experimental_telemetry: { isEnabled: true }`; the span
2330
+ * processor maps those.
2331
+ */
2332
+
2333
+ /** Options for `sightTelemetry()`. */
2334
+ type SightAiTelemetryOptions = {
2335
+ /**
2336
+ * The session the calls this integration sees belong to, for a call made
2337
+ * outside any Sight.withSession() scope. An explicit scope wins.
2338
+ */
2339
+ sessionId?: string;
2340
+ };
2341
+ /**
2342
+ * The Sight telemetry integration for the Vercel AI SDK (`ai` 7). It is
2343
+ * structurally a `Telemetry` from `ai`: pass it to `registerTelemetry()` or
2344
+ * to a call's `telemetry.integrations`.
2345
+ */
2346
+ type SightAiTelemetry = {
2347
+ readonly name: 'sight';
2348
+ onStart(event: unknown): void;
2349
+ onStepStart(event: unknown): void;
2350
+ onLanguageModelCallStart(event: unknown): void;
2351
+ onLanguageModelCallEnd(event: unknown): void;
2352
+ onStepEnd(event: unknown): void;
2353
+ onObjectStepStart(event: unknown): void;
2354
+ onObjectStepEnd(event: unknown): void;
2355
+ onEnd(event: unknown): void;
2356
+ onAbort(event: unknown): void;
2357
+ onError(event: unknown): void;
2358
+ executeLanguageModelCall<T>(options: {
2359
+ execute: () => PromiseLike<T>;
2360
+ }): PromiseLike<T>;
2361
+ };
2362
+ /**
2363
+ * The Sight telemetry integration for the Vercel AI SDK (`ai` 7).
2364
+ *
2365
+ * Sight.init() registers it when `ai` is resolvable. Call this yourself when
2366
+ * that cannot work (a bundle where the SDK cannot resolve the host's `ai`):
2367
+ *
2368
+ * import { registerTelemetry } from 'ai';
2369
+ * import { sightTelemetry } from '@cultured_computer/sight';
2370
+ * registerTelemetry(sightTelemetry());
2371
+ *
2372
+ * or per call, with the session the call belongs to:
2373
+ *
2374
+ * generateText({ model, prompt,
2375
+ * telemetry: { integrations: sightTelemetry({ sessionId }) } });
2376
+ *
2377
+ * With no options it returns one shared instance, so Sight.init() does not
2378
+ * register it a second time. Safe to call before Sight.init(): nothing is
2379
+ * captured until init runs.
2380
+ */
2381
+ declare function sightTelemetry(options?: SightAiTelemetryOptions): SightAiTelemetry;
2382
+
2383
+ export { type AlignmentProvenance, type CaptureTurnInput, type CapturedTurn, type EnvironmentEventInput, type OutcomeEventEmit, type OutcomeHook, type OutcomeResult, type PersonaConfig, Probe, type ProbeConfig, type ProbeConfigInput, SPAN_INTERVAL_KINDS, SPAN_PAYLOAD_STATES, SPAN_STATUSES, SPAN_TYPES, SPAN_V2_STATUSES, Probe as Sight, type SightAiTelemetry, type SightAiTelemetryOptions, type AlignmentProvenance as SightAlignmentProvenance, type CaptureTurnInput as SightCaptureTurnInput, type CapturedTurn as SightCapturedTurn, type ProbeConfig as SightConfig, type ProbeConfigInput as SightConfigInput, type EnvironmentEventInput as SightEnvironmentEventInput, type OutcomeEventEmit as SightOutcomeEventEmit, type OutcomeHook as SightOutcomeHook, type OutcomeResult as SightOutcomeResult, type PersonaConfig as SightPersonaConfig, type SpanInput as SightSpanInput, type SpanInputV2 as SightSpanInputV2, type SpansBatch as SightSpansBatch, type SpanInput, SpanInputSchema, type SpanInputV1, SpanInputV1Schema, type SpanInputV2, SpanInputV2Schema, type SpanInterval, type SpanIntervalKind, SpanIntervalSchema, type SpanPayload, SpanPayloadSchema, type SpanPayloadState, type SpanStatus, type SpanType, type SpansBatch, SpansBatchSchema, sightTelemetry, wrapOpenAI };