@cultured_computer/sight 0.6.0 → 0.7.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
@@ -28,22 +28,22 @@ around it are still moving.
28
28
  npm install @cultured_computer/sight
29
29
  ```
30
30
 
31
- Node 18 or later. TypeScript types ship with the package.
31
+ Node 20.6 or later. TypeScript types ship with the package.
32
32
 
33
33
  ## Quickstart
34
34
 
35
35
  ```ts
36
- import { Sight } from '@cultured_computer/sight'
36
+ import { Sight } from "@cultured_computer/sight";
37
37
 
38
38
  Sight.init({
39
39
  apiKey: process.env.SIGHT_API_KEY!,
40
- deployment: 'my-assistant',
41
- })
40
+ deployment: "my-assistant",
41
+ });
42
42
 
43
43
  Sight.startSession({
44
44
  externalId: conversationId,
45
45
  externalUserId: userId,
46
- })
46
+ });
47
47
  ```
48
48
 
49
49
  Notes:
@@ -59,6 +59,53 @@ Notes:
59
59
  stable, pseudonymous user id you supply. Return metrics key on the user id;
60
60
  sessions without it still capture, but return behaviour is not computable.
61
61
 
62
+ ## Headless project setup
63
+
64
+ Provider setup requires an explicitly issued **management** provisioning token
65
+ (`--access manage`), not an ordinary ingest, Studio, or combined token. It grants
66
+ only `providers:write`, allowing provider-key replacement and budget changes.
67
+ With that administrative token, connect your own OpenRouter key without a browser:
68
+
69
+ ```bash
70
+ export SIGHT_PROVISION_TOKEN='<one-time management token from Sight>'
71
+ export OPENROUTER_API_KEY='<your OpenRouter API key>'
72
+
73
+ npx @cultured_computer/sight account create --openrouter --budget 25
74
+ ```
75
+
76
+ The provisioning token and OpenRouter key are read only from the environment,
77
+ not command-line arguments. The Sight key is returned once and saved to
78
+ `~/.config/sight/machine.json` with mode `0600`; it is never printed. Sight
79
+ validates the OpenRouter key, seals it before database storage, and records the
80
+ explicit local monthly budget. Check the safe, redacted state later with:
81
+
82
+ ```bash
83
+ npx @cultured_computer/sight openrouter status
84
+ ```
85
+
86
+ If OpenRouter setup fails after account creation, the Sight credential remains
87
+ saved. Fix the key or budget and retry only that step:
88
+
89
+ ```bash
90
+ export OPENROUTER_API_KEY='<your OpenRouter API key>'
91
+ npx @cultured_computer/sight openrouter connect --budget 25
92
+ ```
93
+
94
+ For an existing project, ask its owner for a separate **Provider administration
95
+ only** key, or have the operator mint one with `scripts/mint-key.mjs --access manage`.
96
+ Set it as `SIGHT_API_KEY` for `openrouter connect`. Use a separate `studio` or
97
+ `both` key for execution; management keys do not authorize runs or ingest.
98
+ Existing tokens and keys are never upgraded. An ordinary provisioning token
99
+ can still be redeemed with `account create` without `--openrouter`.
100
+ Redemption is one-time for the project, so a second provisioning token cannot
101
+ add an execution key after admin provisioning. The owner must mint the separate
102
+ ingest/Studio key in API Keys after claiming the project, or the operator must
103
+ mint it with `scripts/mint-key.mjs --access ingest`, `studio`, or `both`.
104
+
105
+ Use `SIGHT_API_KEY` from your secret manager in the application process. The
106
+ local `machine.json` is a CLI credential store, not a project `.env` file and
107
+ is never copied into your repository automatically.
108
+
62
109
  ## Pull your own data out: the CLI, from your terminal
63
110
 
64
111
  The `sight` CLI also carries out data from projects you **own**, with no
@@ -107,13 +154,23 @@ the walkthrough lives at
107
154
  the one to use in every new integration:
108
155
 
109
156
  ```ts
110
- import OpenAI from 'openai';
111
- import { Sight, wrapOpenAI } from '@cultured_computer/sight';
157
+ import OpenAI from "openai";
158
+ import { Sight, wrapOpenAI } from "@cultured_computer/sight";
112
159
 
113
160
  const openai = wrapOpenAI(new OpenAI());
114
- // Every chat.completions.create and responses.create call on this
115
- // client is now captured, streaming included. Wrap before or after
116
- // Sight.init(); order does not matter.
161
+ // Wrap before or after Sight.init(); order does not matter.
162
+
163
+ // Calls are captured within a session scope: wrapOpenAI reads the session
164
+ // from withSession's async context. Every chat.completions.create and
165
+ // responses.create made inside the scope is captured, streaming included.
166
+ await Sight.withSession(conversationId, async () => {
167
+ const res = await openai.chat.completions.create({
168
+ model: "gpt-4.1",
169
+ messages: [{ role: "user", content: userMessage }],
170
+ });
171
+ });
172
+ // A call made outside any session scope is skipped — with a one-line
173
+ // warning naming withSession, never a silent drop.
117
174
  ```
118
175
 
119
176
  Module-level autocapture (no wrap call) also exists but has hard limits:
@@ -122,6 +179,7 @@ the walkthrough lives at
122
179
  v5+). When it cannot attach, the SDK now prints a warning naming
123
180
  `wrapOpenAI` instead of failing silently. If you run ESM or openai v5+,
124
181
  wrap the client.
182
+
125
183
  - Module-level autocapture is on from `init` for calls made through the
126
184
  Anthropic SDK, Vercel AI SDK, LangChain, and LangGraph in the process,
127
185
  with the same CommonJS and load-order caveats. Each adapter no-ops if
@@ -144,15 +202,15 @@ even hours later, from a webhook or CRM callback.
144
202
  // A user reporting a persona break.
145
203
  await Sight.flagPersonaBreak({
146
204
  sessionExternalId: sessionId,
147
- note: 'sounded robotic',
148
- })
205
+ note: "sounded robotic",
206
+ });
149
207
 
150
208
  // Your own downstream outcome: a resolved ticket, a rating, a conversion.
151
209
  await Sight.emitOutcomeEvent({
152
210
  sessionExternalId: sessionId,
153
- kind: 'ticket_resolved',
154
- detail: { ticketId: 'ZD-88213' },
155
- })
211
+ kind: "ticket_resolved",
212
+ detail: { ticketId: "ZD-88213" },
213
+ });
156
214
  ```
157
215
 
158
216
  ## Capture environment events
@@ -163,10 +221,10 @@ against the conversation:
163
221
 
164
222
  ```ts
165
223
  await Sight.captureEnvironmentEvents(events, {
166
- clock_source: 'my-event-clock',
224
+ clock_source: "my-event-clock",
167
225
  skew_bound_ms: 25,
168
- rule_version: 'v1',
169
- })
226
+ rule_version: "v1",
227
+ });
170
228
  ```
171
229
 
172
230
  The envelope is generalized: `source_type` and `event` are free strings whose
@@ -184,26 +242,60 @@ steps, per-call model usage inside a single turn) can ship it as spans:
184
242
  await Sight.captureSpans(
185
243
  [
186
244
  {
187
- deploymentSlug: 'my-agent',
245
+ contractVersion: 2,
246
+ deploymentSlug: "my-agent",
188
247
  sessionExternalId: sessionId,
189
248
  turnIndex: 3,
190
- spanType: 'tool_call',
191
- name: 'lookup_order',
192
- startedAt: '2026-07-22T00:00:01.200Z',
249
+ spanType: "tool_call",
250
+ spanId: "lookup-3",
251
+ parentSpanId: null,
252
+ name: "lookup_order",
253
+ status: "ok",
254
+ startedAt: "2026-07-22T00:00:01.200Z",
255
+ endedAt: "2026-07-22T00:00:01.380Z",
193
256
  durationMs: 180,
194
- attributes: { toolName: 'lookup_order', argKeys: ['orderId'] },
257
+ model: null,
258
+ provider: null,
259
+ tokensInput: null,
260
+ tokensOutput: null,
261
+ costUsd: null,
262
+ error: null,
263
+ input: { state: "captured", value: { orderId: "ord_123" } },
264
+ output: { state: "captured", value: { status: "shipped" } },
265
+ intervals: [
266
+ {
267
+ kind: "active",
268
+ startedAt: "2026-07-22T00:00:01.200Z",
269
+ endedAt: "2026-07-22T00:00:01.280Z",
270
+ },
271
+ {
272
+ kind: "waiting",
273
+ startedAt: "2026-07-22T00:00:01.280Z",
274
+ endedAt: "2026-07-22T00:00:01.380Z",
275
+ },
276
+ ],
277
+ attributes: { toolName: "lookup_order", argKeys: ["orderId"] },
195
278
  },
196
279
  ],
197
- { clock_source: 'my-agent-clock', skew_bound_ms: 25, rule_version: 'v1' },
198
- )
280
+ { clock_source: "my-agent-clock", skew_bound_ms: 25, rule_version: "v1" },
281
+ );
199
282
  ```
200
283
 
201
284
  A span lands on the turn you name, or on the session's latest turn at/under
202
285
  its `startedAt` when `turnIndex` is omitted. Parent structure rides the
203
286
  batch: give a span a caller-local `spanId` and reference it from a sibling's
204
- `parentSpanId`. `attributes` are metadata only: tool names and argument
205
- shapes, never free-text conversation content. `Sight.captureSpan(span)` is
206
- the single-span form.
287
+ `parentSpanId`. In contract v2 every operational key is present; use `null`
288
+ for an unknown model, token count, cost, end time, or parent. Input and output
289
+ use explicit `captured`, `empty`, `not_captured`, `redacted`, or `unavailable`
290
+ states, so absence is never guessed from attributes. `attributes` are metadata
291
+ only. Optional `intervals` record internal `active`, `waiting`, `retry`, and
292
+ `error` windows. Every interval requires its own `startedAt` and `endedAt` and
293
+ must stay within the span; when intervals are omitted, the waterfall does not
294
+ invent them from status, names, or retry counters. Status is always explicit
295
+ `ok` or `error`; the historical `unset` state
296
+ is reserved for contract-v1 rows. The unversioned v1 shape remains accepted for older SDK callers and is
297
+ read through a legacy adapter. `Sight.captureSpan(span)` is the single-span
298
+ form.
207
299
 
208
300
  ## Scope
209
301
 
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { exec } from "child_process";
5
- import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
5
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
6
6
  import { homedir } from "os";
7
7
  import { dirname, join } from "path";
8
8
  var DEFAULT_API = "https://fieldwork-ingest.fly.dev";
@@ -19,7 +19,11 @@ function usage() {
19
19
  " sight connect <relay-url> --invite <code> [--pulse] [--api <base>]",
20
20
  " sight auth login [--base <dashboard-url>]",
21
21
  " sight auth logout",
22
- " sight export --project <slug> --deployment <slug> [--readings] [--out file.jsonl]",
22
+ " sight account create [--openrouter --budget <usd>] [--api <base>]",
23
+ " sight openrouter connect --budget <usd> [--api <base>]",
24
+ " sight openrouter status [--api <base>]",
25
+ " sight export --project <slug> --deployment <slug> [--readings|--conditions] [--out file.jsonl]",
26
+ " sight conditions --session <id-or-external-id> [--run <id>] [--since <iso>] [--until <iso>] [--base <dashboard-url>]",
23
27
  "",
24
28
  " connect attach Sight to a buzz community as a read-only observer.",
25
29
  " --invite one single-use invite code, minted by you on",
@@ -33,11 +37,21 @@ function usage() {
33
37
  " auth login sign this terminal in with your browser session \u2014 a",
34
38
  " code prints, you approve on the dashboard, done. The",
35
39
  " token lives at ~/.config/sight/credentials.json (0600).",
40
+ " account create redeem SIGHT_PROVISION_TOKEN without a browser and",
41
+ " save the scoped Sight key in machine.json (0600). Add",
42
+ " --openrouter to validate + seal OPENROUTER_API_KEY.",
43
+ " openrouter connect attach/rotate your BYOK key; requires a positive",
44
+ " local monthly --budget and a providers:write Sight key.",
36
45
  " export pull a deployment\u2019s full record (RLDS JSONL) with that",
37
46
  " token. Owner role on the project required.",
38
47
  " --readings pull the per-turn judge labels (the graded",
39
48
  " reads: closure, backward-pass, and the rest)",
40
49
  " instead of the record.",
50
+ " --conditions pull the detector checks: each checked",
51
+ " sentence, flagged / not flagged / not checked.",
52
+ " conditions pull one session\u2019s (or one run\u2019s) detector checks with",
53
+ " the machine key from ~/.config/sight/machine.json \u2014",
54
+ " NDJSON to stdout, errors to stderr.",
41
55
  "",
42
56
  "The SDK half of this package (serving-path capture) is documented at",
43
57
  "https://sight.cultured.computer/docs (the two lanes share one project)."
@@ -94,18 +108,24 @@ async function connect(args) {
94
108
  console.log(` ${body["claimUrl"]}`);
95
109
  return 0;
96
110
  }
111
+ var DEFAULT_DASHBOARD = "https://sight.cultured.computer";
97
112
  var [, , command, ...rest] = process.argv;
98
113
  if (command === "connect") {
99
114
  connect(rest).then((code) => process.exit(code));
100
115
  } else if (command === "auth") {
101
116
  auth(rest).then((code) => process.exit(code));
117
+ } else if (command === "account") {
118
+ account(rest).then((code) => process.exit(code));
119
+ } else if (command === "openrouter") {
120
+ openrouter(rest).then((code) => process.exit(code));
102
121
  } else if (command === "export") {
103
122
  exportRecord(rest).then((code) => process.exit(code));
123
+ } else if (command === "conditions") {
124
+ conditions(rest).then((code) => process.exit(code));
104
125
  } else {
105
126
  usage();
106
127
  process.exit(command && command !== "--help" && command !== "-h" ? 1 : 0);
107
128
  }
108
- var DEFAULT_DASHBOARD = "https://sight.cultured.computer";
109
129
  var CLIENT_ID = "sight-cli";
110
130
  function credentialsPath() {
111
131
  return join(process.env["XDG_CONFIG_HOME"] ?? join(homedir(), ".config"), "sight", "credentials.json");
@@ -125,6 +145,142 @@ function writeCredentials(token, base) {
125
145
  });
126
146
  chmodSync(p, 384);
127
147
  }
148
+ function machineCredentialsPath() {
149
+ return join(process.env["XDG_CONFIG_HOME"] ?? join(homedir(), ".config"), "sight", "machine.json");
150
+ }
151
+ function readMachineCredentials() {
152
+ try {
153
+ const value = JSON.parse(readFileSync(machineCredentialsPath(), "utf8"));
154
+ return value.apiKey && value.api ? value : null;
155
+ } catch {
156
+ return null;
157
+ }
158
+ }
159
+ function writeMachineCredentials(value) {
160
+ const path = machineCredentialsPath();
161
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
162
+ const temporary = mkdtempSync(join(dirname(path), ".machine-"));
163
+ try {
164
+ const pending = join(temporary, "machine.json");
165
+ writeFileSync(pending, JSON.stringify({ ...value, savedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2) + "\n", {
166
+ mode: 384
167
+ });
168
+ renameSync(pending, path);
169
+ } finally {
170
+ rmSync(temporary, { recursive: true, force: true });
171
+ }
172
+ }
173
+ function positiveBudget(args) {
174
+ const raw = flag(args, "--budget");
175
+ if (!raw) return null;
176
+ const value = Number(raw);
177
+ return Number.isFinite(value) && value > 0 && value <= 1e5 ? value : null;
178
+ }
179
+ async function connectOpenRouter(api, sightKey, args) {
180
+ const openRouterKey = process.env["OPENROUTER_API_KEY"];
181
+ if (!openRouterKey) {
182
+ console.error("OPENROUTER_API_KEY is required; it is read from the environment and never printed.");
183
+ return 1;
184
+ }
185
+ const budget = positiveBudget(args);
186
+ if (budget === null) {
187
+ console.error("--budget must be a positive monthly USD limit (maximum 100000).");
188
+ return 1;
189
+ }
190
+ const response = await fetch(`${api}/v1/provider-connections/openrouter`, {
191
+ method: "POST",
192
+ redirect: "error",
193
+ headers: {
194
+ authorization: `Bearer ${sightKey}`,
195
+ "content-type": "application/json"
196
+ },
197
+ body: JSON.stringify({ apiKey: openRouterKey, monthlyBudgetUsd: budget })
198
+ }).catch((_error) => ({ __error: _error }));
199
+ if (!response.ok) {
200
+ const body2 = response instanceof Response ? await response.json().catch(() => ({})) : {};
201
+ const status = response instanceof Response ? response.status : "unreachable";
202
+ console.error(`OpenRouter connect failed (${status}): ${body2["error"] ?? "network error"}`);
203
+ return 1;
204
+ }
205
+ const body = await response.json();
206
+ console.log(`OpenRouter connected (\u2026${String(body["last4"] ?? "")}); local monthly budget: $${budget}.`);
207
+ return 0;
208
+ }
209
+ async function account(args) {
210
+ if (args[0] !== "create") {
211
+ console.error("usage: sight account create [--openrouter --budget <usd>] [--api <base>]");
212
+ return 1;
213
+ }
214
+ const token = process.env["SIGHT_PROVISION_TOKEN"];
215
+ if (!token) {
216
+ console.error("SIGHT_PROVISION_TOKEN is required; keep it in the environment, not a command-line flag.");
217
+ return 1;
218
+ }
219
+ const api = (flag(args, "--api") ?? process.env["SIGHT_API"] ?? DEFAULT_API).replace(/\/+$/, "");
220
+ const response = await fetch(`${api}/v1/provision/redeem`, {
221
+ method: "POST",
222
+ redirect: "error",
223
+ headers: { "content-type": "application/json" },
224
+ body: JSON.stringify({ token })
225
+ }).catch((_error) => ({ __error: _error }));
226
+ if (!response.ok) {
227
+ const body2 = response instanceof Response ? await response.json().catch(() => ({})) : {};
228
+ const status = response instanceof Response ? response.status : "unreachable";
229
+ console.error(`account create failed (${status}): ${body2["error"] ?? "network error"}`);
230
+ return 1;
231
+ }
232
+ const body = await response.json();
233
+ if (!body.key || !body.project || !Array.isArray(body.capabilities)) {
234
+ console.error("account create failed: the server returned an incomplete credential.");
235
+ return 1;
236
+ }
237
+ writeMachineCredentials({
238
+ apiKey: body.key,
239
+ api,
240
+ project: body.project,
241
+ tier: body.tier ?? "research",
242
+ capabilities: body.capabilities
243
+ });
244
+ console.log(`Sight account ready for project ${body.project}; key saved at ${machineCredentialsPath()} (0600).`);
245
+ console.log(`capabilities: ${body.capabilities.join(", ") || "none"}`);
246
+ if (!args.includes("--openrouter")) return 0;
247
+ if (!body.capabilities.includes("providers:write")) {
248
+ console.error("The Sight key was saved, but provider setup requires providers:write. Ask the owner or operator for a separate management key.");
249
+ return 1;
250
+ }
251
+ const connected = await connectOpenRouter(api, body.key, args);
252
+ if (connected !== 0) {
253
+ console.error("The Sight key was saved. Fix the OpenRouter input and retry: sight openrouter connect --budget <usd>");
254
+ }
255
+ return connected;
256
+ }
257
+ async function openrouter(args) {
258
+ const sub = args[0];
259
+ if (sub !== "connect" && sub !== "status") {
260
+ console.error("usage: sight openrouter connect --budget <usd> [--api <base>] \xB7 sight openrouter status");
261
+ return 1;
262
+ }
263
+ const stored = readMachineCredentials();
264
+ const sightKey = process.env["SIGHT_API_KEY"] ?? stored?.apiKey;
265
+ const api = (flag(args, "--api") ?? process.env["SIGHT_API"] ?? stored?.api ?? DEFAULT_API).replace(/\/+$/, "");
266
+ if (!sightKey) {
267
+ console.error("No machine credential. Run sight account create or set SIGHT_API_KEY.");
268
+ return 1;
269
+ }
270
+ if (sub === "connect") return connectOpenRouter(api, sightKey, args);
271
+ const response = await fetch(`${api}/v1/provider-connections/openrouter`, {
272
+ redirect: "error",
273
+ headers: { authorization: `Bearer ${sightKey}` }
274
+ }).catch(() => null);
275
+ if (!response?.ok) {
276
+ const body2 = response ? await response.json().catch(() => ({})) : {};
277
+ console.error(`OpenRouter status failed (${response?.status ?? "unreachable"}): ${body2["error"] ?? body2["status"] ?? "network error"}`);
278
+ return 1;
279
+ }
280
+ const body = await response.json();
281
+ console.log(`OpenRouter ${body["status"]} (\u2026${String(body["last4"] ?? "")}); monthly budget: $${body["monthlyBudgetUsd"]}.`);
282
+ return 0;
283
+ }
128
284
  function openBrowser(url) {
129
285
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
130
286
  exec(`${cmd} "${url}"`);
@@ -208,8 +364,9 @@ async function exportRecord(args) {
208
364
  const deployment = flag(args, "--deployment");
209
365
  const out = flag(args, "--out") ?? null;
210
366
  const readings = args.includes("--readings");
211
- if (!project || !deployment) {
212
- console.error("usage: sight export --project <slug> --deployment <slug> [--readings] [--out file.jsonl]");
367
+ const conditions2 = args.includes("--conditions");
368
+ if (!project || !deployment || readings && conditions2) {
369
+ console.error("usage: sight export --project <slug> --deployment <slug> [--readings|--conditions] [--out file.jsonl]");
213
370
  return 1;
214
371
  }
215
372
  const creds = readCredentials();
@@ -217,7 +374,8 @@ async function exportRecord(args) {
217
374
  console.error("no stored login \u2014 run sight auth login first.");
218
375
  return 1;
219
376
  }
220
- const url = `${creds.base}/api/export?project=${encodeURIComponent(project)}&deployment=${encodeURIComponent(deployment)}` + (readings ? "&kind=readings" : "");
377
+ const kind = conditions2 ? "conditions" : readings ? "readings" : null;
378
+ const url = `${creds.base}/api/export?project=${encodeURIComponent(project)}&deployment=${encodeURIComponent(deployment)}` + (kind ? `&kind=${kind}` : "");
221
379
  const res = await fetch(url, {
222
380
  headers: { authorization: `Bearer ${creds.token}` }
223
381
  }).catch((err) => ({ __err: err }));
@@ -232,10 +390,43 @@ async function exportRecord(args) {
232
390
  if (out) {
233
391
  writeFileSync(out, text);
234
392
  console.log(
235
- `exported to ${out} (${text.split("\n").filter(Boolean).length} ${readings ? "readings" : "episodes"}).`
393
+ `exported to ${out} (${text.split("\n").filter(Boolean).length} ${kind ?? "episodes"}).`
236
394
  );
237
395
  } else {
238
396
  process.stdout.write(text);
239
397
  }
240
398
  return 0;
241
399
  }
400
+ async function conditions(args) {
401
+ const session = flag(args, "--session");
402
+ const run = flag(args, "--run");
403
+ if (!session && !run) {
404
+ console.error("usage: sight conditions --session <id-or-external-id> [--run <id>] [--since <iso>] [--until <iso>] [--base <dashboard-url>]");
405
+ return 1;
406
+ }
407
+ const stored = readMachineCredentials();
408
+ const sightKey = process.env["SIGHT_API_KEY"] ?? stored?.apiKey;
409
+ const base = (flag(args, "--base") ?? process.env["SIGHT_BASE"] ?? DEFAULT_DASHBOARD).replace(/\/+$/, "");
410
+ if (!sightKey) {
411
+ console.error("No machine credential. Run sight account create or set SIGHT_API_KEY.");
412
+ return 1;
413
+ }
414
+ const params = new URLSearchParams();
415
+ if (session) params.set("session", session);
416
+ if (run) params.set("run", run);
417
+ const since = flag(args, "--since");
418
+ if (since) params.set("since", since);
419
+ const until = flag(args, "--until");
420
+ if (until) params.set("until", until);
421
+ const res = await fetch(`${base}/api/studio/conditions?${params.toString()}`, {
422
+ redirect: "error",
423
+ headers: { authorization: `Bearer ${sightKey}` }
424
+ }).catch(() => null);
425
+ if (!res?.ok) {
426
+ const body = res ? await res.json().catch(() => ({})) : {};
427
+ console.error(`conditions failed (${res?.status ?? "unreachable"}): ${body["error"] ?? "network error"}`);
428
+ return 1;
429
+ }
430
+ process.stdout.write(await res.text());
431
+ return 0;
432
+ }