@cultured_computer/sight 0.9.0 → 0.10.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/dist/cli.js CHANGED
@@ -5,11 +5,377 @@ import { exec } from "child_process";
5
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
+
9
+ // src/import.ts
10
+ import { createHash } from "crypto";
11
+ var IMPORT_FORMATS = ["chat-jsonl"];
12
+ var RATE_DEFAULT = 120;
13
+ var RATE_MIN = 1;
14
+ var RATE_MAX = 600;
15
+ var BATCH_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
16
+ var IMPORT_ENVELOPE_VERSION = "sdk-envelope-v1";
17
+ var MAX_TURN_BODY_BYTES = 9e5;
18
+ var LIST_LIMIT = 20;
19
+ var MAX_RETRIES = 4;
20
+ var BACKOFF_BASE_MS = 1e3;
21
+ var BACKOFF_CAP_MS = 3e4;
22
+ var RETRY_AFTER_MIN_S = 1;
23
+ var RETRY_AFTER_MAX_S = 60;
24
+ var REQUEST_TIMEOUT_MS = 15e3;
25
+ var PROGRESS_EVERY_MS = 5e3;
26
+ function parseFormat(raw) {
27
+ if (raw === null) return { ok: true, value: IMPORT_FORMATS[0] };
28
+ const known = IMPORT_FORMATS.find((format) => format === raw);
29
+ if (known) return { ok: true, value: known };
30
+ return { ok: false, error: `unknown format "${raw}". The known formats are: ${IMPORT_FORMATS.join(", ")}.` };
31
+ }
32
+ function parseBatch(raw) {
33
+ if (raw === null) {
34
+ return { ok: false, error: "import needs --batch <name>: a name for this import, stored on every session it creates." };
35
+ }
36
+ if (!BATCH_PATTERN.test(raw)) {
37
+ return { ok: false, error: `--batch "${raw}" is not a valid name. Use letters, digits, dot, dash and underscore, 1 to 64 characters.` };
38
+ }
39
+ return { ok: true, value: raw };
40
+ }
41
+ var REPLIES_BY = ["model", "person"];
42
+ function parseRepliesBy(raw) {
43
+ if (raw === null) return { ok: true, value: null };
44
+ const known = REPLIES_BY.find((value) => value === raw);
45
+ if (known) return { ok: true, value: known };
46
+ return { ok: false, error: `--replies-by "${raw}" is not known. It is one of: ${REPLIES_BY.join(", ")}.` };
47
+ }
48
+ function parseRate(raw) {
49
+ if (raw === null) return { ok: true, value: RATE_DEFAULT };
50
+ const value = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
51
+ if (!Number.isInteger(value) || value < RATE_MIN || value > RATE_MAX) {
52
+ return {
53
+ ok: false,
54
+ error: `--rate "${raw}" is out of range. It is requests per minute: a whole number from ${RATE_MIN} to ${RATE_MAX} (the capture API's limit for one project). The default is ${RATE_DEFAULT}.`
55
+ };
56
+ }
57
+ return { ok: true, value };
58
+ }
59
+ function turnIdFor(deployment, conversationId, turnIndex) {
60
+ if (deployment.includes("\0")) throw new Error("a deployment slug cannot contain a NUL character");
61
+ if (!Number.isInteger(turnIndex) || turnIndex < 0) throw new Error("a turn index is a whole number from 0");
62
+ const bytes = createHash("sha256").update(`${deployment}\0${conversationId}\0${turnIndex}`, "utf8").digest().subarray(0, 16);
63
+ bytes[6] = bytes[6] & 15 | 80;
64
+ bytes[8] = bytes[8] & 63 | 128;
65
+ const hex = Buffer.from(bytes).toString("hex");
66
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
67
+ }
68
+ var ROLES = ["system", "user", "assistant", "tool"];
69
+ var ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/;
70
+ function parseTime(value) {
71
+ if (typeof value !== "string" || !ISO_DATE_TIME.test(value)) return null;
72
+ const ms = Date.parse(value);
73
+ return Number.isFinite(ms) ? ms : null;
74
+ }
75
+ var iso = (ms) => new Date(ms).toISOString();
76
+ function readConversation(value) {
77
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
78
+ return { ok: false, id: null, reason: "the line is not a JSON object" };
79
+ }
80
+ const line = value;
81
+ if (typeof line["id"] !== "string") return { ok: false, id: null, reason: 'the conversation has no "id" string' };
82
+ const id = line["id"].trim();
83
+ if (id === "") return { ok: false, id: null, reason: `the conversation's "id" is empty` };
84
+ const refuse = (reason) => ({ ok: false, id, reason });
85
+ if (!Array.isArray(line["messages"])) return refuse('"messages" is not a list');
86
+ const messages = [];
87
+ let invalidTimes = 0;
88
+ let last = null;
89
+ for (const [index, raw] of line["messages"].entries()) {
90
+ const position = index + 1;
91
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return refuse(`message ${position} is not an object`);
92
+ const message = raw;
93
+ const role = ROLES.find((known) => known === message["role"]);
94
+ if (!role) return refuse(`message ${position} has the role ${JSON.stringify(message["role"])}. The roles are: ${ROLES.join(", ")}.`);
95
+ if (typeof message["content"] !== "string") return refuse(`message ${position} has no "content" string`);
96
+ let at = null;
97
+ if (message["at"] !== void 0 && message["at"] !== null) {
98
+ at = parseTime(message["at"]);
99
+ if (at === null) invalidTimes += 1;
100
+ }
101
+ if (at !== null) {
102
+ if (last !== null && at < last.at) {
103
+ return refuse(`the message times go backwards: message ${position} (${iso(at)}) is earlier than message ${last.position} (${iso(last.at)})`);
104
+ }
105
+ last = { at, position };
106
+ }
107
+ messages.push({ role, content: message["content"], at });
108
+ }
109
+ for (const key of ["model", "user"]) {
110
+ if (line[key] !== void 0 && line[key] !== null && typeof line[key] !== "string") return refuse(`"${key}" is not a string`);
111
+ }
112
+ const model = typeof line["model"] === "string" && line["model"].trim() !== "" ? line["model"].trim() : null;
113
+ const user = typeof line["user"] === "string" && line["user"].trim() !== "" ? line["user"].trim() : null;
114
+ let repliesBy = null;
115
+ if (line["replies_by"] !== void 0 && line["replies_by"] !== null) {
116
+ const known = REPLIES_BY.find((value2) => value2 === line["replies_by"]);
117
+ if (!known) return refuse(`"replies_by" is ${JSON.stringify(line["replies_by"])}. It is one of: ${REPLIES_BY.join(", ")}.`);
118
+ repliesBy = known;
119
+ }
120
+ return { ok: true, conversation: { id, messages, model, user, repliesBy, invalidTimes } };
121
+ }
122
+ function repliesByOf(conversation, options) {
123
+ return conversation.repliesBy ?? options.repliesBy ?? null;
124
+ }
125
+ function modelFields(model) {
126
+ if (model === null) return {};
127
+ const slash = model.indexOf("/");
128
+ const vendor = slash > 0 ? model.slice(0, slash).trim() : "";
129
+ const name = slash > 0 ? model.slice(slash + 1).trim() : "";
130
+ if (vendor === "" || name === "") return { probe_model: model };
131
+ return { probe_model: name, probe_provider: vendor.toLowerCase() };
132
+ }
133
+ function mapConversation(conversation, options) {
134
+ const turns = [];
135
+ const person = repliesByOf(conversation, options) === "person";
136
+ let pending = [];
137
+ let systemMessages = 0;
138
+ let toolMessages = 0;
139
+ for (const message of conversation.messages) {
140
+ if (message.role === "system") systemMessages += 1;
141
+ else if (message.role === "tool") toolMessages += 1;
142
+ else if (message.role === "user") pending.push(message.content);
143
+ else {
144
+ const turnIndex = turns.length;
145
+ const text = pending.filter((part) => part.trim() !== "").join("\n\n");
146
+ turns.push({
147
+ sessionExternalId: conversation.id,
148
+ turnIndex,
149
+ turnId: turnIdFor(options.deployment, conversation.id, turnIndex),
150
+ ...message.at !== null ? { startedAt: iso(message.at) } : {},
151
+ ...text !== "" ? { userInput: { text } } : {},
152
+ payload: {
153
+ ...message.content !== "" ? { response: { text: message.content } } : {},
154
+ ...modelFields(conversation.model)
155
+ },
156
+ deploymentSlug: options.deployment,
157
+ envelopeVersion: IMPORT_ENVELOPE_VERSION,
158
+ ...conversation.user !== null ? { externalUserId: conversation.user } : {},
159
+ clientContext: { metadata: { batch: options.batch, import: { format: options.format } } },
160
+ // The session is created by whichever turn is processed first, so
161
+ // every turn of the conversation says it.
162
+ ...person ? { repliesBy: "person" } : {}
163
+ });
164
+ pending = [];
165
+ }
166
+ }
167
+ const lastAt = conversation.messages.at(-1)?.at ?? null;
168
+ return {
169
+ turns,
170
+ sessionEnd: {
171
+ deploymentSlug: options.deployment,
172
+ sessionExternalId: conversation.id,
173
+ ...lastAt !== null ? { endedAt: iso(lastAt) } : {}
174
+ },
175
+ systemMessages,
176
+ toolMessages,
177
+ unansweredUserMessages: pending.length
178
+ };
179
+ }
180
+ function planImport(text, options) {
181
+ const rows = [];
182
+ const lines = text.replace(/^/, "").split("\n");
183
+ for (const [index, rawLine] of lines.entries()) {
184
+ const line = index + 1;
185
+ if (rawLine.trim() === "") continue;
186
+ let value;
187
+ try {
188
+ value = JSON.parse(rawLine);
189
+ } catch {
190
+ rows.push({ line, ok: false, id: null, reason: "the line is not valid JSON" });
191
+ continue;
192
+ }
193
+ rows.push({ line, ...readConversation(value) });
194
+ }
195
+ const linesOf = /* @__PURE__ */ new Map();
196
+ for (const row of rows) {
197
+ const id = row.ok ? row.conversation.id : row.id;
198
+ if (id === null) continue;
199
+ linesOf.set(id, [...linesOf.get(id) ?? [], row.line]);
200
+ }
201
+ const plan = {
202
+ conversations: [],
203
+ turns: 0,
204
+ skipped: [],
205
+ refused: [],
206
+ systemMessages: 0,
207
+ toolMessages: 0,
208
+ unansweredUserMessages: 0,
209
+ invalidTimes: 0,
210
+ personReplies: 0,
211
+ modelNotSaid: 0,
212
+ modelWithoutVendor: 0
213
+ };
214
+ for (const row of rows) {
215
+ if (!row.ok) {
216
+ plan.refused.push({ line: row.line, id: row.id, reason: row.reason });
217
+ continue;
218
+ }
219
+ const { conversation } = row;
220
+ const shared = linesOf.get(conversation.id) ?? [];
221
+ if (shared.length > 1) {
222
+ plan.refused.push({
223
+ line: row.line,
224
+ id: conversation.id,
225
+ reason: `the id is on more than one line (lines ${shared.join(", ")}). Each conversation needs its own id.`
226
+ });
227
+ continue;
228
+ }
229
+ const repliesBy = repliesByOf(conversation, options);
230
+ if (repliesBy === "person" && conversation.model !== null) {
231
+ plan.refused.push({
232
+ line: row.line,
233
+ id: conversation.id,
234
+ reason: `the conversation says a person replies and also names a model (${JSON.stringify(conversation.model)}). Say one of the two.`
235
+ });
236
+ continue;
237
+ }
238
+ const mapped = mapConversation(conversation, options);
239
+ if (mapped.turns.length === 0) {
240
+ plan.skipped.push({ line: row.line, id: conversation.id });
241
+ continue;
242
+ }
243
+ const requests = mapped.turns.map((turn) => ({
244
+ path: "/v1/turns",
245
+ body: JSON.stringify(turn),
246
+ conversationId: conversation.id,
247
+ turnIndex: turn.turnIndex
248
+ }));
249
+ const tooLarge = requests.find((request) => Buffer.byteLength(request.body, "utf8") > MAX_TURN_BODY_BYTES);
250
+ if (tooLarge) {
251
+ plan.refused.push({
252
+ line: row.line,
253
+ id: conversation.id,
254
+ reason: `turn ${tooLarge.turnIndex} is ${Buffer.byteLength(tooLarge.body, "utf8")} bytes as sent. One request holds at most ${MAX_TURN_BODY_BYTES} bytes.`
255
+ });
256
+ continue;
257
+ }
258
+ requests.push({
259
+ path: "/v1/sessions/end",
260
+ body: JSON.stringify(mapped.sessionEnd),
261
+ conversationId: conversation.id,
262
+ turnIndex: null
263
+ });
264
+ plan.conversations.push({ id: conversation.id, line: row.line, requests });
265
+ plan.turns += mapped.turns.length;
266
+ plan.systemMessages += mapped.systemMessages;
267
+ plan.toolMessages += mapped.toolMessages;
268
+ plan.unansweredUserMessages += mapped.unansweredUserMessages;
269
+ plan.invalidTimes += conversation.invalidTimes;
270
+ if (repliesBy === "person") plan.personReplies += 1;
271
+ else if (conversation.model === null) plan.modelNotSaid += 1;
272
+ else if (modelFields(conversation.model).probe_provider === void 0) plan.modelWithoutVendor += 1;
273
+ }
274
+ return plan;
275
+ }
276
+ function requestCount(plan) {
277
+ return plan.turns + plan.conversations.length;
278
+ }
279
+ function estimatedMinutes(plan, rate) {
280
+ return Math.ceil(requestCount(plan) / rate);
281
+ }
282
+ function retryAfterMs(response) {
283
+ const raw = response.headers.get("retry-after");
284
+ if (raw === null || raw.trim() === "") return null;
285
+ const seconds = Number(raw);
286
+ if (!Number.isFinite(seconds)) return null;
287
+ return Math.min(Math.max(seconds, RETRY_AFTER_MIN_S), RETRY_AFTER_MAX_S) * 1e3;
288
+ }
289
+ function backoffMs(retry) {
290
+ return Math.min(BACKOFF_BASE_MS * 2 ** retry, BACKOFF_CAP_MS);
291
+ }
292
+ async function errorText(response) {
293
+ const text = await response.text().catch(() => "");
294
+ try {
295
+ const body = JSON.parse(text);
296
+ if (typeof body.error === "string") return body.error;
297
+ } catch {
298
+ }
299
+ return text.trim().slice(0, 300) || "no error text";
300
+ }
301
+ async function sendImport(plan, options, deps) {
302
+ const intervalMs = 6e4 / options.rate;
303
+ const progressEveryMs = options.progressEveryMs ?? PROGRESS_EVERY_MS;
304
+ const result = { conversationsSent: 0, turnsSent: 0, sessionEndsSent: 0, stopped: null };
305
+ const requestsTotal = requestCount(plan);
306
+ let requestsSent = 0;
307
+ let nextAt = deps.now();
308
+ let lastProgressAt = deps.now();
309
+ const paced = async (request) => {
310
+ const wait = nextAt - deps.now();
311
+ if (wait > 0) await deps.sleep(wait);
312
+ nextAt = Math.max(deps.now(), nextAt) + intervalMs;
313
+ try {
314
+ return await deps.fetch(`${options.api}${request.path}`, {
315
+ method: "POST",
316
+ redirect: "error",
317
+ headers: { Authorization: `Bearer ${options.apiKey}`, "content-type": "application/json" },
318
+ body: request.body,
319
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
320
+ });
321
+ } catch (error) {
322
+ return error instanceof Error ? error : new Error(String(error));
323
+ }
324
+ };
325
+ const send = async (request) => {
326
+ for (let attempt = 0; ; attempt++) {
327
+ const answer = await paced(request);
328
+ if (answer instanceof Response && answer.ok) {
329
+ await answer.body?.cancel().catch(() => {
330
+ });
331
+ return null;
332
+ }
333
+ const retryable = !(answer instanceof Response) || answer.status === 429 || answer.status >= 500;
334
+ if (!retryable || attempt === MAX_RETRIES) {
335
+ return {
336
+ status: answer instanceof Response ? answer.status : null,
337
+ path: request.path,
338
+ conversationId: request.conversationId,
339
+ turnIndex: request.turnIndex,
340
+ detail: answer instanceof Response ? await errorText(answer) : answer.message,
341
+ attempts: attempt + 1
342
+ };
343
+ }
344
+ const wait = (answer instanceof Response ? retryAfterMs(answer) : null) ?? backoffMs(attempt);
345
+ if (answer instanceof Response) await answer.body?.cancel().catch(() => {
346
+ });
347
+ await deps.sleep(wait);
348
+ }
349
+ };
350
+ for (const conversation of plan.conversations) {
351
+ for (const request of conversation.requests) {
352
+ const stopped = await send(request);
353
+ if (stopped) return { ...result, stopped };
354
+ requestsSent += 1;
355
+ if (request.turnIndex === null) result.sessionEndsSent += 1;
356
+ else result.turnsSent += 1;
357
+ if (request.turnIndex === null) result.conversationsSent += 1;
358
+ if (options.onProgress && deps.now() - lastProgressAt >= progressEveryMs) {
359
+ lastProgressAt = deps.now();
360
+ options.onProgress({
361
+ requestsSent,
362
+ requestsTotal,
363
+ conversationsSent: result.conversationsSent,
364
+ conversationsTotal: plan.conversations.length
365
+ });
366
+ }
367
+ }
368
+ }
369
+ return result;
370
+ }
371
+
372
+ // src/cli.ts
8
373
  var DEFAULT_API = "https://api.cultured.computer";
9
374
  function flag(args, name) {
10
375
  const i = args.indexOf(name);
11
376
  return i === -1 ? null : args[i + 1] ?? null;
12
377
  }
378
+ var IMPORT_USAGE = "sight import <file> --deployment <slug> --batch <name> [--format chat-jsonl] [--replies-by model|person] [--rate <requests per minute>] [--dry-run] [--api <base>]";
13
379
  function usage() {
14
380
  console.log(
15
381
  [
@@ -20,6 +386,7 @@ function usage() {
20
386
  " sight auth logout",
21
387
  " sight export --project <slug> --deployment <slug> [--readings|--conditions|--labels] [--out file.jsonl]",
22
388
  " sight conditions --session <id-or-external-id> [--deployment <slug>] [--run <id>] [--since <iso>] [--until <iso>] [--base <dashboard-url>]",
389
+ ` ${IMPORT_USAGE}`,
23
390
  " sight account create [--openrouter --budget <usd>] [--api <base>]",
24
391
  " sight openrouter connect --budget <usd> [--house-trial] [--api <base>]",
25
392
  " sight openrouter status [--api <base>]",
@@ -30,16 +397,21 @@ function usage() {
30
397
  " auth logout Delete the stored login token.",
31
398
  " export Write a deployment's record (or --readings, --conditions, --labels) as JSONL. Needs auth login, owner role.",
32
399
  " conditions Print a session's or a run's detector checks as NDJSON. Needs a key with studio:run.",
400
+ " import Send historical conversations from a JSONL file through the capture route, with their original times.",
401
+ " Sending the same file again adds nothing to the record. It is meant for a deployment that has no live traffic,",
402
+ " or for small files, because imported turns wait in the same queue as live ones. The hourly",
403
+ " aggregates cover the last seven days, so older conversations do not appear in them.",
404
+ " Needs a key with ingest. sight import --help describes the file.",
33
405
  " account create Redeem SIGHT_PROVISION_TOKEN; save the key to ~/.config/sight/machine.json (0600).",
34
406
  " openrouter connect Connect your OpenRouter key with a monthly USD budget. Needs a key with providers:write.",
35
407
  " openrouter status Print the stored OpenRouter connection: status, last four characters, budget.",
36
408
  " connect Connect a relay as a read-only observer, with a single-use invite code.",
37
409
  "",
38
410
  "Environment:",
39
- " SIGHT_API_KEY Sight key for conditions and openrouter. Default: the key saved by account create.",
411
+ " SIGHT_API_KEY Sight key for conditions, import and openrouter. Default: the key saved by account create.",
40
412
  " SIGHT_PROVISION_TOKEN One-time token redeemed by account create.",
41
413
  " OPENROUTER_API_KEY Your OpenRouter key, for account create --openrouter and openrouter connect.",
42
- " SIGHT_API API base for account create, openrouter, connect. Default https://api.cultured.computer",
414
+ " SIGHT_API API base for account create, openrouter, connect, import. Default https://api.cultured.computer",
43
415
  " SIGHT_BASE Dashboard base for auth login and conditions. Default https://sight.cultured.computer",
44
416
  " SIGHT_NO_BROWSER 1 prints the auth login link without opening a browser (same as --no-browser).",
45
417
  " XDG_CONFIG_HOME Directory for the stored login and key files. Default ~/.config",
@@ -419,6 +791,222 @@ async function conditions(args) {
419
791
  process.stdout.write(await res.text());
420
792
  return 0;
421
793
  }
794
+ function importHelp() {
795
+ console.log(
796
+ [
797
+ "sight import: send historical conversations through the capture route.",
798
+ "",
799
+ "Usage:",
800
+ ` ${IMPORT_USAGE}`,
801
+ "",
802
+ "It reads conversations from a file and sends each one through the capture route, the same route the SDK uses,",
803
+ "with their original times. Each assistant message becomes one turn; the turn carries the user messages that",
804
+ "came before it. When a conversation is sent, its session is ended.",
805
+ "",
806
+ "Sending the same file again adds nothing to the record: each turn has an id made from the deployment, the",
807
+ "conversation id and the turn's position, and a turn that arrives a second time is dropped. If an import stops,",
808
+ "run the same command again. Every request the capture route accepts is counted as an accepted turn, a repeat",
809
+ "included.",
810
+ "",
811
+ "It is meant for a deployment that has no live traffic, or for small files, because imported turns wait in the",
812
+ "same queue as live ones. The hourly aggregates cover the last seven days, so older conversations do not",
813
+ "appear in them.",
814
+ "",
815
+ "The file (format chat-jsonl) is JSONL, one conversation on each line:",
816
+ ' { "id": "c-1", "messages": [{ "role": "user", "content": "Hello", "at": "2026-03-01T09:30:00Z" }, ...],',
817
+ ' "model": "vendor/model", "user": "u-1" }',
818
+ " id Required. It becomes the session's external id. Each line needs its own.",
819
+ " messages Required. Each has a role (system, user, assistant or tool) and a content string.",
820
+ " System and tool messages are counted and not sent.",
821
+ " at Optional, on a message: an ISO 8601 time with a time zone. An assistant message's time becomes its",
822
+ " turn's time. Times must not go backwards within a conversation.",
823
+ " model Optional. vendor/model sets the provider and the model; a name with no slash sets the model alone,",
824
+ " and an evaluator run needs the vendor. The vendor is who made the model, not where it ran.",
825
+ " user Optional. Your id for the person, stored as the session's user.",
826
+ ' replies_by Optional: "model" or "person". Say "person" when the replies were written by a person and no',
827
+ " model took part, as in a call between two people. A conversation says a model or a person,",
828
+ " never both.",
829
+ "",
830
+ "A call between two people: give the agent's lines the role assistant and the other person's lines the role",
831
+ 'user, and say "replies_by": "person" on the conversation, or pass --replies-by person for the whole file.',
832
+ "A conversation that names no model and does not say a person replies goes on the record, and an evaluator",
833
+ "run over it is refused until the file says one or the other. A session keeps what it was created with: to",
834
+ "change what a conversation says after it was sent, send it again under a new id.",
835
+ "",
836
+ "Flags:",
837
+ " --deployment <slug> Required. The deployment the conversations belong to.",
838
+ " --batch <name> Required. A name for this import, stored on every session it creates.",
839
+ " Letters, digits, dot, dash and underscore, 1 to 64 characters.",
840
+ ` --format <name> The file format. Known formats: ${IMPORT_FORMATS.join(", ")}. Default ${IMPORT_FORMATS[0]}.`,
841
+ ` --replies-by <who> Who replies in a conversation that does not say: ${REPLIES_BY.join(" or ")}. No default.`,
842
+ ` --rate <n> Requests per minute, ${RATE_MIN} to ${RATE_MAX}. Default ${RATE_DEFAULT}.`,
843
+ " --dry-run Read and check the whole file, print the summary, send nothing.",
844
+ " --api <base> The API base. Default SIGHT_API, then the base saved by account create.",
845
+ "",
846
+ "A conversation with no assistant message is skipped. A line that cannot be sent as written is refused and",
847
+ "listed, and the rest of the file is sent; the command then exits 1. A request that answers 429 or 5xx is",
848
+ `sent again up to ${MAX_RETRIES} times. Any other refusal stops the import.`,
849
+ "",
850
+ "It needs a key with ingest: SIGHT_API_KEY, or the key saved by account create. A dry run needs no key."
851
+ ].join("\n")
852
+ );
853
+ }
854
+ function importNotSent(plan) {
855
+ const lines = [];
856
+ lines.push(`skipped, no assistant message: ${plan.skipped.length}`);
857
+ for (const entry of plan.skipped.slice(0, LIST_LIMIT)) lines.push(` line ${entry.line}: ${entry.id}`);
858
+ if (plan.skipped.length > LIST_LIMIT) lines.push(` and ${plan.skipped.length - LIST_LIMIT} more`);
859
+ lines.push(`refused: ${plan.refused.length}`);
860
+ for (const entry of plan.refused.slice(0, LIST_LIMIT)) {
861
+ lines.push(` line ${entry.line}${entry.id === null ? "" : ` (${entry.id})`}: ${entry.reason}`);
862
+ }
863
+ if (plan.refused.length > LIST_LIMIT) lines.push(` and ${plan.refused.length - LIST_LIMIT} more`);
864
+ return lines;
865
+ }
866
+ async function importConversations(args) {
867
+ if (args.includes("--help") || args.includes("-h")) {
868
+ importHelp();
869
+ return 0;
870
+ }
871
+ const valueFlags = ["--deployment", "--batch", "--format", "--replies-by", "--rate", "--api"];
872
+ const files = [];
873
+ for (let i = 0; i < args.length; i++) {
874
+ const arg = args[i];
875
+ if (valueFlags.includes(arg)) {
876
+ const value = args[i + 1];
877
+ if (value === void 0 || value.startsWith("-")) {
878
+ console.error(`import: the flag ${arg} needs a value.
879
+ usage: ${IMPORT_USAGE}`);
880
+ return 1;
881
+ }
882
+ i++;
883
+ } else if (arg === "--dry-run") continue;
884
+ else if (arg.startsWith("-")) {
885
+ console.error(`import does not know the flag ${arg}.
886
+ usage: ${IMPORT_USAGE}`);
887
+ return 1;
888
+ } else files.push(arg);
889
+ }
890
+ const deployment = flag(args, "--deployment");
891
+ if (files.length !== 1 || !deployment) {
892
+ console.error(`usage: ${IMPORT_USAGE}
893
+ sight import --help describes the file and the flags.`);
894
+ return 1;
895
+ }
896
+ const format = parseFormat(flag(args, "--format"));
897
+ const batch = parseBatch(flag(args, "--batch"));
898
+ const rate = parseRate(flag(args, "--rate"));
899
+ const repliesBy = parseRepliesBy(flag(args, "--replies-by"));
900
+ for (const option of [format, batch, rate, repliesBy]) {
901
+ if (!option.ok) {
902
+ console.error(option.error);
903
+ return 1;
904
+ }
905
+ }
906
+ if (!format.ok || !batch.ok || !rate.ok || !repliesBy.ok) return 1;
907
+ const dryRun = args.includes("--dry-run");
908
+ const stored = readMachineCredentials();
909
+ const sightKey = process.env["SIGHT_API_KEY"] ?? stored?.apiKey;
910
+ const api = (flag(args, "--api") ?? process.env["SIGHT_API"] ?? stored?.api ?? DEFAULT_API).replace(/\/+$/, "");
911
+ if (!dryRun && !sightKey) {
912
+ console.error("No Sight key found. Set SIGHT_API_KEY, or run sight account create.");
913
+ return 1;
914
+ }
915
+ const file = files[0];
916
+ let text;
917
+ try {
918
+ text = readFileSync(file, "utf8");
919
+ } catch (err) {
920
+ console.error(`could not read ${file}: ${err instanceof Error ? err.message : err}`);
921
+ return 1;
922
+ }
923
+ const plan = planImport(text, { deployment, batch: batch.value, format: format.value, repliesBy: repliesBy.value });
924
+ const notes = [];
925
+ if (plan.personReplies > 0) notes.push(`conversations in which a person replies: ${plan.personReplies}`);
926
+ if (plan.modelNotSaid > 0) {
927
+ notes.push(
928
+ `conversations that name no model and do not say a person replies: ${plan.modelNotSaid}. They go on the record; an evaluator run over them is refused until the file says "model" or "replies_by".`
929
+ );
930
+ }
931
+ if (plan.unansweredUserMessages > 0) {
932
+ notes.push(`user messages after the last reply, not sent: ${plan.unansweredUserMessages}`);
933
+ }
934
+ if (plan.invalidTimes > 0) {
935
+ notes.push(
936
+ `message times left out: ${plan.invalidTimes}. A time is an ISO 8601 date and time with a time zone, for example 2026-03-01T09:30:00Z. A turn with no time takes the time it is processed.`
937
+ );
938
+ }
939
+ if (plan.modelWithoutVendor > 0) {
940
+ notes.push(
941
+ `conversations whose model names no vendor: ${plan.modelWithoutVendor}. Write the model as vendor/model (for example openai/gpt-4o); an evaluator run over a conversation with no vendor on record is refused.`
942
+ );
943
+ }
944
+ const refusedCount = `${plan.refused.length} ${plan.refused.length === 1 ? "conversation was" : "conversations were"} refused`;
945
+ if (dryRun) {
946
+ const minutes = estimatedMinutes(plan, rate.value);
947
+ console.log(
948
+ [
949
+ "dry run: nothing was sent.",
950
+ `file: ${file} (format ${format.value}), deployment ${deployment}, batch ${batch.value}`,
951
+ `conversations to send: ${plan.conversations.length}`,
952
+ `turns to send: ${plan.turns}`,
953
+ ...importNotSent(plan),
954
+ `system messages not sent: ${plan.systemMessages}`,
955
+ `tool messages not sent: ${plan.toolMessages}`,
956
+ ...notes,
957
+ `estimated time: ${requestCount(plan) < rate.value ? "under a minute" : `about ${minutes} ${minutes === 1 ? "minute" : "minutes"}`} at ${rate.value} requests per minute (${requestCount(plan)} requests)`
958
+ ].join("\n")
959
+ );
960
+ if (plan.refused.length > 0) {
961
+ console.error(`${refusedCount}. Correct the lines listed above; an import sends the rest of the file without them.`);
962
+ return 1;
963
+ }
964
+ return 0;
965
+ }
966
+ const result = await sendImport(
967
+ plan,
968
+ {
969
+ api,
970
+ apiKey: sightKey,
971
+ rate: rate.value,
972
+ onProgress: (progress) => {
973
+ console.error(
974
+ `sent ${progress.requestsSent} of ${progress.requestsTotal} requests (${progress.conversationsSent} of ${progress.conversationsTotal} conversations)`
975
+ );
976
+ }
977
+ },
978
+ { fetch: (url, init) => fetch(url, init), now: () => Date.now(), sleep }
979
+ );
980
+ console.log(
981
+ [
982
+ result.stopped ? "import stopped before the end of the file." : "import finished.",
983
+ `conversations sent: ${result.conversationsSent}`,
984
+ `turns sent: ${result.turnsSent}`,
985
+ `session ends sent: ${result.sessionEndsSent}`,
986
+ ...importNotSent(plan),
987
+ ...notes
988
+ ].join("\n")
989
+ );
990
+ if (result.stopped) {
991
+ const stop = result.stopped;
992
+ const what = stop.turnIndex === null ? "the session end" : `turn ${stop.turnIndex}`;
993
+ const answer = stop.status === null ? "got no answer" : `answered ${stop.status}`;
994
+ console.error(
995
+ [
996
+ `import stopped: POST ${stop.path} ${answer} for conversation ${stop.conversationId}, ${what}, after ${stop.attempts} ${stop.attempts === 1 ? "attempt" : "attempts"}: ${stop.detail}`,
997
+ "Nothing after it was sent. Running the same command again is safe: every turn keeps its id, so the turns already sent add nothing."
998
+ ].join("\n")
999
+ );
1000
+ return 1;
1001
+ }
1002
+ if (plan.refused.length > 0) {
1003
+ console.error(
1004
+ `${refusedCount} and not sent. Correct the lines listed above and run the command again: the conversations already sent add nothing.`
1005
+ );
1006
+ return 1;
1007
+ }
1008
+ return 0;
1009
+ }
422
1010
  var [, , command, ...rest] = process.argv;
423
1011
  if (command === "connect") {
424
1012
  connect(rest).then((code) => process.exit(code));
@@ -432,6 +1020,8 @@ if (command === "connect") {
432
1020
  exportRecord(rest).then((code) => process.exit(code));
433
1021
  } else if (command === "conditions") {
434
1022
  conditions(rest).then((code) => process.exit(code));
1023
+ } else if (command === "import") {
1024
+ importConversations(rest).then((code) => process.exit(code));
435
1025
  } else {
436
1026
  usage();
437
1027
  process.exit(command && command !== "--help" && command !== "-h" ? 1 : 0);
package/dist/index.cjs CHANGED
@@ -2461,6 +2461,7 @@ var UserOutcomeSchema = zod.z.object({
2461
2461
  /** Thumbs-up / thumbs-down widget value. */
2462
2462
  thumbs: zod.z.enum(["up", "down"]).optional()
2463
2463
  });
2464
+ var REPLIES_BY = ["model", "person"];
2464
2465
  var TurnInputSchema = zod.z.object({
2465
2466
  deploymentSlug: zod.z.string().min(1),
2466
2467
  sessionExternalId: zod.z.string().min(1),
@@ -2568,6 +2569,18 @@ var TurnInputSchema = zod.z.object({
2568
2569
  * `metadata` key so it has a durable landing place.
2569
2570
  */
2570
2571
  clientContext: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
2572
+ /**
2573
+ * Who writes the replies of this session: a model (the default) or a
2574
+ * person, as in a call between two people where one of them is the
2575
+ * agent. Session context like openedVia: the worker writes it on the
2576
+ * session at create (sessions.subject_type, 'agent' or 'human') and
2577
+ * ignores it afterwards. The session is created by whichever turn is
2578
+ * processed first, which need not be the first one sent, so send it on
2579
+ * every turn of the session (the import does). A session that
2580
+ * says a person replies carries no served model, and a judge run reads
2581
+ * that as a declaration, never as a model that went unrecorded.
2582
+ */
2583
+ repliesBy: zod.z.enum(REPLIES_BY).optional(),
2571
2584
  payload: zod.z.record(zod.z.string(), zod.z.unknown())
2572
2585
  });
2573
2586
  var SessionEndSchema2 = zod.z.object({
@@ -3773,6 +3786,7 @@ var FIELD_REFUSAL_CODES = [
3773
3786
  "runtime_forbidden",
3774
3787
  "invalid_reasoning_effort",
3775
3788
  "invalid_max_output_tokens",
3789
+ "invalid_reply_check",
3776
3790
  "conversation_ended",
3777
3791
  "no_live_version",
3778
3792
  "no_owner",