@cultured_computer/sight 0.2.0 → 0.3.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/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
@@ -5,6 +5,7 @@ var api = require('@opentelemetry/api');
5
5
 
6
6
  // src/client.ts
7
7
  var DEFAULT_DASHBOARD_URL = "https://field.cultured.computer/dashboard";
8
+ var MAX_PENDING_RETRIES = 50;
8
9
  var IngestClient = class {
9
10
  apiKey;
10
11
  endpoint;
@@ -20,6 +21,15 @@ var IngestClient = class {
20
21
  * arriving before any turn is not a captured session).
21
22
  */
22
23
  firstCaptureAnnounced = false;
24
+ /**
25
+ * Rate-limit (429) handling: the first 429 per process prints one stderr
26
+ * warning (not debug-gated, same channel and lifetime as the first-capture
27
+ * announce); subsequent 429s only debug-log. Each rate-limited request is
28
+ * retried exactly once after Retry-After; pendingRetries counts retries
29
+ * waiting on their timers so the cap can shed load.
30
+ */
31
+ rateLimitAnnounced = false;
32
+ pendingRetries = 0;
23
33
  constructor(opts) {
24
34
  this.apiKey = opts.apiKey;
25
35
  this.endpoint = opts.endpoint.replace(/\/$/, "");
@@ -32,7 +42,7 @@ var IngestClient = class {
32
42
  */
33
43
  async sendTurn(turn) {
34
44
  try {
35
- const response = await fetch(`${this.endpoint}/v1/turns`, {
45
+ const send = () => fetch(`${this.endpoint}/v1/turns`, {
36
46
  method: "POST",
37
47
  headers: {
38
48
  Authorization: `Bearer ${this.apiKey}`,
@@ -40,6 +50,8 @@ var IngestClient = class {
40
50
  },
41
51
  body: JSON.stringify(turn)
42
52
  });
53
+ const response = await this.retryIfRateLimited(await send(), send);
54
+ if (response === null) return;
43
55
  if (!response.ok) {
44
56
  this.log(`[probe] ingest failed status=${response.status}`);
45
57
  return;
@@ -65,7 +77,7 @@ var IngestClient = class {
65
77
  */
66
78
  async sendFlag(deploymentSlug, flag) {
67
79
  try {
68
- const response = await fetch(`${this.endpoint}/v1/flags`, {
80
+ const send = () => fetch(`${this.endpoint}/v1/flags`, {
69
81
  method: "POST",
70
82
  headers: {
71
83
  Authorization: `Bearer ${this.apiKey}`,
@@ -79,6 +91,8 @@ var IngestClient = class {
79
91
  turnIndex: flag.turnIndex
80
92
  })
81
93
  });
94
+ const response = await this.retryIfRateLimited(await send(), send);
95
+ if (response === null) return;
82
96
  if (!response.ok) {
83
97
  this.log(`[probe] flag ingest failed status=${response.status}`);
84
98
  return;
@@ -97,7 +111,7 @@ var IngestClient = class {
97
111
  */
98
112
  async sendSessionEnd(deploymentSlug, end) {
99
113
  try {
100
- const response = await fetch(`${this.endpoint}/v1/sessions/end`, {
114
+ const send = () => fetch(`${this.endpoint}/v1/sessions/end`, {
101
115
  method: "POST",
102
116
  headers: {
103
117
  Authorization: `Bearer ${this.apiKey}`,
@@ -109,6 +123,8 @@ var IngestClient = class {
109
123
  endedReason: end.endedReason
110
124
  })
111
125
  });
126
+ const response = await this.retryIfRateLimited(await send(), send);
127
+ if (response === null) return;
112
128
  if (!response.ok) {
113
129
  this.log(`[probe] session-end ingest failed status=${response.status}`);
114
130
  return;
@@ -127,7 +143,7 @@ var IngestClient = class {
127
143
  */
128
144
  async sendOutcomeEvent(deploymentSlug, event) {
129
145
  try {
130
- const response = await fetch(`${this.endpoint}/v1/outcome-events`, {
146
+ const send = () => fetch(`${this.endpoint}/v1/outcome-events`, {
131
147
  method: "POST",
132
148
  headers: {
133
149
  Authorization: `Bearer ${this.apiKey}`,
@@ -142,6 +158,8 @@ var IngestClient = class {
142
158
  detail: event.detail
143
159
  })
144
160
  });
161
+ const response = await this.retryIfRateLimited(await send(), send);
162
+ if (response === null) return;
145
163
  if (!response.ok) {
146
164
  this.log(`[probe] outcome-event ingest failed status=${response.status}`);
147
165
  return;
@@ -156,6 +174,73 @@ var IngestClient = class {
156
174
  this.log(`[probe] outcome-event ingest error: ${msg}`);
157
175
  }
158
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
+ }
206
+ /**
207
+ * Route a send response through the 429 retry policy. Non-429 responses
208
+ * pass through untouched. A 429 is re-sent exactly once after Retry-After
209
+ * seconds (default 1s when the header is missing or unparseable; clamped
210
+ * to [1, 60]s); the retry's response is returned as-is, so a second 429 is
211
+ * never retried again — callers log and drop it like any other failed
212
+ * send. Returns null when the retry was dropped at the pending-retry cap.
213
+ * The timer is unref'd (where supported) so a pending retry never holds
214
+ * the process open.
215
+ */
216
+ async retryIfRateLimited(response, resend) {
217
+ if (response.status !== 429) return response;
218
+ if (!this.rateLimitAnnounced) {
219
+ this.rateLimitAnnounced = true;
220
+ console.error(
221
+ "Sight: ingest rate limit (429) \u2014 retrying once per Retry-After; sustained limiting drops captures. See https://field.cultured.computer/sight/sdk-reference#rate-limits"
222
+ );
223
+ } else {
224
+ this.log("[probe] ingest rate limited (429), retrying once");
225
+ }
226
+ if (this.pendingRetries >= MAX_PENDING_RETRIES) {
227
+ this.log("[probe] retry buffer full, dropped");
228
+ return null;
229
+ }
230
+ const raw = response.headers.get("retry-after");
231
+ const parsed = raw === null ? Number.NaN : Number(raw);
232
+ const seconds = Number.isFinite(parsed) ? Math.min(Math.max(parsed, 1), 60) : 1;
233
+ this.pendingRetries += 1;
234
+ try {
235
+ await new Promise((resolve) => {
236
+ const timer = setTimeout(resolve, seconds * 1e3);
237
+ timer.unref?.();
238
+ });
239
+ return await resend();
240
+ } finally {
241
+ this.pendingRetries -= 1;
242
+ }
243
+ }
159
244
  log(msg) {
160
245
  if (this.debug) {
161
246
  console.error(msg);
@@ -1102,6 +1187,35 @@ zod.z.object({
1102
1187
  seed: zod.z.number().int(),
1103
1188
  startDate: zod.z.string()
1104
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
+ });
1105
1219
  zod.z.object({
1106
1220
  deploymentSlug: zod.z.string().min(1),
1107
1221
  sessionExternalId: zod.z.string().min(1),
@@ -1119,6 +1233,10 @@ zod.z.object({
1119
1233
 
1120
1234
  // src/probe.ts
1121
1235
  var PRE_SESSION_BUFFER_MAX = 100;
1236
+ var DEFAULT_ENVIRONMENT_ALIGNMENT = {
1237
+ clock_source: "sdk",
1238
+ rule_version: "v1"
1239
+ };
1122
1240
  var state = null;
1123
1241
  var Probe = class {
1124
1242
  /**
@@ -1579,6 +1697,43 @@ var Probe = class {
1579
1697
  const validated = OutcomeEventEmitSchema.parse(input);
1580
1698
  await state.client.sendOutcomeEvent(state.config.deployment, validated);
1581
1699
  }
1700
+ /**
1701
+ * Capture one environment event against a session (Arc D-rail). The
1702
+ * envelope is generalized: `source_type` and `event` are free strings whose
1703
+ * meaning is defined per deployment — the instrument stores the event and
1704
+ * attaches it to the session's record by time (the next turn's state
1705
+ * corner, plus the causing turn's outcome corner when `causeProvenance`
1706
+ * names a turn index), and never interprets it. Fire-and-log, like
1707
+ * captureTurn: errors are debug-logged, never thrown.
1708
+ *
1709
+ * Alignment defaults to the SDK's own clock claim; deployments with a
1710
+ * stricter clock contract (or batches) should call
1711
+ * captureEnvironmentEvents with explicit alignment provenance.
1712
+ */
1713
+ static async captureEnvironmentEvent(event, alignment) {
1714
+ if (state === null) {
1715
+ console.warn("[probe] captureEnvironmentEvent called before init");
1716
+ return;
1717
+ }
1718
+ const validated = EnvironmentEventInputSchema.parse(event);
1719
+ const align = alignment ? AlignmentProvenanceSchema.parse(alignment) : DEFAULT_ENVIRONMENT_ALIGNMENT;
1720
+ await state.client.sendEnvironmentEvents({ events: [validated], alignment: align });
1721
+ }
1722
+ /**
1723
+ * Capture a batch of environment events with explicit alignment provenance
1724
+ * (clock_source, skew_bound_ms, rule_version). Batches are capped at 100
1725
+ * events and may span sessions — every event is self-addressed. Same
1726
+ * generalized envelope and fire-and-log discipline as the single-event
1727
+ * capture above.
1728
+ */
1729
+ static async captureEnvironmentEvents(events, alignment) {
1730
+ if (state === null) {
1731
+ console.warn("[probe] captureEnvironmentEvents called before init");
1732
+ return;
1733
+ }
1734
+ const batch = EnvironmentEventsBatchSchema.parse({ events, alignment });
1735
+ await state.client.sendEnvironmentEvents(batch);
1736
+ }
1582
1737
  /**
1583
1738
  * Flag a persona break for a session. Wire this to the customer's in-product
1584
1739
  * "that didn't sound like you" UX. Populates the `user_flagged_break`