@cultured_computer/sight 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -76,6 +76,26 @@ await Sight.emitOutcomeEvent({
76
76
  })
77
77
  ```
78
78
 
79
+ ## Capture environment events
80
+
81
+ Deployments that run alongside a non-dialogue channel — a stimulus feed, a
82
+ game state stream, an editor buffer — can record that channel's events
83
+ against the conversation:
84
+
85
+ ```ts
86
+ await Sight.captureEnvironmentEvents(events, {
87
+ clock_source: 'my-event-clock',
88
+ skew_bound_ms: 25,
89
+ rule_version: 'v1',
90
+ })
91
+ ```
92
+
93
+ The envelope is generalized: `source_type` and `event` are free strings whose
94
+ meaning is defined per deployment. The instrument attaches events to turns by
95
+ time — the next turn's state corner, plus the causing turn's outcome corner
96
+ when the event carries a `causeProvenance` turn reference — and never
97
+ interprets them.
98
+
79
99
  ## Scope
80
100
 
81
101
  Sight is a measurement system: it reports what a deployment did. It does not
package/dist/index.cjs CHANGED
@@ -174,6 +174,35 @@ var IngestClient = class {
174
174
  this.log(`[probe] outcome-event ingest error: ${msg}`);
175
175
  }
176
176
  }
177
+ /**
178
+ * Send an environment-event batch to the ingest API. Fire-and-log, same as
179
+ * sendTurn. The envelope is generalized: the worker attaches each event to
180
+ * its session's record by time; meaning is per-deployment.
181
+ */
182
+ async sendEnvironmentEvents(batch) {
183
+ try {
184
+ const send = () => fetch(`${this.endpoint}/v1/environment-events`, {
185
+ method: "POST",
186
+ headers: {
187
+ Authorization: `Bearer ${this.apiKey}`,
188
+ "content-type": "application/json"
189
+ },
190
+ body: JSON.stringify(batch)
191
+ });
192
+ const response = await this.retryIfRateLimited(await send(), send);
193
+ if (response === null) return;
194
+ if (!response.ok) {
195
+ this.log(`[probe] environment-events ingest failed status=${response.status}`);
196
+ return;
197
+ }
198
+ if (this.debug) {
199
+ this.log(`[probe] environment-events ingest ok events=${batch.events.length}`);
200
+ }
201
+ } catch (err) {
202
+ const msg = err instanceof Error ? err.message : String(err);
203
+ this.log(`[probe] environment-events ingest error: ${msg}`);
204
+ }
205
+ }
177
206
  /**
178
207
  * Route a send response through the 429 retry policy. Non-429 responses
179
208
  * pass through untouched. A 429 is re-sent exactly once after Retry-After
@@ -263,8 +292,8 @@ var ProbeConfigSchema = zod.z.object({
263
292
  apiKey: zod.z.string().min(1),
264
293
  /** Deployment slug registered in the Probe backend. Required. */
265
294
  deployment: zod.z.string().min(1),
266
- /** Ingest endpoint. Defaults to https://ingest.probe.io. */
267
- endpoint: zod.z.string().url().default("https://ingest.probe.io"),
295
+ /** Ingest endpoint. Defaults to the production ingest service. */
296
+ endpoint: zod.z.string().url().default("https://fieldwork-ingest.fly.dev"),
268
297
  /**
269
298
  * Dashboard base URL used by the one-time first-capture announcement
270
299
  * (the stderr permalink printed after the first successful send).
@@ -1158,6 +1187,74 @@ zod.z.object({
1158
1187
  seed: zod.z.number().int(),
1159
1188
  startDate: zod.z.string()
1160
1189
  });
1190
+ var EnvironmentEventInputSchema = zod.z.object({
1191
+ /** Free-form channel label (e.g. a stimulus feed, a game state stream). Open vocabulary — NOT an enum. */
1192
+ source_type: zod.z.string().min(1),
1193
+ /** Free-form event name. Open vocabulary — NOT an enum. */
1194
+ event: zod.z.string().min(1),
1195
+ /** ISO timestamp of the event on the deployer's clock (see alignment). */
1196
+ at: zod.z.string().datetime(),
1197
+ /** Optional detail payload (deployer-defined). */
1198
+ meta: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
1199
+ sessionExternalId: zod.z.string().min(1),
1200
+ deploymentSlug: zod.z.string().min(1),
1201
+ /**
1202
+ * Optional reference to the causing turn. v1 resolves a turn index within
1203
+ * the same session (string-encoded integer); any other value is stored
1204
+ * verbatim on the event record without an outcome-corner link. The
1205
+ * instrument records the reference only — no causal inference.
1206
+ */
1207
+ causeProvenance: zod.z.string().min(1).optional()
1208
+ });
1209
+ var AlignmentProvenanceSchema = zod.z.object({
1210
+ clock_source: zod.z.string().min(1),
1211
+ skew_bound_ms: zod.z.number().nonnegative().optional(),
1212
+ rule_version: zod.z.string().min(1)
1213
+ });
1214
+ var EnvironmentEventsBatchSchema = zod.z.object({
1215
+ /** Events are self-addressed: a batch may span sessions/deployments. */
1216
+ events: zod.z.array(EnvironmentEventInputSchema).min(1).max(100),
1217
+ alignment: AlignmentProvenanceSchema
1218
+ });
1219
+ var DEFINITION_SLUG = /^[a-z][a-z0-9_-]{0,63}$/;
1220
+ var DEFINITION_VALUE = zod.z.string().trim().min(1).max(64);
1221
+ zod.z.object({
1222
+ /** Measurement family the definition belongs to (e.g. 'voice-conformance'). */
1223
+ family: zod.z.string().regex(DEFINITION_SLUG, "family must be a lowercase slug (a-z, 0-9, _-)."),
1224
+ /** Slug within the family. family+name identifies the definition across versions. */
1225
+ name: zod.z.string().regex(DEFINITION_SLUG, "name must be a lowercase slug (a-z, 0-9, _-)."),
1226
+ /** The elicitation prompt — the queue row's plain-language question. */
1227
+ question: zod.z.string().trim().min(1).max(280),
1228
+ /** Difference metric for α (Krippendorff). Elicit v1: nominal | ordinal. */
1229
+ metric: zod.z.enum(["nominal", "ordinal"]),
1230
+ /** The chips (closed vocabulary the rater chooses from). */
1231
+ values: zod.z.array(DEFINITION_VALUE).min(2, "A rubric needs at least two chips.").max(9, "The queue is keyboard-first \u2014 at most 9 chips."),
1232
+ /** Rank order (lowest first) — required iff metric is 'ordinal'. */
1233
+ ordinalScale: zod.z.array(DEFINITION_VALUE).min(2).max(9).optional()
1234
+ }).refine((input) => new Set(input.values).size === input.values.length, {
1235
+ message: "Chips must be unique.",
1236
+ path: ["values"]
1237
+ }).superRefine((input, ctx) => {
1238
+ if (input.metric === "ordinal") {
1239
+ const scale = input.ordinalScale;
1240
+ if (!scale) {
1241
+ ctx.addIssue({
1242
+ code: zod.z.ZodIssueCode.custom,
1243
+ message: "ordinalScale is required when metric is ordinal.",
1244
+ path: ["ordinalScale"]
1245
+ });
1246
+ return;
1247
+ }
1248
+ const same = scale.length === input.values.length && [...scale].sort().join("") === [...input.values].sort().join("");
1249
+ if (!same) {
1250
+ ctx.addIssue({
1251
+ code: zod.z.ZodIssueCode.custom,
1252
+ message: "ordinalScale must be exactly the chips in rank order (lowest first).",
1253
+ path: ["ordinalScale"]
1254
+ });
1255
+ }
1256
+ }
1257
+ });
1161
1258
  zod.z.object({
1162
1259
  deploymentSlug: zod.z.string().min(1),
1163
1260
  sessionExternalId: zod.z.string().min(1),
@@ -1175,6 +1272,10 @@ zod.z.object({
1175
1272
 
1176
1273
  // src/probe.ts
1177
1274
  var PRE_SESSION_BUFFER_MAX = 100;
1275
+ var DEFAULT_ENVIRONMENT_ALIGNMENT = {
1276
+ clock_source: "sdk",
1277
+ rule_version: "v1"
1278
+ };
1178
1279
  var state = null;
1179
1280
  var Probe = class {
1180
1281
  /**
@@ -1512,7 +1613,7 @@ var Probe = class {
1512
1613
  const contract = validatePropensityContract(propensity);
1513
1614
  if (!contract.ok) {
1514
1615
  console.warn(
1515
- `[probe] Amendment S contract violation (${contract.class}): ${contract.reason}`
1616
+ `[sight] propensity contract violation (${contract.class}): ${contract.reason}`
1516
1617
  );
1517
1618
  turn.payload.propensity = void 0;
1518
1619
  validPropensity = void 0;
@@ -1635,6 +1736,43 @@ var Probe = class {
1635
1736
  const validated = OutcomeEventEmitSchema.parse(input);
1636
1737
  await state.client.sendOutcomeEvent(state.config.deployment, validated);
1637
1738
  }
1739
+ /**
1740
+ * Capture one environment event against a session (Arc D-rail). The
1741
+ * envelope is generalized: `source_type` and `event` are free strings whose
1742
+ * meaning is defined per deployment — the instrument stores the event and
1743
+ * attaches it to the session's record by time (the next turn's state
1744
+ * corner, plus the causing turn's outcome corner when `causeProvenance`
1745
+ * names a turn index), and never interprets it. Fire-and-log, like
1746
+ * captureTurn: errors are debug-logged, never thrown.
1747
+ *
1748
+ * Alignment defaults to the SDK's own clock claim; deployments with a
1749
+ * stricter clock contract (or batches) should call
1750
+ * captureEnvironmentEvents with explicit alignment provenance.
1751
+ */
1752
+ static async captureEnvironmentEvent(event, alignment) {
1753
+ if (state === null) {
1754
+ console.warn("[probe] captureEnvironmentEvent called before init");
1755
+ return;
1756
+ }
1757
+ const validated = EnvironmentEventInputSchema.parse(event);
1758
+ const align = alignment ? AlignmentProvenanceSchema.parse(alignment) : DEFAULT_ENVIRONMENT_ALIGNMENT;
1759
+ await state.client.sendEnvironmentEvents({ events: [validated], alignment: align });
1760
+ }
1761
+ /**
1762
+ * Capture a batch of environment events with explicit alignment provenance
1763
+ * (clock_source, skew_bound_ms, rule_version). Batches are capped at 100
1764
+ * events and may span sessions — every event is self-addressed. Same
1765
+ * generalized envelope and fire-and-log discipline as the single-event
1766
+ * capture above.
1767
+ */
1768
+ static async captureEnvironmentEvents(events, alignment) {
1769
+ if (state === null) {
1770
+ console.warn("[probe] captureEnvironmentEvents called before init");
1771
+ return;
1772
+ }
1773
+ const batch = EnvironmentEventsBatchSchema.parse({ events, alignment });
1774
+ await state.client.sendEnvironmentEvents(batch);
1775
+ }
1638
1776
  /**
1639
1777
  * Flag a persona break for a session. Wire this to the customer's in-product
1640
1778
  * "that didn't sound like you" UX. Populates the `user_flagged_break`