@cultured_computer/sight 0.6.0 → 0.8.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/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";
@@ -13,34 +13,70 @@ function flag(args, name) {
13
13
  function usage() {
14
14
  console.log(
15
15
  [
16
- "sight: the observer for agent conversations",
16
+ "sight: the command line for Sight. Sign a terminal in, export your data, read detector checks, set up a project.",
17
17
  "",
18
18
  "Usage:",
19
- " sight connect <relay-url> --invite <code> [--pulse] [--api <base>]",
20
19
  " sight auth login [--base <dashboard-url>]",
21
20
  " sight auth logout",
22
- " sight export --project <slug> --deployment <slug> [--readings] [--out file.jsonl]",
21
+ " sight export --project <slug> --deployment <slug> [--readings|--conditions] [--out file.jsonl]",
22
+ " sight conditions --session <id-or-external-id> [--deployment <slug>] [--run <id>] [--since <iso>] [--until <iso>] [--base <dashboard-url>]",
23
+ " sight account create [--openrouter --budget <usd>] [--api <base>]",
24
+ " sight openrouter connect --budget <usd> [--api <base>]",
25
+ " sight openrouter status [--api <base>]",
26
+ " sight connect <relay-url> --invite <code> [--pulse] [--api <base>]",
23
27
  "",
24
- " connect attach Sight to a buzz community as a read-only observer.",
25
- " --invite one single-use invite code, minted by you on",
26
- " your relay (its admin surface, or",
27
- " POST /api/invites as the community owner).",
28
- " Your invite is the authorization: Sight can",
29
- " never enter a community you did not invite it into.",
30
- " --pulse opt into the daily readout (off by",
31
- " default; counts, times, and links only).",
28
+ "Commands:",
29
+ " auth login sign this terminal in with your browser session: a code",
30
+ " prints, you approve it on the dashboard. The token is",
31
+ " stored at ~/.config/sight/credentials.json (0600).",
32
+ " auth logout delete the stored login token.",
33
+ " export pull a deployment\u2019s full record (RLDS JSONL) with the",
34
+ " login token. Owner role on the project required.",
35
+ " --readings pull the per-turn judge labels instead.",
36
+ " --conditions pull the detector checks instead: each",
37
+ " checked sentence, flagged / not flagged /",
38
+ " not checked.",
39
+ " --out <file> write to a file (default: stdout).",
40
+ " conditions pull one session\u2019s (or one run\u2019s) detector checks with",
41
+ " the machine key: NDJSON to stdout, errors to stderr.",
42
+ " account create redeem SIGHT_PROVISION_TOKEN without a browser and save",
43
+ " the scoped Sight key at ~/.config/sight/machine.json",
44
+ " (0600). Add --openrouter --budget <usd> to also",
45
+ " validate and store OPENROUTER_API_KEY.",
46
+ " openrouter connect attach or rotate your own OpenRouter key; requires a",
47
+ " positive monthly --budget and a Sight key with",
48
+ " providers:write.",
49
+ " openrouter status print the stored provider connection: status, last",
50
+ " four characters of the key, monthly budget.",
51
+ " connect attach Sight to a buzz community as a read-only",
52
+ " observer. No account needed.",
53
+ " --invite one single-use invite code, minted by you on",
54
+ " your relay (its admin surface, or",
55
+ " POST /api/invites as the community owner).",
56
+ " Sight can never enter a community you did",
57
+ " not invite it into.",
58
+ " --pulse opt into the daily readout (off by default;",
59
+ " counts, times, and links only).",
32
60
  "",
33
- " auth login sign this terminal in with your browser session \u2014 a",
34
- " code prints, you approve on the dashboard, done. The",
35
- " token lives at ~/.config/sight/credentials.json (0600).",
36
- " export pull a deployment\u2019s full record (RLDS JSONL) with that",
37
- " token. Owner role on the project required.",
38
- " --readings pull the per-turn judge labels (the graded",
39
- " reads: closure, backward-pass, and the rest)",
40
- " instead of the record.",
61
+ "Environment:",
62
+ " SIGHT_API ingest API base used by connect, account create and",
63
+ " openrouter. Default https://fieldwork-ingest.fly.dev",
64
+ " (openrouter: the base saved by account create, when",
65
+ " there is one). --api overrides it.",
66
+ " SIGHT_BASE dashboard base used by auth login and conditions.",
67
+ " Default https://sight.cultured.computer. --base",
68
+ " overrides it. export uses the base stored at login.",
69
+ " SIGHT_API_KEY Sight key for openrouter and conditions; overrides",
70
+ " the key stored in machine.json.",
71
+ " SIGHT_PROVISION_TOKEN one-time token redeemed by account create.",
72
+ " OPENROUTER_API_KEY your OpenRouter key, read by account create",
73
+ " --openrouter and openrouter connect. Never printed.",
41
74
  "",
42
- "The SDK half of this package (serving-path capture) is documented at",
43
- "https://sight.cultured.computer/docs (the two lanes share one project)."
75
+ "The Field API (serving a profile) has no CLI verbs. Its docs:",
76
+ "https://sight.cultured.computer/docs/serve-a-soul-md",
77
+ "",
78
+ "The capture SDK in this package (server-side Node >=20.6) is documented at",
79
+ "https://sight.cultured.computer/docs"
44
80
  ].join("\n")
45
81
  );
46
82
  }
@@ -94,18 +130,24 @@ async function connect(args) {
94
130
  console.log(` ${body["claimUrl"]}`);
95
131
  return 0;
96
132
  }
133
+ var DEFAULT_DASHBOARD = "https://sight.cultured.computer";
97
134
  var [, , command, ...rest] = process.argv;
98
135
  if (command === "connect") {
99
136
  connect(rest).then((code) => process.exit(code));
100
137
  } else if (command === "auth") {
101
138
  auth(rest).then((code) => process.exit(code));
139
+ } else if (command === "account") {
140
+ account(rest).then((code) => process.exit(code));
141
+ } else if (command === "openrouter") {
142
+ openrouter(rest).then((code) => process.exit(code));
102
143
  } else if (command === "export") {
103
144
  exportRecord(rest).then((code) => process.exit(code));
145
+ } else if (command === "conditions") {
146
+ conditions(rest).then((code) => process.exit(code));
104
147
  } else {
105
148
  usage();
106
149
  process.exit(command && command !== "--help" && command !== "-h" ? 1 : 0);
107
150
  }
108
- var DEFAULT_DASHBOARD = "https://sight.cultured.computer";
109
151
  var CLIENT_ID = "sight-cli";
110
152
  function credentialsPath() {
111
153
  return join(process.env["XDG_CONFIG_HOME"] ?? join(homedir(), ".config"), "sight", "credentials.json");
@@ -125,6 +167,142 @@ function writeCredentials(token, base) {
125
167
  });
126
168
  chmodSync(p, 384);
127
169
  }
170
+ function machineCredentialsPath() {
171
+ return join(process.env["XDG_CONFIG_HOME"] ?? join(homedir(), ".config"), "sight", "machine.json");
172
+ }
173
+ function readMachineCredentials() {
174
+ try {
175
+ const value = JSON.parse(readFileSync(machineCredentialsPath(), "utf8"));
176
+ return value.apiKey && value.api ? value : null;
177
+ } catch {
178
+ return null;
179
+ }
180
+ }
181
+ function writeMachineCredentials(value) {
182
+ const path = machineCredentialsPath();
183
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
184
+ const temporary = mkdtempSync(join(dirname(path), ".machine-"));
185
+ try {
186
+ const pending = join(temporary, "machine.json");
187
+ writeFileSync(pending, JSON.stringify({ ...value, savedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2) + "\n", {
188
+ mode: 384
189
+ });
190
+ renameSync(pending, path);
191
+ } finally {
192
+ rmSync(temporary, { recursive: true, force: true });
193
+ }
194
+ }
195
+ function positiveBudget(args) {
196
+ const raw = flag(args, "--budget");
197
+ if (!raw) return null;
198
+ const value = Number(raw);
199
+ return Number.isFinite(value) && value > 0 && value <= 1e5 ? value : null;
200
+ }
201
+ async function connectOpenRouter(api, sightKey, args) {
202
+ const openRouterKey = process.env["OPENROUTER_API_KEY"];
203
+ if (!openRouterKey) {
204
+ console.error("OPENROUTER_API_KEY is required; it is read from the environment and never printed.");
205
+ return 1;
206
+ }
207
+ const budget = positiveBudget(args);
208
+ if (budget === null) {
209
+ console.error("--budget must be a positive monthly USD limit (maximum 100000).");
210
+ return 1;
211
+ }
212
+ const response = await fetch(`${api}/v1/provider-connections/openrouter`, {
213
+ method: "POST",
214
+ redirect: "error",
215
+ headers: {
216
+ authorization: `Bearer ${sightKey}`,
217
+ "content-type": "application/json"
218
+ },
219
+ body: JSON.stringify({ apiKey: openRouterKey, monthlyBudgetUsd: budget })
220
+ }).catch((_error) => ({ __error: _error }));
221
+ if (!response.ok) {
222
+ const body2 = response instanceof Response ? await response.json().catch(() => ({})) : {};
223
+ const status = response instanceof Response ? response.status : "unreachable";
224
+ console.error(`OpenRouter connect failed (${status}): ${body2["error"] ?? "network error"}`);
225
+ return 1;
226
+ }
227
+ const body = await response.json();
228
+ console.log(`OpenRouter connected (\u2026${String(body["last4"] ?? "")}); local monthly budget: $${budget}.`);
229
+ return 0;
230
+ }
231
+ async function account(args) {
232
+ if (args[0] !== "create") {
233
+ console.error("usage: sight account create [--openrouter --budget <usd>] [--api <base>]");
234
+ return 1;
235
+ }
236
+ const token = process.env["SIGHT_PROVISION_TOKEN"];
237
+ if (!token) {
238
+ console.error("SIGHT_PROVISION_TOKEN is required; keep it in the environment, not a command-line flag.");
239
+ return 1;
240
+ }
241
+ const api = (flag(args, "--api") ?? process.env["SIGHT_API"] ?? DEFAULT_API).replace(/\/+$/, "");
242
+ const response = await fetch(`${api}/v1/provision/redeem`, {
243
+ method: "POST",
244
+ redirect: "error",
245
+ headers: { "content-type": "application/json" },
246
+ body: JSON.stringify({ token })
247
+ }).catch((_error) => ({ __error: _error }));
248
+ if (!response.ok) {
249
+ const body2 = response instanceof Response ? await response.json().catch(() => ({})) : {};
250
+ const status = response instanceof Response ? response.status : "unreachable";
251
+ console.error(`account create failed (${status}): ${body2["error"] ?? "network error"}`);
252
+ return 1;
253
+ }
254
+ const body = await response.json();
255
+ if (!body.key || !body.project || !Array.isArray(body.capabilities)) {
256
+ console.error("account create failed: the server returned an incomplete credential.");
257
+ return 1;
258
+ }
259
+ writeMachineCredentials({
260
+ apiKey: body.key,
261
+ api,
262
+ project: body.project,
263
+ tier: body.tier ?? "research",
264
+ capabilities: body.capabilities
265
+ });
266
+ console.log(`Sight account ready for project ${body.project}; key saved at ${machineCredentialsPath()} (0600).`);
267
+ console.log(`capabilities: ${body.capabilities.join(", ") || "none"}`);
268
+ if (!args.includes("--openrouter")) return 0;
269
+ if (!body.capabilities.includes("providers:write")) {
270
+ console.error("The Sight key was saved, but provider setup requires providers:write. Ask the owner or operator for a separate management key.");
271
+ return 1;
272
+ }
273
+ const connected = await connectOpenRouter(api, body.key, args);
274
+ if (connected !== 0) {
275
+ console.error("The Sight key was saved. Fix the OpenRouter input and retry: sight openrouter connect --budget <usd>");
276
+ }
277
+ return connected;
278
+ }
279
+ async function openrouter(args) {
280
+ const sub = args[0];
281
+ if (sub !== "connect" && sub !== "status") {
282
+ console.error("usage: sight openrouter connect --budget <usd> [--api <base>] \xB7 sight openrouter status");
283
+ return 1;
284
+ }
285
+ const stored = readMachineCredentials();
286
+ const sightKey = process.env["SIGHT_API_KEY"] ?? stored?.apiKey;
287
+ const api = (flag(args, "--api") ?? process.env["SIGHT_API"] ?? stored?.api ?? DEFAULT_API).replace(/\/+$/, "");
288
+ if (!sightKey) {
289
+ console.error("No machine credential. Run sight account create or set SIGHT_API_KEY.");
290
+ return 1;
291
+ }
292
+ if (sub === "connect") return connectOpenRouter(api, sightKey, args);
293
+ const response = await fetch(`${api}/v1/provider-connections/openrouter`, {
294
+ redirect: "error",
295
+ headers: { authorization: `Bearer ${sightKey}` }
296
+ }).catch(() => null);
297
+ if (!response?.ok) {
298
+ const body2 = response ? await response.json().catch(() => ({})) : {};
299
+ console.error(`OpenRouter status failed (${response?.status ?? "unreachable"}): ${body2["error"] ?? body2["status"] ?? "network error"}`);
300
+ return 1;
301
+ }
302
+ const body = await response.json();
303
+ console.log(`OpenRouter ${body["status"]} (\u2026${String(body["last4"] ?? "")}); monthly budget: $${body["monthlyBudgetUsd"]}.`);
304
+ return 0;
305
+ }
128
306
  function openBrowser(url) {
129
307
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
130
308
  exec(`${cmd} "${url}"`);
@@ -208,8 +386,9 @@ async function exportRecord(args) {
208
386
  const deployment = flag(args, "--deployment");
209
387
  const out = flag(args, "--out") ?? null;
210
388
  const readings = args.includes("--readings");
211
- if (!project || !deployment) {
212
- console.error("usage: sight export --project <slug> --deployment <slug> [--readings] [--out file.jsonl]");
389
+ const conditions2 = args.includes("--conditions");
390
+ if (!project || !deployment || readings && conditions2) {
391
+ console.error("usage: sight export --project <slug> --deployment <slug> [--readings|--conditions] [--out file.jsonl]");
213
392
  return 1;
214
393
  }
215
394
  const creds = readCredentials();
@@ -217,7 +396,8 @@ async function exportRecord(args) {
217
396
  console.error("no stored login \u2014 run sight auth login first.");
218
397
  return 1;
219
398
  }
220
- const url = `${creds.base}/api/export?project=${encodeURIComponent(project)}&deployment=${encodeURIComponent(deployment)}` + (readings ? "&kind=readings" : "");
399
+ const kind = conditions2 ? "conditions" : readings ? "readings" : null;
400
+ const url = `${creds.base}/api/export?project=${encodeURIComponent(project)}&deployment=${encodeURIComponent(deployment)}` + (kind ? `&kind=${kind}` : "");
221
401
  const res = await fetch(url, {
222
402
  headers: { authorization: `Bearer ${creds.token}` }
223
403
  }).catch((err) => ({ __err: err }));
@@ -232,10 +412,45 @@ async function exportRecord(args) {
232
412
  if (out) {
233
413
  writeFileSync(out, text);
234
414
  console.log(
235
- `exported to ${out} (${text.split("\n").filter(Boolean).length} ${readings ? "readings" : "episodes"}).`
415
+ `exported to ${out} (${text.split("\n").filter(Boolean).length} ${kind ?? "episodes"}).`
236
416
  );
237
417
  } else {
238
418
  process.stdout.write(text);
239
419
  }
240
420
  return 0;
241
421
  }
422
+ async function conditions(args) {
423
+ const session = flag(args, "--session");
424
+ const run = flag(args, "--run");
425
+ if (!session && !run) {
426
+ console.error("usage: sight conditions --session <id-or-external-id> [--deployment <slug>] [--run <id>] [--since <iso>] [--until <iso>] [--base <dashboard-url>]");
427
+ return 1;
428
+ }
429
+ const stored = readMachineCredentials();
430
+ const sightKey = process.env["SIGHT_API_KEY"] ?? stored?.apiKey;
431
+ const base = (flag(args, "--base") ?? process.env["SIGHT_BASE"] ?? DEFAULT_DASHBOARD).replace(/\/+$/, "");
432
+ if (!sightKey) {
433
+ console.error("No machine credential. Run sight account create or set SIGHT_API_KEY.");
434
+ return 1;
435
+ }
436
+ const params = new URLSearchParams();
437
+ if (session) params.set("session", session);
438
+ const deployment = flag(args, "--deployment");
439
+ if (deployment) params.set("deployment", deployment);
440
+ if (run) params.set("run", run);
441
+ const since = flag(args, "--since");
442
+ if (since) params.set("since", since);
443
+ const until = flag(args, "--until");
444
+ if (until) params.set("until", until);
445
+ const res = await fetch(`${base}/api/studio/conditions?${params.toString()}`, {
446
+ redirect: "error",
447
+ headers: { authorization: `Bearer ${sightKey}` }
448
+ }).catch(() => null);
449
+ if (!res?.ok) {
450
+ const body = res ? await res.json().catch(() => ({})) : {};
451
+ console.error(`conditions failed (${res?.status ?? "unreachable"}): ${body["error"] ?? "network error"}`);
452
+ return 1;
453
+ }
454
+ process.stdout.write(await res.text());
455
+ return 0;
456
+ }