@superbased/sdk 0.0.0-stage → 0.1.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.
Files changed (119) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +438 -2
  4. package/dist/cjs/admit.d.ts +139 -0
  5. package/dist/cjs/admit.js +442 -0
  6. package/dist/cjs/admit.js.map +1 -0
  7. package/dist/cjs/attrs.d.ts +113 -0
  8. package/dist/cjs/attrs.js +183 -0
  9. package/dist/cjs/attrs.js.map +1 -0
  10. package/dist/cjs/config.d.ts +202 -0
  11. package/dist/cjs/config.js +386 -0
  12. package/dist/cjs/config.js.map +1 -0
  13. package/dist/cjs/context.d.ts +102 -0
  14. package/dist/cjs/context.js +234 -0
  15. package/dist/cjs/context.js.map +1 -0
  16. package/dist/cjs/control.d.ts +99 -0
  17. package/dist/cjs/control.js +243 -0
  18. package/dist/cjs/control.js.map +1 -0
  19. package/dist/cjs/cost.d.ts +108 -0
  20. package/dist/cjs/cost.js +211 -0
  21. package/dist/cjs/cost.js.map +1 -0
  22. package/dist/cjs/destination.d.ts +125 -0
  23. package/dist/cjs/destination.js +357 -0
  24. package/dist/cjs/destination.js.map +1 -0
  25. package/dist/cjs/experiments.d.ts +237 -0
  26. package/dist/cjs/experiments.js +678 -0
  27. package/dist/cjs/experiments.js.map +1 -0
  28. package/dist/cjs/export.d.ts +84 -0
  29. package/dist/cjs/export.js +328 -0
  30. package/dist/cjs/export.js.map +1 -0
  31. package/dist/cjs/index.d.ts +168 -0
  32. package/dist/cjs/index.js +581 -0
  33. package/dist/cjs/index.js.map +1 -0
  34. package/dist/cjs/instrument.d.ts +88 -0
  35. package/dist/cjs/instrument.js +397 -0
  36. package/dist/cjs/instrument.js.map +1 -0
  37. package/dist/cjs/package.json +1 -0
  38. package/dist/cjs/policy.d.ts +77 -0
  39. package/dist/cjs/policy.js +252 -0
  40. package/dist/cjs/policy.js.map +1 -0
  41. package/dist/cjs/prompts.d.ts +175 -0
  42. package/dist/cjs/prompts.js +476 -0
  43. package/dist/cjs/prompts.js.map +1 -0
  44. package/dist/cjs/propagation.d.ts +34 -0
  45. package/dist/cjs/propagation.js +151 -0
  46. package/dist/cjs/propagation.js.map +1 -0
  47. package/dist/cjs/req.d.ts +10 -0
  48. package/dist/cjs/req.js +3 -0
  49. package/dist/cjs/req.js.map +1 -0
  50. package/dist/cjs/runtime.d.ts +44 -0
  51. package/dist/cjs/runtime.js +67 -0
  52. package/dist/cjs/runtime.js.map +1 -0
  53. package/dist/cjs/scores.d.ts +102 -0
  54. package/dist/cjs/scores.js +226 -0
  55. package/dist/cjs/scores.js.map +1 -0
  56. package/dist/cjs/spans.d.ts +193 -0
  57. package/dist/cjs/spans.js +398 -0
  58. package/dist/cjs/spans.js.map +1 -0
  59. package/dist/cjs/vendor.d.ts +33 -0
  60. package/dist/cjs/vendor.js +67 -0
  61. package/dist/cjs/vendor.js.map +1 -0
  62. package/dist/esm/admit.d.ts +139 -0
  63. package/dist/esm/admit.js +432 -0
  64. package/dist/esm/admit.js.map +1 -0
  65. package/dist/esm/attrs.d.ts +113 -0
  66. package/dist/esm/attrs.js +179 -0
  67. package/dist/esm/attrs.js.map +1 -0
  68. package/dist/esm/config.d.ts +202 -0
  69. package/dist/esm/config.js +364 -0
  70. package/dist/esm/config.js.map +1 -0
  71. package/dist/esm/context.d.ts +102 -0
  72. package/dist/esm/context.js +221 -0
  73. package/dist/esm/context.js.map +1 -0
  74. package/dist/esm/control.d.ts +99 -0
  75. package/dist/esm/control.js +230 -0
  76. package/dist/esm/control.js.map +1 -0
  77. package/dist/esm/cost.d.ts +108 -0
  78. package/dist/esm/cost.js +202 -0
  79. package/dist/esm/cost.js.map +1 -0
  80. package/dist/esm/destination.d.ts +125 -0
  81. package/dist/esm/destination.js +346 -0
  82. package/dist/esm/destination.js.map +1 -0
  83. package/dist/esm/experiments.d.ts +237 -0
  84. package/dist/esm/experiments.js +666 -0
  85. package/dist/esm/experiments.js.map +1 -0
  86. package/dist/esm/export.d.ts +84 -0
  87. package/dist/esm/export.js +314 -0
  88. package/dist/esm/export.js.map +1 -0
  89. package/dist/esm/index.d.ts +168 -0
  90. package/dist/esm/index.js +500 -0
  91. package/dist/esm/index.js.map +1 -0
  92. package/dist/esm/instrument.d.ts +88 -0
  93. package/dist/esm/instrument.js +391 -0
  94. package/dist/esm/instrument.js.map +1 -0
  95. package/dist/esm/policy.d.ts +77 -0
  96. package/dist/esm/policy.js +240 -0
  97. package/dist/esm/policy.js.map +1 -0
  98. package/dist/esm/prompts.d.ts +175 -0
  99. package/dist/esm/prompts.js +460 -0
  100. package/dist/esm/prompts.js.map +1 -0
  101. package/dist/esm/propagation.d.ts +34 -0
  102. package/dist/esm/propagation.js +145 -0
  103. package/dist/esm/propagation.js.map +1 -0
  104. package/dist/esm/req.d.ts +10 -0
  105. package/dist/esm/req.js +2 -0
  106. package/dist/esm/req.js.map +1 -0
  107. package/dist/esm/runtime.d.ts +44 -0
  108. package/dist/esm/runtime.js +59 -0
  109. package/dist/esm/runtime.js.map +1 -0
  110. package/dist/esm/scores.d.ts +102 -0
  111. package/dist/esm/scores.js +219 -0
  112. package/dist/esm/scores.js.map +1 -0
  113. package/dist/esm/spans.d.ts +193 -0
  114. package/dist/esm/spans.js +378 -0
  115. package/dist/esm/spans.js.map +1 -0
  116. package/dist/esm/vendor.d.ts +33 -0
  117. package/dist/esm/vendor.js +61 -0
  118. package/dist/esm/vendor.js.map +1 -0
  119. package/package.json +130 -4
@@ -0,0 +1,346 @@
1
+ /**
2
+ * Data destination (D18; contract `contracts/destination.md`, lane B6).
3
+ *
4
+ * - `local`: this machine's Observer only.
5
+ * - `online`: the org or SaaS gateway only.
6
+ * - `both`: the SDK exports to each itself, through its own exporter, so one
7
+ * failing destination never blocks the other and `both` never depends on
8
+ * the machine's push tiers.
9
+ *
10
+ * The choice, first set wins: the `destination` option, then
11
+ * `SUPERBASED_DESTINATION`, then the default this machine advertises at
12
+ * `GET <nodeUrl>/api/sdk/destination` (loopback only, 500 ms, one attempt),
13
+ * then `online` when no machine answered and the app was given a gateway and
14
+ * a credential (`inferred`, a production app), then `local`. Discovery also
15
+ * runs for an explicit `online` / `both` that still lacks a gateway URL or a
16
+ * credential, which the machine supplies (review finding R-B09), and for an
17
+ * explicit `local` / `both` with no endpoint the app named for the local
18
+ * destination: the machine advertises its own receiver (live finding L-01).
19
+ * An explicit `endpoint` only sets where the local destination sends.
20
+ *
21
+ * The gateway URL: `orgUrl`, `SUPERBASED_ORG_URL`, then the `gateway_url`
22
+ * line of the machine's credential file. The credential: `apiKey`,
23
+ * `SUPERBASED_API_KEY`, then that file's key line. The file is read only
24
+ * after the owner, mode and symlink checks of contract section 6. The
25
+ * discovery answer never decides where the key goes (review E-04): it only
26
+ * names the file, and its local URLs are used only when they are loopback.
27
+ * The machine never sends the credential itself.
28
+ *
29
+ * While discovery runs, finished spans wait in a bounded queue and then go
30
+ * to the chosen destination; none are sent to a guess.
31
+ */
32
+ import { closeSync, constants as fsConstants, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
33
+ import { DESTINATION_CHOICES, trimSlash } from "./config.js";
34
+ import { legsOf, stats } from "./export.js";
35
+ /** The machine's discovery route (contract section 4). */
36
+ export const DISCOVERY_PATH = "/api/sdk/destination";
37
+ export const DISCOVERY_API_VERSION = 1;
38
+ /** Most spans held while the destination is being discovered. */
39
+ export const DISCOVERY_QUEUE_MAX = 2048;
40
+ function obj(v) {
41
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
42
+ }
43
+ /** Parse the discovery body; null when it is not a usable api_version 1 answer. */
44
+ export function parseDiscovery(body) {
45
+ const d = obj(body);
46
+ if (d.api_version !== DISCOVERY_API_VERSION)
47
+ return null;
48
+ const rawDest = typeof d.destination === "string" ? d.destination.trim().toLowerCase() : "";
49
+ const destKnown = DESTINATION_CHOICES.includes(rawDest);
50
+ const dest = destKnown ? rawDest : "local";
51
+ const local = obj(d.local);
52
+ const online = obj(d.online);
53
+ const s = (o, k) => (typeof o[k] === "string" ? o[k].trim() : "");
54
+ // The machine's receiver and admission check are on this machine: a remote
55
+ // address there is not the machine speaking (review E-04).
56
+ const refused = [];
57
+ const unknownDest = destKnown ? [] : [`the discovery answer names an unknown destination ${JSON.stringify(rawDest)}; using local`];
58
+ const loopback = (k) => {
59
+ const v = s(local, k);
60
+ if (v && !isLoopbackUrl(v)) {
61
+ refused.push(`the machine's discovery answer names a non-loopback ${k} (${v}); ignored`);
62
+ return "";
63
+ }
64
+ return v;
65
+ };
66
+ return {
67
+ destination: dest,
68
+ source: s(d, "source"),
69
+ signedIn: d.signed_in === true,
70
+ localEnabled: local.enabled !== false,
71
+ localTracesUrl: loopback("otlp_traces_url"),
72
+ admissionUrl: loopback("admission_url"),
73
+ gatewayUrl: trimSlash(s(online, "gateway_url")),
74
+ credentialPresent: online.credential_present === true,
75
+ credentialFile: s(online, "credential_file"),
76
+ warnings: [...(Array.isArray(d.warnings) ? d.warnings.filter((w) => typeof w === "string") : []), ...unknownDest],
77
+ refused,
78
+ };
79
+ }
80
+ /** Whether a URL's host is loopback (the only hosts discovery is sent to). */
81
+ export function isLoopbackUrl(url) {
82
+ try {
83
+ const h = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
84
+ return h === "localhost" || h === "::1" || /^127\.\d+\.\d+\.\d+$/.test(h);
85
+ }
86
+ catch {
87
+ return false;
88
+ }
89
+ }
90
+ /**
91
+ * The longest discovery waits on a busy event loop (see discoverDestination),
92
+ * or ten windows when the window is longer.
93
+ */
94
+ export const DISCOVERY_WALL_CAP_MS = 5000;
95
+ /**
96
+ * What a discovery window's timer does when it fires at `now` (it was due at
97
+ * `due`): "rearm" when it fired late (the event loop was busy, so the
98
+ * machine's answer may be waiting behind it) and the wall cap `giveUpAt` is
99
+ * not reached; otherwise "abort".
100
+ */
101
+ export function discoveryTimerStep(now, due, giveUpAt, timeoutMs) {
102
+ const lateBy = Math.max(50, timeoutMs / 5);
103
+ return now - due > lateBy && now < giveUpAt ? "rearm" : "abort";
104
+ }
105
+ /** Ask the machine for its destination default. Never rejects; `error` says why on failure. */
106
+ export async function discoverDestination(nodeUrl, timeoutMs) {
107
+ if (!isLoopbackUrl(nodeUrl)) {
108
+ return { found: null, error: `discovery skipped: ${nodeUrl} is not a loopback address` };
109
+ }
110
+ if (!(timeoutMs > 0) || typeof fetch !== "function")
111
+ return { found: null, error: "discovery off" };
112
+ const controller = new AbortController();
113
+ // The timeout is the machine's budget, not the app's: init() returns at
114
+ // once and the app usually goes on to load its framework synchronously
115
+ // (a cold require of LangChain or the Agents SDK can take seconds on a
116
+ // loaded box). A timer that fires late means the event loop was busy, and
117
+ // the machine's answer may already be waiting behind it, so the window is
118
+ // re-armed for as long as the timers keep firing late, up to a wall cap.
119
+ // Discovery gives up only after one window the loop spent idle with no
120
+ // answer, or at the cap. Spans finished meanwhile are held, not lost.
121
+ const giveUpAt = Date.now() + Math.max(DISCOVERY_WALL_CAP_MS, timeoutMs * 10);
122
+ const arm = () => {
123
+ const due = Date.now() + timeoutMs;
124
+ const t = setTimeout(() => {
125
+ if (discoveryTimerStep(Date.now(), due, giveUpAt, timeoutMs) === "rearm")
126
+ timer = arm();
127
+ else
128
+ controller.abort();
129
+ }, timeoutMs);
130
+ t.unref?.();
131
+ return t;
132
+ };
133
+ let timer = arm();
134
+ try {
135
+ const resp = await fetch(nodeUrl + DISCOVERY_PATH, { headers: { Accept: "application/json" }, signal: controller.signal, redirect: "manual" });
136
+ if (resp.status !== 200) {
137
+ void resp.body?.cancel().catch(() => undefined);
138
+ return { found: null, error: `discovery: HTTP ${resp.status}` };
139
+ }
140
+ let body;
141
+ try {
142
+ body = JSON.parse(await resp.text());
143
+ }
144
+ catch {
145
+ return { found: null, error: "discovery: the body is not JSON" };
146
+ }
147
+ const found = parseDiscovery(body);
148
+ return found ? { found, error: "" } : { found: null, error: "discovery: not an api_version 1 answer" };
149
+ }
150
+ catch (err) {
151
+ const cause = err.cause;
152
+ return { found: null, error: `discovery: ${controller.signal.aborted ? `timed out after ${timeoutMs}ms` : (cause?.code ?? String(err))}` };
153
+ }
154
+ finally {
155
+ clearTimeout(timer);
156
+ }
157
+ }
158
+ /** The credential file's gateway line (contract destination.md section 6). */
159
+ export const CREDENTIAL_GATEWAY_FIELD = "gateway_url";
160
+ /**
161
+ * Why `url` is not a usable gateway base for the key ("" when it is): https
162
+ * (or http to a loopback host), a host, no user info, query, fragment or path.
163
+ */
164
+ export function gatewayProblem(url) {
165
+ let u;
166
+ try {
167
+ u = new URL(url);
168
+ }
169
+ catch {
170
+ return `${JSON.stringify(url)} is not a URL`;
171
+ }
172
+ if ((u.protocol !== "http:" && u.protocol !== "https:") || !u.hostname)
173
+ return `${JSON.stringify(url)} is not an http(s) address with a host`;
174
+ if (u.username || u.password)
175
+ return `${JSON.stringify(url)} carries a user name or password`;
176
+ if (u.search || u.hash || (u.pathname !== "/" && u.pathname !== ""))
177
+ return `${JSON.stringify(url)} is not a base address`;
178
+ if (u.protocol !== "https:" && !isLoopbackUrl(url))
179
+ return `${JSON.stringify(url)} is plain http to a remote host`;
180
+ return "";
181
+ }
182
+ /**
183
+ * Read the machine's SDK credential file under the contract's rules (unix):
184
+ * not a symlink, no group or other permission bits, owned by this user. The
185
+ * first line is `<key_id>.<secret>`; each further line is `name=value`, where
186
+ * `gateway_url` names the only address the key is sent to (review E-04: the
187
+ * address comes from this owner-only file, never from the discovery answer).
188
+ * Unknown names are ignored; a gateway that is not https (or http to this
189
+ * machine) is ignored with an error. Returns the compound and the gateway,
190
+ * or `error` saying why it was refused. On Windows the file is never read:
191
+ * there is no owner check to make, so SUPERBASED_API_KEY is the way (as
192
+ * Python; review R-C33).
193
+ */
194
+ export function readCredentialFile(path) {
195
+ if (!path)
196
+ return { key: "", gateway: "", error: "" };
197
+ if (process.platform === "win32")
198
+ return { key: "", gateway: "", error: "credential files are not read on Windows; set SUPERBASED_API_KEY" };
199
+ const refuse = (error) => ({ key: "", gateway: "", error });
200
+ try {
201
+ const st = lstatSync(path);
202
+ if (st.isSymbolicLink())
203
+ return refuse(`credential file ${path} is a symlink; refused`);
204
+ if (!st.isFile())
205
+ return refuse(`credential file ${path} is not a regular file; refused`);
206
+ if ((st.mode & 0o077) !== 0)
207
+ return refuse(`credential file ${path} is readable by others (mode ${(st.mode & 0o777).toString(8)}); refused`);
208
+ const uid = typeof process.getuid === "function" ? process.getuid() : -1;
209
+ if (uid >= 0 && st.uid !== uid)
210
+ return refuse(`credential file ${path} is not owned by this user; refused`);
211
+ if (st.size > 4096)
212
+ return refuse(`credential file ${path} is too large; refused`);
213
+ // Open without following a symlink swapped in after the lstat, and read the
214
+ // descriptor that is checked.
215
+ const fd = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
216
+ let raw;
217
+ try {
218
+ const fst = fstatSync(fd);
219
+ if (!fst.isFile() || fst.ino !== st.ino || fst.dev !== st.dev)
220
+ return refuse(`credential file ${path} changed while it was read; refused`);
221
+ raw = readFileSync(fd, "utf8");
222
+ }
223
+ finally {
224
+ closeSync(fd);
225
+ }
226
+ // Printable ASCII only (and line ends).
227
+ if (/[^ -~\n\r\t]/.test(raw))
228
+ return refuse(`credential file ${path} has non-ASCII content; refused`);
229
+ const lines = (raw.endsWith("\n") ? raw.slice(0, -1) : raw).split("\n");
230
+ const bad = `credential file ${path} is not one <key_id>.<secret> line followed by name=value lines; refused`;
231
+ const key = lines[0] ?? "";
232
+ if (!/^[^\s.]+\.\S+$/.test(key))
233
+ return refuse(bad);
234
+ let gateway = "";
235
+ for (const line of lines.slice(1)) {
236
+ const eq = line.indexOf("=");
237
+ if (eq <= 0)
238
+ return refuse(bad);
239
+ if (line.slice(0, eq) === CREDENTIAL_GATEWAY_FIELD)
240
+ gateway = line.slice(eq + 1).trim();
241
+ }
242
+ if (gateway) {
243
+ const problem = gatewayProblem(gateway);
244
+ if (problem)
245
+ return { key, gateway: "", error: `credential file ${path} names a gateway address that is not usable (${problem}); it is ignored` };
246
+ }
247
+ return { key, gateway: trimSlash(gateway), error: "" };
248
+ }
249
+ catch (err) {
250
+ return refuse(`credential file ${path}: ${err.code ?? String(err)}`);
251
+ }
252
+ }
253
+ /** Settings with what the machine supplied filled in; explicit settings win. Also returns problems. */
254
+ export function withDiscovered(s, d, choice) {
255
+ const problems = [...d.warnings.map((w) => `machine: ${w}`), ...(d.refused ?? [])];
256
+ const out = { ...s };
257
+ if (d.localTracesUrl)
258
+ out.advertisedEndpoint = d.localTracesUrl;
259
+ // Where the key goes comes from the owner-only key file, never from the
260
+ // discovery answer (review E-04): discovery only names the file.
261
+ if ((!out.apiKey || !out.orgUrl) && (choice === "online" || choice === "both") && d.credentialPresent && d.credentialFile) {
262
+ const cred = readCredentialFile(d.credentialFile);
263
+ if (!out.apiKey && cred.key) {
264
+ out.apiKey = cred.key;
265
+ out.credentialSource = "file";
266
+ }
267
+ if (!out.orgUrl && cred.gateway)
268
+ out.orgUrl = cred.gateway;
269
+ if (cred.error)
270
+ problems.push(cred.error);
271
+ }
272
+ if (!d.localEnabled && (choice === "local" || choice === "both")) {
273
+ problems.push("this machine's Observer has [observability] off, so it refuses local spans; turn it on in the dashboard (Settings > Your apps)");
274
+ }
275
+ return { settings: out, problems };
276
+ }
277
+ /**
278
+ * The delegate the SDK runs while discovery is in flight: holds finished
279
+ * spans (up to DISCOVERY_QUEUE_MAX; beyond that they are counted as dropped)
280
+ * and hands them to the real delegate once it is known.
281
+ */
282
+ export class PendingProcessor {
283
+ queue = [];
284
+ target = null;
285
+ settled = false;
286
+ ready;
287
+ resolveReady;
288
+ constructor() {
289
+ this.ready = new Promise((r) => (this.resolveReady = r));
290
+ }
291
+ /** Counted destinations per span: one while held, then the target's (review E-31). */
292
+ get legs() {
293
+ return this.settled && this.target ? legsOf(this.target) : 1;
294
+ }
295
+ /** Install the real delegate (null: drop) and replay what was held. */
296
+ resolve(target) {
297
+ if (this.settled)
298
+ return;
299
+ this.settled = true;
300
+ this.target = target;
301
+ const held = this.queue;
302
+ this.queue = [];
303
+ // A held span was counted once; its replay goes to every destination.
304
+ if (target)
305
+ stats.handedSpans += held.length * (legsOf(target) - 1);
306
+ for (const s of held) {
307
+ if (!target) {
308
+ stats.droppedSpans += 1;
309
+ continue;
310
+ }
311
+ try {
312
+ target.onEnd(s);
313
+ }
314
+ catch {
315
+ // never break
316
+ }
317
+ }
318
+ this.resolveReady();
319
+ }
320
+ onStart(span, ctx) {
321
+ this.target?.onStart(span, ctx);
322
+ }
323
+ onEnd(span) {
324
+ if (this.settled) {
325
+ if (this.target)
326
+ this.target.onEnd(span);
327
+ else
328
+ stats.droppedSpans += 1;
329
+ return;
330
+ }
331
+ if (this.queue.length >= DISCOVERY_QUEUE_MAX) {
332
+ stats.droppedSpans += 1;
333
+ return;
334
+ }
335
+ this.queue.push(span);
336
+ }
337
+ async forceFlush() {
338
+ await this.ready;
339
+ await this.target?.forceFlush();
340
+ }
341
+ async shutdown() {
342
+ await this.ready;
343
+ await this.target?.shutdown();
344
+ }
345
+ }
346
+ //# sourceMappingURL=destination.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"destination.js","sourceRoot":"","sources":["../../src/destination.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EAAE,SAAS,EAAE,SAAS,IAAI,WAAW,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAK5G,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAyC,MAAM,aAAa,CAAC;AACpG,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAE5C,0DAA0D;AAC1D,MAAM,CAAC,MAAM,cAAc,GAAG,sBAAsB,CAAC;AACrD,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC;AACvC,iEAAiE;AACjE,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,CAAC;AAkBxC,SAAS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AE,CAAC;YACrB,IAAI,CAAC,MAAM,EAAE,CAAC;gBACZ,KAAK,CAAC,YAAY,IAAI,CAAC,CAAC;gBACxB,SAAS;YACX,CAAC;YACD,IAAI,CAAC;gBACH,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;YAAC,MAAM,CAAC;gBACP,cAAc;YAChB,CAAC;QACH,CAAC;QACD,IAAI,CAAC,YAAY,EAAE,CAAC;IACtB,CAAC;IAED,OAAO,CAAC,IAAU,EAAE,GAAY;QAC9B,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IAClC,CAAC;IAED,KAAK,CAAC,IAAkB;QACtB,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,IAAI,IAAI,CAAC,MAAM;gBAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;;gBACpC,KAAK,CAAC,YAAY,IAAI,CAAC,CAAC;YAC7B,OAAO;QACT,CAAC;QACD,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,mBAAmB,EAAE,CAAC;YAC7C,KAAK,CAAC,YAAY,IAAI,CAAC,CAAC;YACxB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IAED,KAAK,CAAC,UAAU;QACd,MAAM,IAAI,CAAC,KAAK,CAAC;QACjB,MAAM,IAAI,CAAC,MAAM,EAAE,UAAU,EAAE,CAAC;IAClC,CAAC;IAED,KAAK,CAAC,QAAQ;QACZ,MAAM,IAAI,CAAC,KAAK,CAAC;QACjB,MAAM,IAAI,CAAC,MAAM,EAAE,QAAQ,EAAE,CAAC;IAChC,CAAC;CACF","sourcesContent":["/**\n * Data destination (D18; contract `contracts/destination.md`, lane B6).\n *\n * - `local`: this machine's Observer only.\n * - `online`: the org or SaaS gateway only.\n * - `both`: the SDK exports to each itself, through its own exporter, so one\n * failing destination never blocks the other and `both` never depends on\n * the machine's push tiers.\n *\n * The choice, first set wins: the `destination` option, then\n * `SUPERBASED_DESTINATION`, then the default this machine advertises at\n * `GET <nodeUrl>/api/sdk/destination` (loopback only, 500 ms, one attempt),\n * then `online` when no machine answered and the app was given a gateway and\n * a credential (`inferred`, a production app), then `local`. Discovery also\n * runs for an explicit `online` / `both` that still lacks a gateway URL or a\n * credential, which the machine supplies (review finding R-B09), and for an\n * explicit `local` / `both` with no endpoint the app named for the local\n * destination: the machine advertises its own receiver (live finding L-01).\n * An explicit `endpoint` only sets where the local destination sends.\n *\n * The gateway URL: `orgUrl`, `SUPERBASED_ORG_URL`, then the `gateway_url`\n * line of the machine's credential file. The credential: `apiKey`,\n * `SUPERBASED_API_KEY`, then that file's key line. The file is read only\n * after the owner, mode and symlink checks of contract section 6. The\n * discovery answer never decides where the key goes (review E-04): it only\n * names the file, and its local URLs are used only when they are loopback.\n * The machine never sends the credential itself.\n *\n * While discovery runs, finished spans wait in a bounded queue and then go\n * to the chosen destination; none are sent to a guess.\n */\n\nimport { closeSync, constants as fsConstants, fstatSync, lstatSync, openSync, readFileSync } from \"node:fs\";\n\nimport type { Context } from \"@opentelemetry/api\";\nimport type { ReadableSpan, Span, SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\n\nimport { DESTINATION_CHOICES, trimSlash, type DestinationChoice, type Settings } from \"./config.js\";\nimport { legsOf, stats } from \"./export.js\";\n\n/** The machine's discovery route (contract section 4). */\nexport const DISCOVERY_PATH = \"/api/sdk/destination\";\nexport const DISCOVERY_API_VERSION = 1;\n/** Most spans held while the destination is being discovered. */\nexport const DISCOVERY_QUEUE_MAX = 2048;\n\n/** What the machine advertises (api_version 1), reduced to what the SDK uses. */\nexport interface Discovered {\n destination: DestinationChoice;\n source: string;\n signedIn: boolean;\n localEnabled: boolean;\n localTracesUrl: string;\n admissionUrl: string;\n gatewayUrl: string;\n credentialPresent: boolean;\n credentialFile: string;\n warnings: string[];\n /** Local URLs the answer named that were not loopback, and so were ignored (review E-04). */\n refused: string[];\n}\n\nfunction obj(v: unknown): Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n}\n\n/** Parse the discovery body; null when it is not a usable api_version 1 answer. */\nexport function parseDiscovery(body: unknown): Discovered | null {\n const d = obj(body);\n if (d.api_version !== DISCOVERY_API_VERSION) return null;\n const rawDest = typeof d.destination === \"string\" ? d.destination.trim().toLowerCase() : \"\";\n const destKnown = (DESTINATION_CHOICES as readonly string[]).includes(rawDest);\n const dest = destKnown ? rawDest : \"local\";\n const local = obj(d.local);\n const online = obj(d.online);\n const s = (o: Record<string, unknown>, k: string) => (typeof o[k] === \"string\" ? (o[k] as string).trim() : \"\");\n // The machine's receiver and admission check are on this machine: a remote\n // address there is not the machine speaking (review E-04).\n const refused: string[] = [];\n const unknownDest = destKnown ? [] : [`the discovery answer names an unknown destination ${JSON.stringify(rawDest)}; using local`];\n const loopback = (k: string): string => {\n const v = s(local, k);\n if (v && !isLoopbackUrl(v)) {\n refused.push(`the machine's discovery answer names a non-loopback ${k} (${v}); ignored`);\n return \"\";\n }\n return v;\n };\n return {\n destination: dest as DestinationChoice,\n source: s(d, \"source\"),\n signedIn: d.signed_in === true,\n localEnabled: local.enabled !== false,\n localTracesUrl: loopback(\"otlp_traces_url\"),\n admissionUrl: loopback(\"admission_url\"),\n gatewayUrl: trimSlash(s(online, \"gateway_url\")),\n credentialPresent: online.credential_present === true,\n credentialFile: s(online, \"credential_file\"),\n warnings: [...(Array.isArray(d.warnings) ? d.warnings.filter((w): w is string => typeof w === \"string\") : []), ...unknownDest],\n refused,\n };\n}\n\n/** Whether a URL's host is loopback (the only hosts discovery is sent to). */\nexport function isLoopbackUrl(url: string): boolean {\n try {\n const h = new URL(url).hostname.replace(/^\\[|\\]$/g, \"\").toLowerCase();\n return h === \"localhost\" || h === \"::1\" || /^127\\.\\d+\\.\\d+\\.\\d+$/.test(h);\n } catch {\n return false;\n }\n}\n\n/**\n * The longest discovery waits on a busy event loop (see discoverDestination),\n * or ten windows when the window is longer.\n */\nexport const DISCOVERY_WALL_CAP_MS = 5000;\n\n/**\n * What a discovery window's timer does when it fires at `now` (it was due at\n * `due`): \"rearm\" when it fired late (the event loop was busy, so the\n * machine's answer may be waiting behind it) and the wall cap `giveUpAt` is\n * not reached; otherwise \"abort\".\n */\nexport function discoveryTimerStep(now: number, due: number, giveUpAt: number, timeoutMs: number): \"rearm\" | \"abort\" {\n const lateBy = Math.max(50, timeoutMs / 5);\n return now - due > lateBy && now < giveUpAt ? \"rearm\" : \"abort\";\n}\n\n/** Ask the machine for its destination default. Never rejects; `error` says why on failure. */\nexport async function discoverDestination(nodeUrl: string, timeoutMs: number): Promise<{ found: Discovered | null; error: string }> {\n if (!isLoopbackUrl(nodeUrl)) {\n return { found: null, error: `discovery skipped: ${nodeUrl} is not a loopback address` };\n }\n if (!(timeoutMs > 0) || typeof fetch !== \"function\") return { found: null, error: \"discovery off\" };\n const controller = new AbortController();\n // The timeout is the machine's budget, not the app's: init() returns at\n // once and the app usually goes on to load its framework synchronously\n // (a cold require of LangChain or the Agents SDK can take seconds on a\n // loaded box). A timer that fires late means the event loop was busy, and\n // the machine's answer may already be waiting behind it, so the window is\n // re-armed for as long as the timers keep firing late, up to a wall cap.\n // Discovery gives up only after one window the loop spent idle with no\n // answer, or at the cap. Spans finished meanwhile are held, not lost.\n const giveUpAt = Date.now() + Math.max(DISCOVERY_WALL_CAP_MS, timeoutMs * 10);\n const arm = (): ReturnType<typeof setTimeout> => {\n const due = Date.now() + timeoutMs;\n const t = setTimeout(() => {\n if (discoveryTimerStep(Date.now(), due, giveUpAt, timeoutMs) === \"rearm\") timer = arm();\n else controller.abort();\n }, timeoutMs);\n t.unref?.();\n return t;\n };\n let timer = arm();\n try {\n const resp = await fetch(nodeUrl + DISCOVERY_PATH, { headers: { Accept: \"application/json\" }, signal: controller.signal, redirect: \"manual\" });\n if (resp.status !== 200) {\n void resp.body?.cancel().catch(() => undefined);\n return { found: null, error: `discovery: HTTP ${resp.status}` };\n }\n let body: unknown;\n try {\n body = JSON.parse(await resp.text());\n } catch {\n return { found: null, error: \"discovery: the body is not JSON\" };\n }\n const found = parseDiscovery(body);\n return found ? { found, error: \"\" } : { found: null, error: \"discovery: not an api_version 1 answer\" };\n } catch (err) {\n const cause = (err as { cause?: { code?: string } }).cause;\n return { found: null, error: `discovery: ${controller.signal.aborted ? `timed out after ${timeoutMs}ms` : (cause?.code ?? String(err))}` };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The credential file's gateway line (contract destination.md section 6). */\nexport const CREDENTIAL_GATEWAY_FIELD = \"gateway_url\";\n\n/**\n * Why `url` is not a usable gateway base for the key (\"\" when it is): https\n * (or http to a loopback host), a host, no user info, query, fragment or path.\n */\nexport function gatewayProblem(url: string): string {\n let u: URL;\n try {\n u = new URL(url);\n } catch {\n return `${JSON.stringify(url)} is not a URL`;\n }\n if ((u.protocol !== \"http:\" && u.protocol !== \"https:\") || !u.hostname) return `${JSON.stringify(url)} is not an http(s) address with a host`;\n if (u.username || u.password) return `${JSON.stringify(url)} carries a user name or password`;\n if (u.search || u.hash || (u.pathname !== \"/\" && u.pathname !== \"\")) return `${JSON.stringify(url)} is not a base address`;\n if (u.protocol !== \"https:\" && !isLoopbackUrl(url)) return `${JSON.stringify(url)} is plain http to a remote host`;\n return \"\";\n}\n\n/**\n * Read the machine's SDK credential file under the contract's rules (unix):\n * not a symlink, no group or other permission bits, owned by this user. The\n * first line is `<key_id>.<secret>`; each further line is `name=value`, where\n * `gateway_url` names the only address the key is sent to (review E-04: the\n * address comes from this owner-only file, never from the discovery answer).\n * Unknown names are ignored; a gateway that is not https (or http to this\n * machine) is ignored with an error. Returns the compound and the gateway,\n * or `error` saying why it was refused. On Windows the file is never read:\n * there is no owner check to make, so SUPERBASED_API_KEY is the way (as\n * Python; review R-C33).\n */\nexport function readCredentialFile(path: string): { key: string; gateway: string; error: string } {\n if (!path) return { key: \"\", gateway: \"\", error: \"\" };\n if (process.platform === \"win32\") return { key: \"\", gateway: \"\", error: \"credential files are not read on Windows; set SUPERBASED_API_KEY\" };\n const refuse = (error: string) => ({ key: \"\", gateway: \"\", error });\n try {\n const st = lstatSync(path);\n if (st.isSymbolicLink()) return refuse(`credential file ${path} is a symlink; refused`);\n if (!st.isFile()) return refuse(`credential file ${path} is not a regular file; refused`);\n if ((st.mode & 0o077) !== 0) return refuse(`credential file ${path} is readable by others (mode ${(st.mode & 0o777).toString(8)}); refused`);\n const uid = typeof process.getuid === \"function\" ? process.getuid() : -1;\n if (uid >= 0 && st.uid !== uid) return refuse(`credential file ${path} is not owned by this user; refused`);\n if (st.size > 4096) return refuse(`credential file ${path} is too large; refused`);\n // Open without following a symlink swapped in after the lstat, and read the\n // descriptor that is checked.\n const fd = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));\n let raw: string;\n try {\n const fst = fstatSync(fd);\n if (!fst.isFile() || fst.ino !== st.ino || fst.dev !== st.dev) return refuse(`credential file ${path} changed while it was read; refused`);\n raw = readFileSync(fd, \"utf8\");\n } finally {\n closeSync(fd);\n }\n // Printable ASCII only (and line ends).\n if (/[^ -~\\n\\r\\t]/.test(raw)) return refuse(`credential file ${path} has non-ASCII content; refused`);\n const lines = (raw.endsWith(\"\\n\") ? raw.slice(0, -1) : raw).split(\"\\n\");\n const bad = `credential file ${path} is not one <key_id>.<secret> line followed by name=value lines; refused`;\n const key = lines[0] ?? \"\";\n if (!/^[^\\s.]+\\.\\S+$/.test(key)) return refuse(bad);\n let gateway = \"\";\n for (const line of lines.slice(1)) {\n const eq = line.indexOf(\"=\");\n if (eq <= 0) return refuse(bad);\n if (line.slice(0, eq) === CREDENTIAL_GATEWAY_FIELD) gateway = line.slice(eq + 1).trim();\n }\n if (gateway) {\n const problem = gatewayProblem(gateway);\n if (problem) return { key, gateway: \"\", error: `credential file ${path} names a gateway address that is not usable (${problem}); it is ignored` };\n }\n return { key, gateway: trimSlash(gateway), error: \"\" };\n } catch (err) {\n return refuse(`credential file ${path}: ${(err as { code?: string }).code ?? String(err)}`);\n }\n}\n\n/** Settings with what the machine supplied filled in; explicit settings win. Also returns problems. */\nexport function withDiscovered(s: Settings, d: Discovered, choice: DestinationChoice): { settings: Settings; problems: string[] } {\n const problems = [...d.warnings.map((w) => `machine: ${w}`), ...(d.refused ?? [])];\n const out: Settings = { ...s };\n if (d.localTracesUrl) out.advertisedEndpoint = d.localTracesUrl;\n // Where the key goes comes from the owner-only key file, never from the\n // discovery answer (review E-04): discovery only names the file.\n if ((!out.apiKey || !out.orgUrl) && (choice === \"online\" || choice === \"both\") && d.credentialPresent && d.credentialFile) {\n const cred = readCredentialFile(d.credentialFile);\n if (!out.apiKey && cred.key) {\n out.apiKey = cred.key;\n out.credentialSource = \"file\";\n }\n if (!out.orgUrl && cred.gateway) out.orgUrl = cred.gateway;\n if (cred.error) problems.push(cred.error);\n }\n if (!d.localEnabled && (choice === \"local\" || choice === \"both\")) {\n problems.push(\"this machine's Observer has [observability] off, so it refuses local spans; turn it on in the dashboard (Settings > Your apps)\");\n }\n return { settings: out, problems };\n}\n\n/**\n * The delegate the SDK runs while discovery is in flight: holds finished\n * spans (up to DISCOVERY_QUEUE_MAX; beyond that they are counted as dropped)\n * and hands them to the real delegate once it is known.\n */\nexport class PendingProcessor implements SpanProcessor {\n private queue: ReadableSpan[] = [];\n private target: SpanProcessor | null = null;\n private settled = false;\n readonly ready: Promise<void>;\n private resolveReady!: () => void;\n\n constructor() {\n this.ready = new Promise((r) => (this.resolveReady = r));\n }\n\n /** Counted destinations per span: one while held, then the target's (review E-31). */\n get legs(): number {\n return this.settled && this.target ? legsOf(this.target) : 1;\n }\n\n /** Install the real delegate (null: drop) and replay what was held. */\n resolve(target: SpanProcessor | null): void {\n if (this.settled) return;\n this.settled = true;\n this.target = target;\n const held = this.queue;\n this.queue = [];\n // A held span was counted once; its replay goes to every destination.\n if (target) stats.handedSpans += held.length * (legsOf(target) - 1);\n for (const s of held) {\n if (!target) {\n stats.droppedSpans += 1;\n continue;\n }\n try {\n target.onEnd(s);\n } catch {\n // never break\n }\n }\n this.resolveReady();\n }\n\n onStart(span: Span, ctx: Context): void {\n this.target?.onStart(span, ctx);\n }\n\n onEnd(span: ReadableSpan): void {\n if (this.settled) {\n if (this.target) this.target.onEnd(span);\n else stats.droppedSpans += 1;\n return;\n }\n if (this.queue.length >= DISCOVERY_QUEUE_MAX) {\n stats.droppedSpans += 1;\n return;\n }\n this.queue.push(span);\n }\n\n async forceFlush(): Promise<void> {\n await this.ready;\n await this.target?.forceFlush();\n }\n\n async shutdown(): Promise<void> {\n await this.ready;\n await this.target?.shutdown();\n }\n}\n"]}
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Datasets and experiments (W3-2; contract `contracts/experiments.md`, lane
3
+ * B7; the same flow as the Python SDK's `run_experiment`).
4
+ *
5
+ * `runExperiment({ dataset, task, evaluators })`:
6
+ * 1. finds the dataset by name or id on each destination side (online
7
+ * first, then this machine), or uploads inline items as a literal
8
+ * snapshot of `datasetName` (created on the machine; on the org it must
9
+ * exist). Inline items without `datasetName` run in-process only and
10
+ * nothing is posted;
11
+ * 2. creates a run on each side (`POST /v1/sdk/experiments`, machine
12
+ * `/api/obs/eval/experiments`), which freezes a snapshot unless
13
+ * `snapshotVersion` pins one, and reads that snapshot's items. Under `both`
14
+ * the task runs once: the other side's items are matched by client id,
15
+ * then by input;
16
+ * 3. runs `task` on each item in its own trace (a CHAIN root span stamped
17
+ * `sbo.experiment.run_id` / `sbo.experiment.item_id`), then the
18
+ * evaluators in-process;
19
+ * 4. posts each item's result (output under captureContent, scores, error)
20
+ * to each run as it finishes; the server also stores each score on the
21
+ * item's trace;
22
+ * 5. finishes the runs and reads their totals.
23
+ *
24
+ * An experiment is an explicit batch job, so unlike the tracing calls a
25
+ * dataset that cannot be found or a run that cannot be created rejects with
26
+ * {@link ExperimentError}, and `failUnder` rejects with
27
+ * {@link ExperimentGateFailed} (and sets `process.exitCode = 1`) when the
28
+ * pass rate is below it. A task or evaluator that throws is recorded on its
29
+ * item; the run goes on. CI credentials need the `sdk:eval` scope.
30
+ */
31
+ import { type ControlOptions, type TargetName } from "./control.js";
32
+ export interface DatasetItem {
33
+ /** The server's item id (`it_...`), or yours for an inline item. */
34
+ id?: string;
35
+ input: unknown;
36
+ expectedOutput?: unknown;
37
+ metadata?: Record<string, unknown>;
38
+ }
39
+ export interface Dataset {
40
+ id: string;
41
+ name: string;
42
+ /** The snapshot version the items come from (0 for inline items). */
43
+ version: number;
44
+ items: DatasetItem[];
45
+ /** Items frozen without content (their trace's content was not stored); skipped by an experiment. */
46
+ skippedNoContent: number;
47
+ target?: TargetName;
48
+ }
49
+ export interface EvaluatorArgs {
50
+ input: unknown;
51
+ output: unknown;
52
+ expectedOutput: unknown;
53
+ /** The same as expectedOutput (the Python SDK's name). */
54
+ expected: unknown;
55
+ metadata: Record<string, unknown>;
56
+ item: DatasetItem;
57
+ }
58
+ /** One evaluation: a bare value (named after the evaluator) or a named result. */
59
+ export type Evaluation = number | boolean | string | {
60
+ name?: string;
61
+ value: number | boolean | string;
62
+ comment?: string;
63
+ };
64
+ type EvalOut = Evaluation | Evaluation[] | null | undefined;
65
+ /** An evaluator: a function (its name names the score) or a named, versioned function. */
66
+ export type Evaluator = ((args: EvaluatorArgs) => EvalOut | Promise<EvalOut>) | {
67
+ name: string;
68
+ version?: string;
69
+ evaluate: (args: EvaluatorArgs) => EvalOut | Promise<EvalOut>;
70
+ };
71
+ export interface ExperimentOptions extends ControlOptions {
72
+ /** A dataset name or id (fetched), a fetched Dataset, or the items themselves. */
73
+ dataset: string | Dataset | Array<DatasetItem & {
74
+ expected?: unknown;
75
+ }>;
76
+ /** Runs on one item's input; may be async. */
77
+ task: (input: unknown, item: DatasetItem) => unknown;
78
+ evaluators?: Evaluator[];
79
+ /** The experiment's name (default: the task's name, else `experiment`). */
80
+ name?: string;
81
+ /** Stored with the run. */
82
+ metadata?: Record<string, unknown>;
83
+ /** Items run at once (default 4). */
84
+ maxConcurrency?: number;
85
+ /** A frozen snapshot version to run over (default: freeze a new one). The contract name (Python `snapshot_version`). */
86
+ snapshotVersion?: number;
87
+ /** @deprecated The pre-contract name of `snapshotVersion`; still read when `snapshotVersion` is not set (review E-49). */
88
+ datasetVersion?: number;
89
+ /** For inline items: the dataset they are uploaded to (created on the machine; on the org it must exist). */
90
+ datasetName?: string;
91
+ /** CI gate: below this pass rate runExperiment rejects with ExperimentGateFailed and sets process.exitCode = 1. */
92
+ failUnder?: number;
93
+ /**
94
+ * With `failUnder` set, the gate is strict by default (review E-12): a run
95
+ * that scored nothing, a skipped destination or a result a destination did
96
+ * not accept also fails it, because a CI gate that passes on an outage is
97
+ * worse than none. `false` gates on the pass rate alone.
98
+ */
99
+ strict?: boolean;
100
+ }
101
+ export interface ItemResult {
102
+ item: DatasetItem;
103
+ traceId: string;
104
+ output: unknown;
105
+ /** The task's error, if it threw. */
106
+ error: string;
107
+ scores: Array<{
108
+ name: string;
109
+ value: number | boolean | string;
110
+ comment?: string;
111
+ error?: string;
112
+ }>;
113
+ /** Why a result was not accepted ("" when it was, or nothing was posted). */
114
+ postError: string;
115
+ }
116
+ export interface ExperimentResult {
117
+ /** The first side's run id ("" when nothing was recorded). */
118
+ runId: string;
119
+ /** Run id per side. */
120
+ runs: Partial<Record<TargetName, string>>;
121
+ name: string;
122
+ datasetId: string;
123
+ snapshotVersion: number;
124
+ items: ItemResult[];
125
+ /** Mean of each numeric / boolean score, with its count. */
126
+ summary: Record<string, {
127
+ mean: number;
128
+ count: number;
129
+ }>;
130
+ /**
131
+ * The first side's pass rate, else computed locally over the scored items.
132
+ * NaN when nothing was scored (`scored` 0): no rate, not 0.
133
+ */
134
+ passRate: number;
135
+ /**
136
+ * How many items were scored: the side's `total`, else the local count of
137
+ * items with a score or a task error. An item with neither (no evaluator
138
+ * ran, or every evaluator threw) is neither passed nor failed. `failUnder`
139
+ * is not applied when this is 0; `errors` says "no scores" instead.
140
+ */
141
+ scored: number;
142
+ /** Whether the runs were created and finished. */
143
+ recorded: boolean;
144
+ skippedNoContent: number;
145
+ /** Problems that are not one item's (a result a side refused, an unmatched item). */
146
+ errors: string[];
147
+ /** Destinations skipped for want of a scope (403 insufficient_scope). */
148
+ skippedSides: TargetName[];
149
+ /** Results a destination did not accept (a failed post or a rejected row; one per result per side). */
150
+ failedPosts: number;
151
+ /** The totals each side returned (`GET .../experiments/{id}`). */
152
+ server: Partial<Record<TargetName, Record<string, unknown>>>;
153
+ }
154
+ /** The experiment could not be set up (dataset, run creation). */
155
+ export declare class ExperimentError extends Error {
156
+ constructor(message: string);
157
+ }
158
+ /**
159
+ * The `failUnder` gate failed (a CI gate): the pass rate is below it, or,
160
+ * strict (the default), `reasons` says why the gate could not pass at all.
161
+ */
162
+ export declare class ExperimentGateFailed extends Error {
163
+ readonly result: ExperimentResult;
164
+ readonly failUnder: number;
165
+ readonly reasons: string[];
166
+ constructor(result: ExperimentResult, failUnder: number, reasons?: string[]);
167
+ }
168
+ /**
169
+ * The `failUnder` gate (contract experiments.md 4.2, review E-12): `reasons`
170
+ * are why a strict gate fails before the rate is compared (nothing scored, a
171
+ * skipped destination, results not accepted); `failed` applies them when
172
+ * `strict`, then the rate. A run that scored nothing is not failed when not
173
+ * strict. Python: gate_problems / gate_fails.
174
+ */
175
+ export declare function experimentGate(r: Pick<ExperimentResult, "scored" | "passRate" | "skippedSides" | "failedPosts">, failUnder: number | undefined, strict?: boolean): {
176
+ failed: boolean;
177
+ reasons: string[];
178
+ };
179
+ /**
180
+ * The default id of a literal item: derived from its content (review E-75),
181
+ * so a re-run with changed inputs makes new items on the machine instead of
182
+ * matching the previous run's `item-00001`. Python gives the same id
183
+ * (sdk-behaviour-cases.json `literal_item_ids`).
184
+ */
185
+ export declare function literalItemId(input: unknown, expected?: unknown, metadata?: unknown): string;
186
+ /**
187
+ * Inline items as the literal upload rows `{id, input, expected, metadata?}`.
188
+ * A missing id is {@link literalItemId} of the content; the same content
189
+ * twice gets `-2`, `-3`, ... (E-75; Python's `_literal`).
190
+ */
191
+ export declare function literalRows(ds: ReadonlyArray<DatasetItem & {
192
+ expected?: unknown;
193
+ }>): Array<Record<string, unknown>>;
194
+ /**
195
+ * Fetch a dataset's items: by name or id, from a snapshot `version` (default
196
+ * the latest), from the first destination that has it (the org first under
197
+ * `both`). Rejects with {@link ExperimentError} when no destination has it
198
+ * (or none is usable), as Python's `get_dataset` raises (review R-C34);
199
+ * `errors` lists what an earlier destination answered when a later one had
200
+ * it.
201
+ */
202
+ export declare function getDataset(nameOrId: string, opts?: ControlOptions & {
203
+ version?: number;
204
+ }): Promise<Dataset & {
205
+ errors: string[];
206
+ }>;
207
+ /**
208
+ * Run `task` over a dataset and score each output.
209
+ *
210
+ * ```ts
211
+ * const res = await runExperiment({
212
+ * name: "prompt-v7",
213
+ * dataset: "golden-qa",
214
+ * task: async (input) => answer(input),
215
+ * evaluators: [function exact_match({ output, expectedOutput }) { return output === expectedOutput; }],
216
+ * failUnder: 0.9,
217
+ * });
218
+ * ```
219
+ */
220
+ export declare function runExperiment(opts: ExperimentOptions): Promise<ExperimentResult>;
221
+ /** B7's pass rule (contract 4.2): boolean true, a number >= 0.5, a label not fail/false/no/bad. */
222
+ export declare function scorePasses(v: number | boolean | string): boolean;
223
+ /**
224
+ * A run's pass rate and scored count (contract experiments.md 4.2), as
225
+ * Python's ExperimentResult computes them: the first side whose totals say
226
+ * something was scored, else the local tally over scored items (an item
227
+ * passes with no task error and every returned score passing). A side's
228
+ * `pass_rate` with `total` 0 (an older server's 0 for "nothing scored") is
229
+ * not a rate. NaN when nothing was scored. `gateFailed`: the rate is below
230
+ * `failUnder`; never for a run that scored nothing.
231
+ */
232
+ export declare function experimentTotals(items: ItemResult[], sides?: Array<Record<string, unknown>>, failUnder?: number): {
233
+ scored: number;
234
+ passRate: number;
235
+ gateFailed: boolean;
236
+ };
237
+ export {};