@cultured_computer/sight 0.7.1 → 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/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,21 +1222,22 @@ 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<{
1229
- /** Persona slug matching the deployment's registered persona. */
1229
+ /** The persona's slug. */
1230
1230
  slug: z.ZodString;
1231
1231
  /**
1232
- * RICE authorship artifact (Role, Identity, Communication, Engagement).
1233
- * Either inline object or a path/URL to a JSON file loaded at init time.
1232
+ * The persona's description (role, identity, communication, engagement):
1233
+ * an object, or a string reference to one. Optional. This SDK does not
1234
+ * read or send it.
1234
1235
  */
1235
1236
  rice: z.ZodOptional<z.ZodUnion<[z.ZodRecord<z.ZodString, z.ZodUnknown>, z.ZodString]>>;
1236
1237
  /**
1237
- * Customer-authored signature phrases for this persona. Compiled once at
1238
- * init and matched per turn at the SDK edge; matched slugs appear on the
1239
- * outgoing turn as `signaturePhraseMatches`.
1238
+ * Signature phrases for this persona. Compiled once and matched against
1239
+ * each reply in the SDK; matched slugs are sent with the turn as
1240
+ * `signaturePhraseMatches`.
1240
1241
  */
1241
1242
  signaturePhrases: z.ZodOptional<z.ZodArray<z.ZodUnion<[z.ZodObject<{
1242
1243
  slug: z.ZodString;
@@ -1298,11 +1299,10 @@ declare const OutcomeHookSchema: z.ZodObject<{
1298
1299
  /** Type of outcome the deployment tracks. */
1299
1300
  type: z.ZodEnum<["numeric", "categorical", "boolean", "duration"]>;
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
1303
- * lands as an outcome event on the session. Not invoked for sessions
1304
- * swept server-side (no explicit endSession) — use emitOutcomeEvent()
1305
- * for outcomes that become known out of band.
1302
+ * Resolves the outcome of a finished session. Called by
1303
+ * Sight.endSession() with the session's externalId; a non-null result is
1304
+ * sent as an outcome event on the session. Not called for a session you
1305
+ * never end; use emitOutcomeEvent() for an outcome known later.
1306
1306
  */
1307
1307
  resolve: z.ZodType<(sessionId: string) => Promise<OutcomeResult | null>, z.ZodTypeDef, (sessionId: string) => Promise<OutcomeResult | null>>;
1308
1308
  }, "strip", z.ZodTypeAny, {
@@ -1319,32 +1319,32 @@ 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: a key with the `ingest` capability. 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
+ /** The API host the captures are sent to. Defaults to
1327
+ `https://api.cultured.computer`. */
1327
1328
  endpoint: z.ZodDefault<z.ZodString>;
1328
1329
  /**
1329
- * Dashboard base URL used by the one-time first-capture announcement
1330
- * (the stderr permalink printed after the first successful send).
1331
- * Self-hosted or staging dashboards override it the same way `endpoint`
1332
- * is overridden.
1330
+ * Dashboard base URL for the link printed on stderr after the first
1331
+ * accepted turn. Set it only for a self-hosted or staging dashboard.
1333
1332
  */
1334
1333
  dashboardUrl: z.ZodDefault<z.ZodString>;
1335
1334
  /** Persona identification. Optional at init; can be set later via identifyPersona(). */
1336
1335
  persona: z.ZodOptional<z.ZodObject<{
1337
- /** Persona slug matching the deployment's registered persona. */
1336
+ /** The persona's slug. */
1338
1337
  slug: z.ZodString;
1339
1338
  /**
1340
- * RICE authorship artifact (Role, Identity, Communication, Engagement).
1341
- * Either inline object or a path/URL to a JSON file loaded at init time.
1339
+ * The persona's description (role, identity, communication, engagement):
1340
+ * an object, or a string reference to one. Optional. This SDK does not
1341
+ * read or send it.
1342
1342
  */
1343
1343
  rice: z.ZodOptional<z.ZodUnion<[z.ZodRecord<z.ZodString, z.ZodUnknown>, z.ZodString]>>;
1344
1344
  /**
1345
- * Customer-authored signature phrases for this persona. Compiled once at
1346
- * init and matched per turn at the SDK edge; matched slugs appear on the
1347
- * outgoing turn as `signaturePhraseMatches`.
1345
+ * Signature phrases for this persona. Compiled once and matched against
1346
+ * each reply in the SDK; matched slugs are sent with the turn as
1347
+ * `signaturePhraseMatches`.
1348
1348
  */
1349
1349
  signaturePhrases: z.ZodOptional<z.ZodArray<z.ZodUnion<[z.ZodObject<{
1350
1350
  slug: z.ZodString;
@@ -1406,11 +1406,10 @@ declare const ProbeConfigSchema: z.ZodObject<{
1406
1406
  /** Type of outcome the deployment tracks. */
1407
1407
  type: z.ZodEnum<["numeric", "categorical", "boolean", "duration"]>;
1408
1408
  /**
1409
- * Callback that resolves the outcome for a completed session. Invoked by
1410
- * Probe.endSession() with the session's externalId; a non-null result
1411
- * lands as an outcome event on the session. Not invoked for sessions
1412
- * swept server-side (no explicit endSession) — use emitOutcomeEvent()
1413
- * for outcomes that become known out of band.
1409
+ * Resolves the outcome of a finished session. Called by
1410
+ * Sight.endSession() with the session's externalId; a non-null result is
1411
+ * sent as an outcome event on the session. Not called for a session you
1412
+ * never end; use emitOutcomeEvent() for an outcome known later.
1414
1413
  */
1415
1414
  resolve: z.ZodType<(sessionId: string) => Promise<OutcomeResult | null>, z.ZodTypeDef, (sessionId: string) => Promise<OutcomeResult | null>>;
1416
1415
  }, "strip", z.ZodTypeAny, {
@@ -1421,13 +1420,14 @@ declare const ProbeConfigSchema: z.ZodObject<{
1421
1420
  resolve: (sessionId: string) => Promise<OutcomeResult | null>;
1422
1421
  }>>;
1423
1422
  /**
1424
- * Sample rate for autocapture. 1.0 = 100% of calls captured. Lower values
1425
- * sample deterministically so a given (turnId) always resolves identically.
1423
+ * Share of turns sent, from 0 to 1. Default 1.0: every turn. Below 1.0
1424
+ * the choice is deterministic per (session id, turn index). Applies to
1425
+ * autocapture and to captureTurn.
1426
1426
  */
1427
1427
  sampleRate: z.ZodDefault<z.ZodNumber>;
1428
1428
  /**
1429
- * Debug mode: log every captured turn to stderr with a prefix. Never logs
1430
- * the Bearer token or PII.
1429
+ * Debug mode: log every send and every failed send to stderr, prefixed
1430
+ * `[sight]`. Never logs the API key or conversation text.
1431
1431
  */
1432
1432
  debug: z.ZodDefault<z.ZodBoolean>;
1433
1433
  }, "strip", z.ZodTypeAny, {
@@ -1483,23 +1483,19 @@ declare const ProbeConfigSchema: z.ZodObject<{
1483
1483
  }>;
1484
1484
  type ProbeConfig = z.infer<typeof ProbeConfigSchema>;
1485
1485
  /**
1486
- * The shape callers pass to Probe.init(). This is the schema's INPUT type, so
1487
- * fields with a `.default()` (endpoint, sampleRate, debug) are optional here —
1488
- * the defaults are applied by ProbeConfigSchema.parse() inside init(). Use this
1489
- * for the init argument; `ProbeConfig` is the resolved (post-parse) type held
1490
- * internally, where those fields are always present.
1486
+ * The argument of Sight.init(). Fields with a default (endpoint,
1487
+ * dashboardUrl, sampleRate, debug) are optional here. `ProbeConfig` is the
1488
+ * same configuration after init has applied the defaults.
1491
1489
  */
1492
1490
  type ProbeConfigInput = z.input<typeof ProbeConfigSchema>;
1493
1491
  declare const SessionStartSchema: z.ZodObject<{
1494
- /** Customer's session identity (opaque string; used as the correlation key). */
1492
+ /** Your id for the session: one conversation. Any non-empty string. */
1495
1493
  externalId: z.ZodString;
1496
1494
  /**
1497
- * Customer's USER identity (opaque string), distinct from externalId:
1498
- * externalId keys the session; externalUserId ties sessions to a
1499
- * returning user. Forwarded on every captured turn so the worker can
1500
- * persist it on the session row — return-with-persona-consistency and
1501
- * prior-session metrics require it. Optional; deployments that do not
1502
- * identify users simply skip the user-level return metrics.
1495
+ * Your id for the person: a stable, pseudonymous string, distinct from
1496
+ * externalId. It ties one person's sessions together and is sent with
1497
+ * every captured turn. Optional; without it, sessions are still captured
1498
+ * and nothing links them to a returning person.
1503
1499
  */
1504
1500
  externalUserId: z.ZodOptional<z.ZodString>;
1505
1501
  /**
@@ -1508,30 +1504,26 @@ declare const SessionStartSchema: z.ZodObject<{
1508
1504
  * deployments where init already carries the persona.
1509
1505
  */
1510
1506
  persona: z.ZodOptional<z.ZodString>;
1511
- /**
1512
- * How the user got into this session.
1513
- * Retention semantics differ radically between a resume and a fresh
1514
- * notification landing.
1515
- */
1507
+ /** How the person arrived in this session. */
1516
1508
  openedVia: z.ZodOptional<z.ZodEnum<["link", "notification", "resume", "direct", "share"]>>;
1517
1509
  /**
1518
- * Environmental context — browser / device / locale / tz (P2). Customer-
1519
- * configurable which fields to include. See collectClientContext helper.
1510
+ * Client context: locale, timezone, runtime, and anything else you
1511
+ * choose to include. Stored as sent. See startSessionWithContext.
1520
1512
  */
1521
1513
  clientContext: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1522
1514
  /**
1523
- * Optional customer metadata attached to the session. Forwarded with the
1524
- * first captured turn merged into `clientContext` under the `metadata`
1525
- * key, so it lands on sessions.probe_session_client_context.
1515
+ * Your own metadata for the session. Sent with the first captured turn,
1516
+ * inside `clientContext` under the `metadata` key, and stored as sent.
1526
1517
  */
1527
1518
  metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1528
1519
  /**
1529
- * RLDS episode-level provenance. Powers the version behavioral diff
1530
- * on the dashboard. All optional.
1531
- * agentId — model/policy version
1532
- * experimentId — A/B arm or feature flag
1533
- * environmentConfigHash — SHA of prompt/config file(s)
1534
- * environmentConfigLabel — human-readable version label
1520
+ * Version tags for the session, used to compare versions on the
1521
+ * dashboard. All optional.
1522
+ * agentId model or policy version
1523
+ * experimentId A/B arm or feature flag
1524
+ * environmentConfigHash hash of the prompt or configuration
1525
+ * (see Sight.hashEnvironmentConfig)
1526
+ * environmentConfigLabel readable name for that version
1535
1527
  */
1536
1528
  agentId: z.ZodOptional<z.ZodString>;
1537
1529
  experimentId: z.ZodOptional<z.ZodString>;
@@ -1562,12 +1554,9 @@ declare const SessionStartSchema: z.ZodObject<{
1562
1554
  }>;
1563
1555
  type SessionStart = z.infer<typeof SessionStartSchema>;
1564
1556
  /**
1565
- * Session end input (P2). Sent by Probe.endSession() so the worker records
1566
- * why a session ended. `outcome` + `outcomeDetail` are the one-call
1567
- * outcome helper: when the deployer knows the outcome at close (a
1568
- * resolved ticket, an escalation, an abandonment), the SDK emits it as an
1569
- * outcome event alongside the session end — it never rides the
1570
- * session-end wire itself.
1557
+ * The argument of Sight.endSession(): why the session ended. When you know
1558
+ * the outcome at close (a resolved ticket, an escalation), pass `outcome`
1559
+ * and optional `outcomeDetail`; the SDK sends it as an outcome event.
1571
1560
  */
1572
1561
  declare const SessionEndSchema: z.ZodObject<{
1573
1562
  externalId: z.ZodString;
@@ -1590,35 +1579,39 @@ type CapturedTurn = {
1590
1579
  deploymentSlug: string;
1591
1580
  sessionExternalId: string;
1592
1581
  /**
1593
- * The SDK payload contract version (D2, research-grade consolidation):
1594
- * stamped on EVERY captured turn by this SDK; absent on payloads from
1595
- * older SDKs (read as 'envelope-v0-unstamped' downstream). Data lineage
1596
- * across SDK upgrades — additive-only, tolerated-absent.
1582
+ * The version of the turn format this SDK sends. Set by the SDK on every
1583
+ * captured turn; a value you supply is replaced.
1597
1584
  */
1598
1585
  envelopeVersion?: string;
1599
1586
  /**
1600
- * Customer's user identity. Forwarded by captureTurn from the session
1601
- * state (Probe.startSession({ externalUserId })); the worker persists it
1602
- * on sessions.external_user_id at first-turn session create. Never
1603
- * defaulted to sessionExternalId — that key identifies the session.
1587
+ * Your id for the person. Filled from Sight.startSession({
1588
+ * externalUserId }) when omitted. Never defaults to sessionExternalId.
1604
1589
  */
1605
1590
  externalUserId?: string;
1606
1591
  turnIndex: number;
1607
1592
  /**
1608
- * Persona slug active for this turn. Resolved by the SDK from (in order):
1609
- * turn-level override, session-level from startSession(), init-level default.
1593
+ * The identity of one logical turn: a UUID. The SDK stamps a fresh one
1594
+ * on every captured turn and re-sends the same value when it retries
1595
+ * the send, so the server can tell a re-sent turn (same turnId) from a
1596
+ * different turn that reached the same turnIndex (another process, a
1597
+ * restart). Supply your own only when you already hold a stable UUID for
1598
+ * the turn; a supplied value is sent as given.
1599
+ */
1600
+ turnId?: string;
1601
+ /**
1602
+ * Persona slug for this turn. When omitted: the session's persona from
1603
+ * startSession(), then the default from init.
1610
1604
  */
1611
1605
  personaSlug?: string;
1612
1606
  /**
1613
- * Signature-phrase slugs matched at the SDK edge (computed from the
1614
- * customer's signaturePhrases config at init). Empty array or omitted when
1615
- * no signatures matched or none were registered.
1607
+ * Slugs of the persona's signature phrases found in the reply. Computed
1608
+ * by the SDK when omitted. Empty or absent when none matched or none are
1609
+ * registered.
1616
1610
  */
1617
1611
  signaturePhraseMatches?: string[];
1618
1612
  /**
1619
- * Interpretive record fields passed through from a customer harness
1620
- * (read hook wired). Populated only if the customer
1621
- * runs the Cultured Computer harness pattern; null for non-harness deployments.
1613
+ * Optional fields from your own decision layer, sent as given: how it
1614
+ * classified the situation and what it chose. Autocapture never sets it.
1622
1615
  */
1623
1616
  interpretive?: {
1624
1617
  situationType?: string[];
@@ -1628,9 +1621,9 @@ type CapturedTurn = {
1628
1621
  reactionNextTurn?: string;
1629
1622
  };
1630
1623
  /**
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.
1624
+ * The person's input for this turn: the message that prompted this
1625
+ * reply, plus UI-level interactivity signals. The text is scrubbed of
1626
+ * personal data server-side before it is stored.
1634
1627
  */
1635
1628
  userInput?: {
1636
1629
  text?: string;
@@ -1641,7 +1634,8 @@ type CapturedTurn = {
1641
1634
  submittedAt?: string;
1642
1635
  };
1643
1636
  /**
1644
- * Interactivity: agent reflect time, stream completion, multimodal events.
1637
+ * Timing of the reply: time from the person's submit to the captured
1638
+ * turn, whether the stream completed, multimodal events.
1645
1639
  */
1646
1640
  interactivity?: {
1647
1641
  agentReflectMs?: number;
@@ -1653,12 +1647,10 @@ type CapturedTurn = {
1653
1647
  }>;
1654
1648
  };
1655
1649
  /**
1656
- * User outcome signals:
1657
- * flagged break, explicit rating (1-5), thumbs.
1650
+ * The person's feedback on the turn: rating (1 to 5), thumbs.
1658
1651
  *
1659
- * `flaggedBreak` is DEPRECATED in favor of Probe.flagPersonaBreak(),
1660
- * which carries user attribution and emits a 'break' outcome event;
1661
- * the turn-level boolean remains accepted for wire compat only.
1652
+ * `flaggedBreak` is deprecated: use Sight.flagPersonaBreak(), which
1653
+ * records an outcome event. The boolean is still accepted.
1662
1654
  */
1663
1655
  userOutcome?: {
1664
1656
  flaggedBreak?: boolean;
@@ -1666,36 +1658,30 @@ type CapturedTurn = {
1666
1658
  thumbs?: "up" | "down";
1667
1659
  };
1668
1660
  /**
1669
- * Propensity + candidate set (harness-supplied).
1670
- * Manual-capture callers put this in payload.propensity; captureTurn
1671
- * validates the contract and hoists the valid object to
1672
- * this top-level field so the worker projection lands it on the
1673
- * read_candidates / read_propensities / selection_meta columns.
1661
+ * The candidate replies and the probability of each, when your system
1662
+ * chooses among candidates. Supply it here or in payload.propensity;
1663
+ * captureTurn checks it and sends a valid one. An invalid one logs one
1664
+ * warning and is removed; the turn is still sent.
1674
1665
  */
1675
1666
  propensity?: PropensityInput;
1676
1667
  /**
1677
- * Transition signals (the human's response to the previous reply).
1678
- * Derived by captureTurn when the previous turn's capture time and this
1679
- * turn's user submit time are both known; may also be supplied directly
1680
- * by manual-capture callers.
1668
+ * The person's response to the previous reply: the time from that reply
1669
+ * to this turn's submit. Derived by the SDK when both times are known;
1670
+ * you may also supply it.
1681
1671
  */
1682
1672
  transition?: {
1683
1673
  timeMs?: number;
1684
1674
  lengthDelta?: number;
1685
1675
  };
1686
1676
  /**
1687
- * Session context forwarded on the FIRST captured turn of a session
1688
- * (populated by captureTurn from Probe.startSession state; the worker
1689
- * persists both at session find-or-create). Omitted on later turns.
1677
+ * Session context from Sight.startSession, sent on the first captured
1678
+ * turn of a session and omitted on later turns.
1690
1679
  */
1691
1680
  openedVia?: "link" | "notification" | "resume" | "direct" | "share";
1692
1681
  clientContext?: Record<string, unknown>;
1693
1682
  /**
1694
- * RLDS episode-level provenance. Forwarded from the session
1695
- * state on every turn so downstream storage can attribute each turn to the
1696
- * arm/version that produced it. Populated by startSession() from either
1697
- * the customer-provided value or the init-time default; null when neither
1698
- * is set.
1683
+ * Version tags from Sight.startSession, sent on every turn so each turn
1684
+ * is attributed to the version that produced it. Absent when not set.
1699
1685
  */
1700
1686
  agentId?: string;
1701
1687
  experimentId?: string;
@@ -1703,6 +1689,14 @@ type CapturedTurn = {
1703
1689
  environmentConfigLabel?: string;
1704
1690
  payload: Record<string, unknown>;
1705
1691
  };
1692
+ /**
1693
+ * What `captureTurn` accepts: a captured turn whose `deploymentSlug` may be
1694
+ * omitted. When it is, the `deployment` given to `init` is used; an
1695
+ * explicit value wins.
1696
+ */
1697
+ type CaptureTurnInput = Omit<CapturedTurn, "deploymentSlug"> & {
1698
+ deploymentSlug?: string;
1699
+ };
1706
1700
  declare const FlagPersonaBreakSchema: z.ZodObject<{
1707
1701
  sessionExternalId: z.ZodString;
1708
1702
  note: z.ZodOptional<z.ZodString>;
@@ -1721,9 +1715,9 @@ type FlagPersonaBreakInput = z.infer<typeof FlagPersonaBreakSchema>;
1721
1715
  declare const OutcomeEventEmitSchema: z.ZodObject<{
1722
1716
  sessionExternalId: z.ZodString;
1723
1717
  kind: z.ZodString;
1724
- /** Optional turn index this event is caused by. Omit to attach to latest turn. */
1718
+ /** The turn that caused the outcome. Omit to attach to the latest turn. */
1725
1719
  causingTurnIndex: z.ZodOptional<z.ZodNumber>;
1726
- /** Optional detail payload (customer-defined). */
1720
+ /** Your own detail for the outcome. Optional. */
1727
1721
  detail: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1728
1722
  }, "strip", z.ZodTypeAny, {
1729
1723
  kind: string;
@@ -1739,18 +1733,21 @@ declare const OutcomeEventEmitSchema: z.ZodObject<{
1739
1733
  type OutcomeEventEmit = z.infer<typeof OutcomeEventEmitSchema>;
1740
1734
 
1741
1735
  /**
1742
- * HTTP client for the Probe ingest API.
1736
+ * HTTP client for the Sight API. Internal; use the `Sight` methods.
1743
1737
  *
1744
- * Sends captured turns to POST /v1/turns with a Bearer token. Async, fire-and-log:
1745
- * SDK never blocks the customer's LLM path on ingest. Rate-limited sends (429)
1746
- * are retried exactly once after Retry-After; sustained limiting drops captures.
1738
+ * Sends captured turns to POST /v1/turns with a Bearer token. A failed send
1739
+ * is logged with `debug: true` and never thrown. The first send the API
1740
+ * rejects (a 4xx other than 429) prints one warning without `debug`, once
1741
+ * per process for each of: 401, 403, any other status. A rate-limited send
1742
+ * (429) is retried once after Retry-After; if the retry is limited too,
1743
+ * that capture is dropped.
1747
1744
  */
1748
1745
 
1749
1746
  type IngestClientOptions = {
1750
1747
  apiKey: string;
1751
1748
  endpoint: string;
1752
1749
  debug: boolean;
1753
- /** Dashboard base URL for the one-time first-capture announcement. */
1750
+ /** Dashboard base URL for the link printed after the first accepted turn. */
1754
1751
  dashboardUrl?: string;
1755
1752
  };
1756
1753
  declare class IngestClient {
@@ -1759,96 +1756,98 @@ declare class IngestClient {
1759
1756
  private debug;
1760
1757
  private dashboardUrl;
1761
1758
  /**
1762
- * First-trace permalink: the first
1763
- * SUCCESSFUL sendTurn prints one stderr line with a dashboard permalink,
1764
- * then never again for the life of this client (one IngestClient per
1765
- * process — one `init` per process; a restart prints once more, accepted).
1766
- * Failed sends do not consume the announcement. Only sendTurn announces:
1767
- * flags, outcome events, and session-end sends never trigger it (a flag
1768
- * arriving before any turn is not a captured session).
1759
+ * The first accepted turn prints one stderr line with a link to the
1760
+ * session on the dashboard, once per client (one client per init). A
1761
+ * failed send does not use it up. Only turns print it; flags, outcome
1762
+ * events and session ends do not.
1769
1763
  */
1770
1764
  private firstCaptureAnnounced;
1771
1765
  /**
1772
- * Rate-limit (429) handling: the first 429 per process prints one stderr
1773
- * warning (not debug-gated, same channel and lifetime as the first-capture
1774
- * announce); subsequent 429s only debug-log. Each rate-limited request is
1775
- * retried exactly once after Retry-After; pendingRetries counts retries
1776
- * waiting on their timers so the cap can shed load.
1766
+ * Rate limiting (429): the first 429 prints one stderr warning, with or
1767
+ * without `debug`; later ones log only with `debug: true`. Each
1768
+ * rate-limited request is retried once after Retry-After. At most 50
1769
+ * retries wait at a time; past that, a rate-limited request is dropped.
1777
1770
  */
1778
1771
  private rateLimitAnnounced;
1779
1772
  private pendingRetries;
1773
+ /**
1774
+ * Rejected sends (a 4xx other than 429): the first one of each class
1775
+ * (401, 403, any other status) prints one stderr warning, with or
1776
+ * without `debug`. A rejected send is never retried: the same key and
1777
+ * the same body get the same answer.
1778
+ */
1779
+ private rejectionAnnounced;
1780
1780
  private inFlight;
1781
1781
  private shedAnnounced;
1782
1782
  /**
1783
- * 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;
1786
- * the first shed per process warns on stderr, the rest debug-log.
1783
+ * Every send goes through here: a 15 second timeout per send and at most
1784
+ * 64 sends in flight. Past that, a new send is dropped, not queued; the
1785
+ * first drop prints one stderr warning, later ones log only with
1786
+ * `debug: true`.
1787
1787
  */
1788
1788
  private guardedFetch;
1789
1789
  /**
1790
- * Await all in-flight sends (bounded). Called by Probe.shutdown() so
1791
- * short-lived processes (serverless, CLI scripts) can actually exit after
1792
- * it — the documented "in-flight sends finish within 15s" only holds while
1793
- * the process lives. Polling is coarse on purpose: sends report through
1794
- * guardedFetch's counter and scheduled retries, never awaited individually.
1795
- * Retries beyond the drain budget remain best-effort, not durable delivery.
1790
+ * Wait for sends in flight and pending retries, for at most `timeoutMs`
1791
+ * (default 15 seconds). Called by Sight.shutdown() so a short-lived
1792
+ * process can exit without losing a send. A retry still waiting when
1793
+ * the time is up is not guaranteed to be sent.
1796
1794
  */
1797
1795
  drainInFlight(timeoutMs?: number): Promise<void>;
1798
1796
  constructor(opts: IngestClientOptions);
1799
1797
  /**
1800
- * 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.
1798
+ * Send a turn. Errors are logged with `debug: true`, never thrown.
1802
1799
  */
1803
1800
  sendTurn(turn: CapturedTurn): Promise<void>;
1804
1801
  /**
1805
- * Send a persona-break flag to the ingest API. Fire-and-log, same as sendTurn.
1806
- * Populates the `user_flagged_break` outcome column on the dashboard.
1802
+ * Send a persona-break flag. Errors are logged with `debug: true`, never
1803
+ * thrown.
1807
1804
  */
1808
1805
  sendFlag(deploymentSlug: string, flag: FlagPersonaBreakInput): Promise<void>;
1809
1806
  /**
1810
- * 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.
1807
+ * Send a session end: why the session ended. Errors are logged with
1808
+ * `debug: true`, never thrown.
1812
1809
  */
1813
1810
  sendSessionEnd(deploymentSlug: string, end: SessionEndInput): Promise<void>;
1814
1811
  /**
1815
- * Send an outcome event to the ingest API. Fire-and-log. Populates
1816
- * the outcome-events store.
1812
+ * Send an outcome event. Errors are logged with `debug: true`, never
1813
+ * thrown.
1817
1814
  */
1818
1815
  sendOutcomeEvent(deploymentSlug: string, event: OutcomeEventEmit): Promise<void>;
1819
1816
  /**
1820
- * Send an environment-event batch to the ingest API. Fire-and-log, same as
1821
- * sendTurn. The envelope is generalized: the worker attaches each event to
1822
- * its session's record by time; meaning is per-deployment.
1817
+ * Send a batch of environment events. Errors are logged with
1818
+ * `debug: true`, never thrown.
1823
1819
  */
1824
1820
  sendEnvironmentEvents(batch: EnvironmentEventsBatch): Promise<void>;
1825
1821
  /**
1826
- * Send a span batch to the ingest API. Fire-and-log, same as sendTurn.
1827
- * Spans carry sub-turn structure (llm_call / tool_call / framework_step /
1828
- * custom); the worker resolves each span's session/turn and wires in-batch
1829
- * parent references.
1822
+ * Send a batch of spans. Errors are logged with `debug: true`, never
1823
+ * thrown.
1830
1824
  */
1831
1825
  sendSpans(batch: SpansBatch): Promise<void>;
1832
1826
  /**
1833
- * Route a send response through the 429 retry policy. Non-429 responses
1834
- * pass through untouched. A 429 is re-sent exactly once after Retry-After
1835
- * seconds (default 1s when the header is missing or unparseable; clamped
1836
- * to [1, 60]s); the retry's response is returned as-is, so a second 429 is
1837
- * never retried again — callers log and drop it like any other failed
1838
- * send. Returns null when the retry was dropped at the pending-retry cap.
1839
- * The timer is unref'd (where supported) so a pending retry never holds
1840
- * the process open.
1827
+ * The 429 retry rule. Any other response passes through. A 429 is sent
1828
+ * again once after Retry-After seconds (1 second when the header is
1829
+ * missing or unreadable; kept between 1 and 60 seconds). The retry's
1830
+ * response is returned as is, so a second 429 is not retried. Returns
1831
+ * null when the retry was dropped because 50 retries were already
1832
+ * waiting. A waiting retry does not keep the process alive.
1841
1833
  */
1842
1834
  private retryIfRateLimited;
1835
+ /**
1836
+ * The once-per-class warning for a send the API rejected. Not gated on
1837
+ * debug: a rejected key drops every capture, so the host is told once.
1838
+ * 429 has its own warning (see retryIfRateLimited); a 5xx is the API's
1839
+ * failure, not the host's, and stays a debug line.
1840
+ */
1841
+ private announceRejection;
1843
1842
  private log;
1844
1843
  }
1845
1844
 
1846
1845
  /**
1847
- * Client-context capture helper (P2 per PLAN-2026-07-11).
1846
+ * Client-context capture helper.
1848
1847
  *
1849
1848
  * At session start the SDK optionally collects browser/device/locale/tz
1850
- * metadata to send as SessionStart.clientContext. Customers control which
1851
- * fields land via ProbeConfig.clientContextIncludes; the default is
1849
+ * metadata to send as SessionStart.clientContext. You choose which fields
1850
+ * are sent with the `includes` argument; the default is
1852
1851
  * conservative (locale + timezone + agent kind, no fingerprinting fields).
1853
1852
  *
1854
1853
  * Node-side calls receive process metadata; browser-side calls receive
@@ -1856,24 +1855,24 @@ declare class IngestClient {
1856
1855
  * fingerprint the user is opt-in.
1857
1856
  */
1858
1857
  type ClientContextIncludes = {
1859
- /** window.navigator.userAgent — off by default (fingerprinting risk). */
1858
+ /** window.navigator.userAgent. Off by default (fingerprinting risk). */
1860
1859
  userAgent?: boolean;
1861
- /** window.navigator.language / process.env.LANG — on by default. */
1860
+ /** window.navigator.language / process.env.LANG. On by default. */
1862
1861
  locale?: boolean;
1863
- /** Intl timezone / process TZ — on by default. */
1862
+ /** Intl timezone / process TZ. On by default. */
1864
1863
  timezone?: boolean;
1865
- /** window.screen dimensions — off by default (fingerprinting risk). */
1864
+ /** window.screen dimensions. Off by default (fingerprinting risk). */
1866
1865
  screen?: boolean;
1867
- /** Node process metadata (platform, node version) — on by default in Node. */
1866
+ /** Node process metadata (platform, node version). On by default in Node. */
1868
1867
  runtime?: boolean;
1869
- /** Custom key/value pairs the customer wants to attach. */
1868
+ /** Your own key/value pairs to attach. */
1870
1869
  custom?: Record<string, string | number | boolean | null>;
1871
1870
  };
1872
1871
 
1873
1872
  /**
1874
1873
  * Signature-phrase matcher.
1875
1874
  *
1876
- * Per-persona regex matching for voice consistency (Day 1 per PROBE.md §2).
1875
+ * Per-persona regex matching for voice consistency.
1877
1876
  * Customer authors signature phrases at Probe.init({ persona: { signaturePhrases: [...] } }).
1878
1877
  * The SDK edge or a worker computes matches per turn and includes the list
1879
1878
  * of matched slugs in the turn payload.
@@ -1883,9 +1882,7 @@ type ClientContextIncludes = {
1883
1882
  * source string with optional flags. Slug is what appears in the matches
1884
1883
  * array; it is not the pattern.
1885
1884
  *
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.
1885
+ * Trivial by design: a heuristic computed from the captured text alone.
1889
1886
  */
1890
1887
  type SignaturePhrase = {
1891
1888
  /** Slug that appears in the matches array. Unique per persona. */
@@ -1915,18 +1912,18 @@ type CompiledPhrase = {
1915
1912
  declare function compileSignaturePhrases(phrases: SignaturePhrase[]): CompiledPhrase[];
1916
1913
 
1917
1914
  /**
1918
- * The Probe SDK main entry point.
1915
+ * The Sight SDK class. Exported as `Sight`, and as `Probe` (its earlier
1916
+ * name) for compatibility.
1919
1917
  *
1920
1918
  * Usage:
1921
- * import { Sight } from '@cultured-computer/sight';
1919
+ * import { Sight } from '@cultured_computer/sight';
1922
1920
  *
1923
- * Probe.init({
1924
- * apiKey: process.env.PROBE_API_KEY!,
1925
- * deployment: 'support-agent',
1926
- * persona: { slug: 'casey' },
1921
+ * Sight.init({
1922
+ * apiKey: process.env.SIGHT_API_KEY!,
1923
+ * deployment: 'my-assistant',
1927
1924
  * });
1928
1925
  *
1929
- * // Autocapture is now on for any subsequent OpenAI / Anthropic / etc. call.
1926
+ * // Model calls made inside Sight.withSession(id, fn) are captured as turns.
1930
1927
  */
1931
1928
 
1932
1929
  type ProbeState = {
@@ -1943,10 +1940,9 @@ type ProbeState = {
1943
1940
  signatureMatchers: Map<string, ReturnType<typeof compileSignaturePhrases>>;
1944
1941
  /**
1945
1942
  * Interaction signals (userInputStart/Edit/Submit, userThumbs/userRating)
1946
- * that arrived BEFORE any session entry existed for their externalId.
1947
- * Flushed into the session entry when it is created (startSession or
1948
- * lazy-create at captureTurn). FIFO-capped at PRE_SESSION_BUFFER_MAX ids
1949
- * so signals for sessions that never capture a turn cannot leak memory.
1943
+ * recorded before any session entry existed for their externalId. Moved
1944
+ * into the session entry when it is created (startSession, or the first
1945
+ * captured turn). Holds at most 100 session ids; the oldest is dropped.
1950
1946
  */
1951
1947
  preSessionBuffer: Map<string, PreSessionSignals>;
1952
1948
  };
@@ -1958,7 +1954,7 @@ type PreSessionSignals = {
1958
1954
 
1959
1955
  type SessionState = {
1960
1956
  externalId: string;
1961
- /** Customer's user identity from startSession; forwarded on every turn. */
1957
+ /** Your user id from startSession; sent with every turn. */
1962
1958
  externalUserId: string | null;
1963
1959
  turnIndex: number;
1964
1960
  startedAt: number;
@@ -1971,32 +1967,32 @@ type SessionState = {
1971
1967
  environmentConfigHash: string | null;
1972
1968
  environmentConfigLabel: string | null;
1973
1969
  /**
1974
- * Timestamp of the last captured agent turn. Used on the NEXT turn to
1975
- * derive transition.timeMs (previous agent reply → this turn's user
1976
- * submit) and firstKeystrokeMs (previous agent reply → typing start).
1970
+ * Time of the last captured turn. Used on the next turn to derive
1971
+ * transition.timeMs (previous reply to this turn's submit) and
1972
+ * firstKeystrokeMs (previous reply to typing start).
1977
1973
  */
1978
1974
  lastAgentTurnAt: number | null;
1979
1975
  /**
1980
- * Timestamp of the last userInputSubmit. Used at captureTurn to derive
1981
- * agentReflectMs (user submit → agent turn capture). transition.timeMs
1982
- * derives from the per-turn pendingUserInput.submittedAt instead, which
1983
- * resets on every capture, so stale submits are never reused for it.
1976
+ * Time of the last userInputSubmit. Used when a turn is captured to
1977
+ * derive agentReflectMs (submit to capture). transition.timeMs uses the
1978
+ * per-turn pendingUserInput.submittedAt instead, which resets on every
1979
+ * capture, so an earlier submit is never reused for it.
1984
1980
  */
1985
1981
  lastUserSubmitAt: number | null;
1986
1982
  /**
1987
1983
  * True once openedVia/clientContext have been sent with a captured turn.
1988
- * The worker persists session context at session find-or-create (first
1989
- * turn that arrives), so the SDK forwards it exactly once.
1984
+ * The server stores session context from the first turn of a session, so
1985
+ * the SDK sends it once.
1990
1986
  */
1991
1987
  sessionContextForwarded: boolean;
1992
- /** Per-turn user input pending on the SDK edge (unified capture helper). */
1988
+ /** The person's input held for the next captured turn. */
1993
1989
  pendingUserInput: {
1994
1990
  text?: string;
1995
1991
  firstKeystrokeMs?: number;
1996
1992
  editCount: number;
1997
1993
  submittedAt?: number;
1998
1994
  } | null;
1999
- /** Per-turn user outcome pending on the SDK edge (thumbs / rating). */
1995
+ /** Thumbs or rating held for the next captured turn. */
2000
1996
  pendingUserOutcome: {
2001
1997
  thumbs?: "up" | "down";
2002
1998
  explicitRating?: number;
@@ -2004,35 +2000,40 @@ type SessionState = {
2004
2000
  };
2005
2001
  declare class Probe {
2006
2002
  /**
2007
- * Initialize the Probe SDK. Call once at process start. Subsequent calls are
2008
- * no-ops with a warning; re-init requires a shutdown() first.
2003
+ * Initialize the SDK. Call once at process start. Throws on an invalid
2004
+ * configuration; no other method throws on bad input. A second call
2005
+ * prints one warning and is ignored; call shutdown() first to
2006
+ * re-initialize.
2009
2007
  */
2010
2008
  static init(config: ProbeConfigInput): void;
2011
2009
  /**
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.
2010
+ * Run a callback inside a session scope. Every model call made inside
2011
+ * `fn` through a wrapped OpenAI client, the Vercel AI SDK or an
2012
+ * instrumented library is captured as a turn on the session `sessionId`
2013
+ * (your conversation id).
2016
2014
  *
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.
2015
+ * Required for autocapture: a call made outside any session scope is not
2016
+ * captured. The first such call in a process prints one warning; later
2017
+ * ones log only with `debug: true`. Exceptions, used only when there is
2018
+ * no scope: a span that carries `gen_ai.conversation.id`, and an `ai`
2019
+ * call that names its session (see `sightTelemetry`). An explicit scope
2020
+ * always wins.
2021
+ *
2022
+ * The scope is carried across awaits. Returns what `fn` returns.
2019
2023
  */
2020
2024
  static withSession<T>(sessionId: string, fn: () => T | Promise<T>): Promise<T>;
2021
2025
  /**
2022
- * Identify the process-level default persona. Overwrites any previously-set
2023
- * default. For per-session persona identification (multi-persona products),
2024
- * use startSession({ externalId, persona }) instead.
2026
+ * Set the default persona for the process. Replaces the previous default.
2027
+ * To set a persona per session, use startSession({ externalId, persona }).
2025
2028
  */
2026
2029
  static identifyPersona(persona: PersonaConfig): void;
2027
2030
  /**
2028
- * Start (or update) a session with an active persona.
2029
- *
2030
- * Single-persona deployments can skip this if the init-level default is
2031
- * enough; the SDK will still create a session entry lazily on first turn.
2032
- * Multi-persona products call this at conversation start so every turn in
2033
- * the session inherits the selected persona.
2031
+ * Start (or update) a session. Optional: a session is created on its
2032
+ * first captured turn. Call it to attach `externalUserId` (your stable,
2033
+ * pseudonymous user id), a persona, version tags or client context.
2034
2034
  *
2035
- * Idempotent: calling with the same externalId updates the entry.
2035
+ * Calling it again with the same externalId updates the entry. Invalid
2036
+ * input logs one warning and is ignored.
2036
2037
  */
2037
2038
  static startSession(input: SessionStart): void;
2038
2039
  /**
@@ -2049,156 +2050,159 @@ declare class Probe {
2049
2050
  */
2050
2051
  private static preSessionEntry;
2051
2052
  /**
2052
- * Compute a stable SHA-256 hex hash of prompt/config text for use as
2053
- * `environmentConfigHash` on Probe.startSession(). Hash is *identity* —
2054
- * pass the human-readable version alongside as `environmentConfigLabel`
2055
- * for the diff table axis (a card keyed by a3f9c2… is unreadable).
2056
- *
2057
- * Ships as a helper because inconsistent hashing across restarts breaks
2058
- * The version behavioral diff — every customer would
2059
- * hash their own way and version-diff would become noise.
2053
+ * SHA-256 hex hash of prompt or configuration text, for
2054
+ * `environmentConfigHash` on Sight.startSession(). The hash identifies a
2055
+ * version; pass a readable name alongside as `environmentConfigLabel`.
2060
2056
  *
2061
- * The same hashing (src/hash.ts) backs the OTel processor's automatic
2062
- * version stamping: when autocapture sees a system message and the
2063
- * deployer set no environmentConfigHash, the session is stamped with
2064
- * the system prompt's hash and an 'auto:xxxxxxxx' label. Explicit
2065
- * startSession values always win over the auto stamp.
2057
+ * Autocapture uses the same hash: when it sees a system prompt and the
2058
+ * session has no environmentConfigHash, the session gets the system
2059
+ * prompt's hash and the label 'auto:' plus its first 8 characters.
2060
+ * Values you pass to startSession always win.
2066
2061
  */
2067
2062
  static hashEnvironmentConfig(input: string): Promise<string>;
2068
2063
  /**
2069
- * End a session and release its in-memory entry. Optional (sessions time out
2070
- * eventually), but recommended for long-running processes with many distinct
2071
- * conversations. If `input.endedReason` is provided the SDK sends an end
2072
- * event to ingest so the worker records the reason server-side.
2064
+ * End a session: sends the end reason (`natural` when none is given) and
2065
+ * releases the session's in-memory entry. Optional; a session you never
2066
+ * end times out on the server.
2073
2067
  *
2074
- * Resolve-on-close: if an outcome hook is registered (init `outcomeHook`
2075
- * or wireOutcomeHook()), endSession invokes `hook.resolve(externalId)`
2076
- * and, when it returns a non-null OutcomeResult, lands it as an outcome
2077
- * event (kind = result.outcome, detail carries type/value). This is the
2078
- * ONLY place the SDK invokes the hook — there are no client-side timers,
2079
- * so sessions that are never ended explicitly are swept server-side as
2080
- * `timeout` and receive no hook-resolved outcome; land those via
2081
- * emitOutcomeEvent() from wherever the outcome becomes known. Error-safe:
2082
- * a throwing or rejecting hook never breaks endSession.
2068
+ * - `outcome` (with optional `outcomeDetail`) is sent as an outcome
2069
+ * event before the session end.
2070
+ * - With no `outcome` and an outcome hook registered (init `outcomeHook`
2071
+ * or wireOutcomeHook()), `hook.resolve(externalId)` runs; a non-null
2072
+ * result is sent as an outcome event. This is the only place the hook
2073
+ * runs. A hook that throws logs one warning and does not break
2074
+ * endSession.
2075
+ * - For an outcome known later, or for a session you never end, call
2076
+ * emitOutcomeEvent().
2083
2077
  */
2084
2078
  static endSession(externalId: string | SessionEndInput): Promise<void>;
2085
2079
  /**
2086
- * User started typing — records the first-keystroke timestamp for
2087
- * probe_user_first_keystroke_ms derivation on captureTurn. Derivable
2088
- * only once a previous agent turn exists; a pre-session typing start
2089
- * buffers the pending-input entry without a firstKeystrokeMs value.
2080
+ * The person started typing. Records the time since the previous reply,
2081
+ * sent as `userInput.firstKeystrokeMs` with the next captured turn. No
2082
+ * value is sent before the session's first captured turn.
2090
2083
  */
2091
2084
  static userInputStart(externalId: string): void;
2092
2085
  /**
2093
- * User pressed backspace / edited — increments edit_count for
2094
- * probe_user_reply_edit_count.
2086
+ * The person pressed backspace or edited. Increments the edit count,
2087
+ * sent as `userInput.editCount` with the next captured turn.
2095
2088
  */
2096
2089
  static userInputEdit(externalId: string): void;
2097
2090
  /**
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).
2091
+ * The person submitted their message. Records the text (scrubbed of
2092
+ * personal data server-side before it is stored) and the submit time.
2093
+ * Both are sent with the next captured turn: a turn's person text is the
2094
+ * message that prompted its reply. Call it before the model call.
2103
2095
  */
2104
2096
  static userInputSubmit(externalId: string, text: string): void;
2105
- /** Attach a thumbs-up/down to the current turn. */
2097
+ /** Record a thumbs-up or thumbs-down. Sent with the next captured turn. */
2106
2098
  static userThumbs(externalId: string, thumbs: "up" | "down"): void;
2107
- /** Attach an explicit 1-5 rating to the current turn. */
2099
+ /**
2100
+ * Record a rating: an integer from 1 to 5. Sent with the next captured
2101
+ * turn. Any other value logs one warning line and is dropped.
2102
+ */
2108
2103
  static userRating(externalId: string, rating: number): void;
2109
2104
  /**
2110
- * Helper: collect client context and pass it to startSession in one call.
2105
+ * startSession, with client context (locale, timezone, runtime) collected
2106
+ * for you unless `input.clientContext` is given.
2111
2107
  */
2112
2108
  static startSessionWithContext(input: SessionStart, includes?: ClientContextIncludes): void;
2113
2109
  /**
2114
- * Register the outcome hook: declares the deployment's outcome type and
2115
- * the resolver for it. The hook's `resolve(sessionExternalId)` is invoked
2116
- * by endSession() — explicit close is the only trigger; the SDK runs no
2117
- * client-side timers. A non-null OutcomeResult lands as an outcome event
2118
- * on the session. Sessions that are never ended explicitly are swept
2119
- * server-side and never resolve through the hook; land those outcomes via
2120
- * emitOutcomeEvent() from the place where the outcome becomes known
2121
- * (webhook, CRM callback); it joins back by sessionExternalId.
2110
+ * Register the outcome hook: the deployment's outcome type and a
2111
+ * resolver for it. `resolve(sessionExternalId)` runs only when you call
2112
+ * endSession() without an `outcome`; the SDK runs no timers. A non-null
2113
+ * result is sent as an outcome event on the session. For a session you
2114
+ * never end, or an outcome known later (webhook, CRM callback), call
2115
+ * emitOutcomeEvent(); it joins to the session by sessionExternalId.
2122
2116
  */
2123
2117
  static wireOutcomeHook(hook: OutcomeHook): void;
2124
2118
  /**
2125
- * Manually capture a turn. Instrumentation adapters call this internally;
2126
- * exposed for advanced customers who want to bypass autocapture.
2119
+ * Capture a turn yourself, for a model call autocapture does not see.
2120
+ *
2121
+ * - `turnIndex` is the turn's position in the session, starting at 0.
2122
+ * - `deploymentSlug` may be omitted: the `deployment` given to `init` is
2123
+ * used. An explicit value wins.
2124
+ * - Every turn is sent with a `turnId` (a fresh UUID unless you supply
2125
+ * one). A retried send carries the same `turnId`.
2126
+ * - The turn is checked before it is sent. An invalid turn logs one
2127
+ * warning line naming the first invalid field and is dropped; nothing
2128
+ * is sent.
2129
+ * - A failed send never throws; it logs with `debug: true`. The first
2130
+ * send the API rejects (401, 403, another 4xx) prints one warning
2131
+ * without it.
2127
2132
  *
2128
- * Persona resolution order for the outgoing turn payload:
2129
- * 1. turn.personaSlug (turn-level override)
2130
- * 2. sessions[externalId].personaSlug (from startSession)
2131
- * 3. state.persona.slug (init-level default)
2133
+ * Persona used for the turn, in this order:
2134
+ * 1. turn.personaSlug
2135
+ * 2. the session's persona (from startSession)
2136
+ * 3. the default from init or identifyPersona
2132
2137
  *
2133
- * Signature-phrase matching runs at the SDK edge when the resolved persona
2134
- * has signature phrases registered. The matched slug list is attached to
2135
- * `turn.signaturePhraseMatches` before send.
2138
+ * When that persona has signature phrases, the SDK matches them against
2139
+ * the reply text and sends the matched slugs as
2140
+ * `signaturePhraseMatches`.
2136
2141
  */
2137
- static captureTurn(turn: CapturedTurn): Promise<void>;
2142
+ static captureTurn(turn: CaptureTurnInput): Promise<void>;
2138
2143
  /**
2139
- * Emit a custom outcome event on a session. Populates probe_outcome_events
2140
- * with the customer-supplied `kind` string. Use for
2141
- * customer-defined kinds like "purchase_complete", "handoff_to_human",
2142
- * "character_break_severe". Universal seed kinds (break, escalation,
2143
- * resolution, thumbs_*, rating_*) are also emitted by worker-side
2144
- * detectors automatically — call this only when the customer has a
2145
- * signal the worker cannot infer.
2144
+ * The one capture path. Manual captureTurn calls and autocapture both
2145
+ * land here; autocapture also passes what it observed on the request
2146
+ * (`hints`), applied below under the explicit-input-wins rule.
2147
+ */
2148
+ private static captureWithHints;
2149
+ /**
2150
+ * Record an outcome on a session, stored with the `kind` string you
2151
+ * supply: for example "ticket_resolved", "purchase_complete",
2152
+ * "handoff_to_human". Call it wherever the outcome becomes known, at any
2153
+ * time after the session; it joins to the session by sessionExternalId.
2154
+ * Invalid input logs one warning and is dropped. A failed send never
2155
+ * throws.
2146
2156
  */
2147
2157
  static emitOutcomeEvent(input: OutcomeEventEmit): Promise<void>;
2148
2158
  /**
2149
- * Capture one environment event against a session. The
2150
- * envelope is generalized: `source_type` and `event` are free strings whose
2151
- * meaning is defined per deployment — the instrument stores the event and
2152
- * attaches it to the session's record by time (the next turn's state
2153
- * corner, plus the causing turn's outcome corner when `causeProvenance`
2154
- * names a turn index), and never interprets it. Fire-and-log, like
2155
- * captureTurn: errors are debug-logged, never thrown.
2159
+ * Record one event from a channel beside the conversation (a feed, a
2160
+ * game state, an editor buffer) against a session. `source_type` and
2161
+ * `event` are free strings; you define their meaning. The event is
2162
+ * stored and attached to the session's turns by time, and is not
2163
+ * interpreted. Errors are logged with `debug: true`, never thrown.
2156
2164
  *
2157
- * Alignment defaults to the SDK's own clock claim; deployments with a
2158
- * stricter clock contract (or batches) should call
2159
- * captureEnvironmentEvents with explicit alignment provenance.
2165
+ * `alignment` describes the clock the event's time comes from. It
2166
+ * defaults to this process's clock; to state your own clock, or to send
2167
+ * a batch, call captureEnvironmentEvents.
2160
2168
  */
2161
2169
  static captureEnvironmentEvent(event: EnvironmentEventInput, alignment?: AlignmentProvenance): Promise<void>;
2162
2170
  /**
2163
- * Capture a batch of environment events with explicit alignment provenance
2164
- * (clock_source, skew_bound_ms, rule_version). Batches are capped at 100
2165
- * events and may span sessions — every event is self-addressed. Same
2166
- * generalized envelope and fire-and-log discipline as the single-event
2167
- * capture above.
2171
+ * Record a batch of environment events, with an optional `alignment`
2172
+ * (clock_source, skew_bound_ms, rule_version) describing their clock. At
2173
+ * most 100 events per call. Events in one batch may belong to different
2174
+ * sessions; each names its own. Errors are logged with `debug: true`,
2175
+ * never thrown.
2168
2176
  */
2169
2177
  static captureEnvironmentEvents(events: EnvironmentEventInput[], alignment?: AlignmentProvenance): Promise<void>;
2170
2178
  /**
2171
- * Capture one sub-turn span against a session: one LLM call, one tool
2172
- * call, one framework step, or a custom unit inside a turn. The span lands
2173
- * on the turn named by `turnIndex`, or — when omitted — on the session's
2174
- * latest turn at/under the span's `startedAt` (most recent turn when
2175
- * `startedAt` is also absent). A span whose turn cannot be resolved is
2176
- * dropped server-side; spans never land unattributed. Fire-and-log, like
2177
- * captureTurn: errors are debug-logged, never thrown.
2179
+ * Record one span: a step inside a turn (a model call, a tool call, a
2180
+ * framework step, or a custom unit). The span attaches to the turn named
2181
+ * by `turnIndex`; when omitted, to the session's latest turn at or
2182
+ * before the span's `startedAt` (the most recent turn when `startedAt`
2183
+ * is absent too). A span whose turn cannot be found is dropped by the
2184
+ * server. Errors are logged with `debug: true`, never thrown.
2178
2185
  *
2179
- * `attributes` are metadata only (tool names, argument shapes) — never
2180
- * free-text conversation content. Alignment defaults to the SDK's own
2181
- * clock claim; deployments with a stricter clock contract (or batches, or
2182
- * parent references between spans) should call captureSpans.
2186
+ * `attributes` are metadata only (tool names, argument shapes), never
2187
+ * conversation text. `alignment` defaults to this process's clock; to
2188
+ * state your own clock, send a batch, or link parent and child spans,
2189
+ * call captureSpans.
2183
2190
  */
2184
2191
  static captureSpan(span: SpanInput, alignment?: AlignmentProvenance): Promise<void>;
2185
2192
  /**
2186
- * Capture a batch of spans with explicit alignment provenance
2187
- * (clock_source, skew_bound_ms, rule_version). Batches are capped at 50
2188
- * spans and may span sessions — every span is self-addressed. Parent
2189
- * structure rides the batch: a span's `parentSpanId` names another span's
2190
- * caller-local `spanId` within the same batch and is wired server-side
2191
- * (unresolvable references land null). Same fire-and-log discipline as the
2192
- * single-span capture above.
2193
+ * Record a batch of spans, with an optional `alignment` (clock_source,
2194
+ * skew_bound_ms, rule_version) describing their clock. At most 50 spans
2195
+ * per call. Spans in one batch may belong to different sessions; each
2196
+ * names its own. To link parent and child, give a span a `spanId` and
2197
+ * name it in another span's `parentSpanId` within the same batch; a
2198
+ * reference that matches no span is stored as null. Errors are logged
2199
+ * with `debug: true`, never thrown.
2193
2200
  */
2194
2201
  static captureSpans(spans: SpanInput[], alignment?: AlignmentProvenance): Promise<void>;
2195
2202
  /**
2196
- * Flag a persona break for a session. Wire this to the customer's in-product
2197
- * "that didn't sound like you" UX. Populates the `user_flagged_break`
2198
- * outcome column on the dashboard.
2199
- *
2200
- * If `turnIndex` is omitted, the flag attaches to the session's most
2201
- * recent turn.
2203
+ * Record a person's report that a reply was out of character. Connect it
2204
+ * to your product's report control. With no `turnIndex`, the flag
2205
+ * attaches to the session's most recent turn.
2202
2206
  */
2203
2207
  static flagPersonaBreak(input: FlagPersonaBreakInput): Promise<void>;
2204
2208
  /**
@@ -2208,52 +2212,145 @@ declare class Probe {
2208
2212
  */
2209
2213
  private static extractTextForMatching;
2210
2214
  /**
2211
- * Shut down the SDK: discards the singleton state (sessions, pending
2212
- * user-side signals, the pre-session buffer) so init() can be called
2213
- * again. There is no send queue to flush — every capture awaits its own
2214
- * HTTP send — and instrumentation stays registered for the life of the
2215
- * process. Idempotent.
2215
+ * Shut down the SDK: waits for sends in flight (at most 15 seconds),
2216
+ * then clears the in-memory state (sessions, pending input) so init()
2217
+ * can be called again. Model calls made after shutdown are not captured
2218
+ * until the next init. Await it before a short-lived process exits; a
2219
+ * send still in flight at exit is lost. Safe to call more than once.
2216
2220
  */
2217
2221
  static shutdown(): Promise<void>;
2218
- /** Package-internal: instrumentation adapters read this to build turns. */
2222
+ /** Internal. Not part of the public API. */
2219
2223
  static _getState(): ProbeState | null;
2220
2224
  private static shouldSample;
2221
2225
  }
2222
2226
 
2223
2227
  /**
2224
- * Explicit OpenAI client wrapping — the autocapture path that cannot miss.
2228
+ * Explicit OpenAI client wrapping: the autocapture path that does not
2229
+ * depend on module format, load order, or the openai version.
2225
2230
  *
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.
2231
+ * Module patching (the other path) needs CommonJS and an openai version the
2232
+ * bundled instrumentation supports. wrapOpenAI() wraps the client instance
2233
+ * the caller already holds instead.
2234
2234
  *
2235
2235
  * import OpenAI from 'openai';
2236
- * import { Probe, wrapOpenAI } from '@cultured_computer/sight';
2236
+ * import { Sight, wrapOpenAI } from '@cultured_computer/sight';
2237
2237
  * const openai = wrapOpenAI(new OpenAI());
2238
+ * await Sight.withSession(conversationId, () =>
2239
+ * openai.chat.completions.create({ ... }),
2240
+ * );
2238
2241
  *
2239
2242
  * Covers chat.completions.create and responses.create, streaming included:
2240
2243
  * 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.
2244
+ * emitted when the stream completes. A call is captured only inside a
2245
+ * Sight.withSession() scope; the first call outside one prints one warning.
2246
+ *
2247
+ * A streamed call also records the time to the first token: request start
2248
+ * to the first chunk that carries reply text, a refusal, or a tool call.
2249
+ * A non-streamed call has no first-token time and sends none. A cost is
2250
+ * sent only when the response reports one (`usage.cost`).
2251
+ *
2252
+ * A wrapped client that is also module-patched (CommonJS, `openai` loaded
2253
+ * after init) sends one turn per call, the wrap's: the span the patch
2254
+ * emits for the call is skipped (see ai-dedupe.ts).
2244
2255
  *
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.
2256
+ * wrapOpenAI() may be called before Sight.init(): the wrap passes calls
2257
+ * through untouched until init runs, and warns once if a call happens
2258
+ * before it.
2249
2259
  */
2250
2260
 
2251
2261
  /**
2252
2262
  * 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).
2263
+ * responses.create call made inside a Sight.withSession() scope is captured
2264
+ * as a turn. Returns the same client. Idempotent; safe to call before
2265
+ * Sight.init() (capture starts once init has run). A call outside any
2266
+ * session scope is not captured; the first one prints one warning.
2256
2267
  */
2257
2268
  declare function wrapOpenAI<T extends object>(client: T): T;
2258
2269
 
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 };
2270
+ /**
2271
+ * Vercel AI SDK (`ai`) autocapture.
2272
+ *
2273
+ * `ai` 7 creates no OpenTelemetry spans itself. It calls the telemetry
2274
+ * integrations registered with `registerTelemetry()` (kept on the global
2275
+ * `AI_SDK_TELEMETRY_INTEGRATIONS`), and once one integration is registered
2276
+ * every call emits events with no per-call flag. This file is that
2277
+ * integration: Sight.init() registers it when `ai` 7 is resolvable, and
2278
+ * `sightTelemetry()` exports it for hosts that register it themselves.
2279
+ *
2280
+ * The turn unit is ONE MODEL CALL (one step of `generateText` / `streamText`,
2281
+ * or the single call of `generateObject` / `streamObject`), the same unit
2282
+ * wrapOpenAI and the span processor use. A tool loop of N model calls is N
2283
+ * turns: each carries the text of that reply (which may be empty when the
2284
+ * model only requested tools) and the tool names it requested. The outer
2285
+ * `generateText` operation is never a turn.
2286
+ *
2287
+ * Events used (interface `Telemetry` of `ai` 7):
2288
+ * onStart session scope and runtimeContext of the call
2289
+ * onStepStart runtimeContext of the step
2290
+ * onLanguageModelCallStart request instructions and messages
2291
+ * executeLanguageModelCall marks the provider call (see ai-dedupe.ts)
2292
+ * onLanguageModelCallEnd provider response id (see ai-dedupe.ts)
2293
+ * onStepEnd the turn: reply, model, usage, finish, timing
2294
+ * onObjectStepStart / End the same for generateObject / streamObject
2295
+ * onError / onAbort a model call that failed or was aborted
2296
+ * onEnd releases the per-call state
2297
+ * `onStepFinish` is deliberately not implemented: `ai` 7 sends every step
2298
+ * end to both names, and `ai` 6 (which has no `onStepEnd`) is captured
2299
+ * through its OpenTelemetry spans instead (see otel-processor.ts).
2300
+ *
2301
+ * `ai` 3 to 6 are not handled here. `ai` 6 emits `ai.*` OpenTelemetry spans
2302
+ * when a call sets `experimental_telemetry: { isEnabled: true }`; the span
2303
+ * processor maps those.
2304
+ */
2305
+
2306
+ /** Options for `sightTelemetry()`. */
2307
+ type SightAiTelemetryOptions = {
2308
+ /**
2309
+ * The session the calls this integration sees belong to, for a call made
2310
+ * outside any Sight.withSession() scope. An explicit scope wins.
2311
+ */
2312
+ sessionId?: string;
2313
+ };
2314
+ /**
2315
+ * The Sight telemetry integration for the Vercel AI SDK (`ai` 7). It is
2316
+ * structurally a `Telemetry` from `ai`: pass it to `registerTelemetry()` or
2317
+ * to a call's `telemetry.integrations`.
2318
+ */
2319
+ type SightAiTelemetry = {
2320
+ readonly name: 'sight';
2321
+ onStart(event: unknown): void;
2322
+ onStepStart(event: unknown): void;
2323
+ onLanguageModelCallStart(event: unknown): void;
2324
+ onLanguageModelCallEnd(event: unknown): void;
2325
+ onStepEnd(event: unknown): void;
2326
+ onObjectStepStart(event: unknown): void;
2327
+ onObjectStepEnd(event: unknown): void;
2328
+ onEnd(event: unknown): void;
2329
+ onAbort(event: unknown): void;
2330
+ onError(event: unknown): void;
2331
+ executeLanguageModelCall<T>(options: {
2332
+ execute: () => PromiseLike<T>;
2333
+ }): PromiseLike<T>;
2334
+ };
2335
+ /**
2336
+ * The Sight telemetry integration for the Vercel AI SDK (`ai` 7).
2337
+ *
2338
+ * Sight.init() registers it when `ai` is resolvable. Call this yourself when
2339
+ * that cannot work (a bundle where the SDK cannot resolve the host's `ai`):
2340
+ *
2341
+ * import { registerTelemetry } from 'ai';
2342
+ * import { sightTelemetry } from '@cultured_computer/sight';
2343
+ * registerTelemetry(sightTelemetry());
2344
+ *
2345
+ * or per call, with the session the call belongs to:
2346
+ *
2347
+ * generateText({ model, prompt,
2348
+ * telemetry: { integrations: sightTelemetry({ sessionId }) } });
2349
+ *
2350
+ * With no options it returns one shared instance, so Sight.init() does not
2351
+ * register it a second time. Safe to call before Sight.init(): nothing is
2352
+ * captured until init runs.
2353
+ */
2354
+ declare function sightTelemetry(options?: SightAiTelemetryOptions): SightAiTelemetry;
2355
+
2356
+ 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 };