@cultured_computer/sight 0.9.0 → 0.10.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/CHANGELOG.md +23 -0
- package/README.md +2 -1
- package/dist/cli.js +584 -2
- package/dist/index.cjs +12 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +27 -27
- package/dist/index.d.ts +27 -27
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,29 @@ reconstructed from the repository: the `sdk-v*` release tags (dates are tag
|
|
|
5
5
|
dates) and the commits between them. Where the history does not say what a
|
|
6
6
|
version changed for SDK users, the entry says "see git history".
|
|
7
7
|
|
|
8
|
+
## Unreleased
|
|
9
|
+
|
|
10
|
+
- Nothing yet.
|
|
11
|
+
|
|
12
|
+
## 0.10.0 (2026-11-17)
|
|
13
|
+
|
|
14
|
+
- New CLI verb: `sight import <file> --deployment <slug> --batch <name>`
|
|
15
|
+
sends historical conversations from a JSONL file through the capture
|
|
16
|
+
route with their original times: one turn for each assistant message,
|
|
17
|
+
then a session end. Each turn's id is derived from the deployment, the
|
|
18
|
+
conversation id and the turn's position, so sending the same file again
|
|
19
|
+
adds nothing to the record (each accepted request is still counted). `--dry-run` checks the file and sends nothing; `--rate`
|
|
20
|
+
sets the requests per minute (1 to 600, default 120). The SDK's exports
|
|
21
|
+
and the request a capture sends are unchanged.
|
|
22
|
+
- `sight import` reads calls between two people: a conversation may say
|
|
23
|
+
`"replies_by": "person"` (or the command `--replies-by person` for the
|
|
24
|
+
whole file) when a person wrote the replies and no model took part. The
|
|
25
|
+
agent's lines carry the role `assistant`. Each of its turns is sent
|
|
26
|
+
with `repliesBy: "person"`, and the session records it. A conversation
|
|
27
|
+
that says a person replies and also names a model is refused. The
|
|
28
|
+
summary counts the conversations that name no model and do not say a
|
|
29
|
+
person replies: an evaluator run over those is refused.
|
|
30
|
+
|
|
8
31
|
## 0.9.0 (2026-10-16)
|
|
9
32
|
|
|
10
33
|
- New: the serving client. `createFieldClient({ apiKey, endpoint? })`
|
package/README.md
CHANGED
|
@@ -184,6 +184,7 @@ environment variables. Secrets are read from the environment, never from a flag.
|
|
|
184
184
|
| `sight auth logout` | Deletes the stored login token | None |
|
|
185
185
|
| `sight export --project <slug> --deployment <slug>` | Writes a deployment's record as JSONL (`--out <file>`, default stdout) | `auth login`; owner role on the project |
|
|
186
186
|
| `sight conditions --session <id>` | Prints one session's detector checks as NDJSON | A key with `studio:run`: `SIGHT_API_KEY`, or the key saved by `account create` |
|
|
187
|
+
| `sight import <file> --deployment <slug> --batch <name>` | Sends historical conversations from a JSONL file through the capture route with their original times; `--dry-run` checks the file and sends nothing; `--replies-by person` (or `"replies_by": "person"` on a conversation) sends a call between two people, where no model took part | A key with `ingest`: `SIGHT_API_KEY`, or the key saved by `account create` |
|
|
187
188
|
| `sight account create` | Redeems a one-time token and saves the key to `~/.config/sight/machine.json` (mode `0600`) | `SIGHT_PROVISION_TOKEN` |
|
|
188
189
|
| `sight openrouter connect --budget <usd> [--house-trial]` | Connects your OpenRouter key (`OPENROUTER_API_KEY`) to the project; `--house-trial` marks it as the operator's key for a demo | A key with `providers:write` |
|
|
189
190
|
| `sight openrouter status` | Prints the stored connection: status, last four characters, budget | A key with `studio:run` or `providers:write` |
|
|
@@ -382,7 +383,7 @@ code this version knows; a newer API may answer one it does not list.
|
|
|
382
383
|
| `archived`, `revoked`, `link_inactive` | `410` | It does not come back |
|
|
383
384
|
| `request_unknown`, `replay_expired` | `404`, `410` | Logical turn requests only; not sent by this client |
|
|
384
385
|
| `precondition_failed` | `412` | `ifMatch` no longer names the live version. Read the profile, then put. |
|
|
385
|
-
| `invalid_consent`, `invalid_safeguards`, `invalid_scrub`, `invalid_fallback`, `invalid_scene`, `invalid_reasoning_effort` | `422` | Fix that setting (on a put, or a start's `runtime`); `body.accepted` lists the words. Nothing was stored. |
|
|
386
|
+
| `invalid_consent`, `invalid_safeguards`, `invalid_scrub`, `invalid_fallback`, `invalid_scene`, `invalid_reasoning_effort`, `invalid_reply_check` | `422` | Fix that setting (on a put, or a start's `runtime`); `body.accepted` lists the words. Nothing was stored. |
|
|
386
387
|
| `invalid_max_output_tokens` | `422` | `maxOutputTokens` (on a put, or a start's `runtime`) is not an integer in the model's range; `body.accepted` is `{ min, max }`. Nothing was stored. |
|
|
387
388
|
| `daily_cap` | `429` | The day's conversations are used up (UTC) |
|
|
388
389
|
| `link_session_cap` | `429` | A rehearsal link's session limit; not sent by this client |
|
package/dist/cli.js
CHANGED
|
@@ -5,11 +5,375 @@ 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
|
+
};
|
|
213
|
+
for (const row of rows) {
|
|
214
|
+
if (!row.ok) {
|
|
215
|
+
plan.refused.push({ line: row.line, id: row.id, reason: row.reason });
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const { conversation } = row;
|
|
219
|
+
const shared = linesOf.get(conversation.id) ?? [];
|
|
220
|
+
if (shared.length > 1) {
|
|
221
|
+
plan.refused.push({
|
|
222
|
+
line: row.line,
|
|
223
|
+
id: conversation.id,
|
|
224
|
+
reason: `the id is on more than one line (lines ${shared.join(", ")}). Each conversation needs its own id.`
|
|
225
|
+
});
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
const repliesBy = repliesByOf(conversation, options);
|
|
229
|
+
if (repliesBy === "person" && conversation.model !== null) {
|
|
230
|
+
plan.refused.push({
|
|
231
|
+
line: row.line,
|
|
232
|
+
id: conversation.id,
|
|
233
|
+
reason: `the conversation says a person replies and also names a model (${JSON.stringify(conversation.model)}). Say one of the two.`
|
|
234
|
+
});
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const mapped = mapConversation(conversation, options);
|
|
238
|
+
if (mapped.turns.length === 0) {
|
|
239
|
+
plan.skipped.push({ line: row.line, id: conversation.id });
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
const requests = mapped.turns.map((turn) => ({
|
|
243
|
+
path: "/v1/turns",
|
|
244
|
+
body: JSON.stringify(turn),
|
|
245
|
+
conversationId: conversation.id,
|
|
246
|
+
turnIndex: turn.turnIndex
|
|
247
|
+
}));
|
|
248
|
+
const tooLarge = requests.find((request) => Buffer.byteLength(request.body, "utf8") > MAX_TURN_BODY_BYTES);
|
|
249
|
+
if (tooLarge) {
|
|
250
|
+
plan.refused.push({
|
|
251
|
+
line: row.line,
|
|
252
|
+
id: conversation.id,
|
|
253
|
+
reason: `turn ${tooLarge.turnIndex} is ${Buffer.byteLength(tooLarge.body, "utf8")} bytes as sent. One request holds at most ${MAX_TURN_BODY_BYTES} bytes.`
|
|
254
|
+
});
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
requests.push({
|
|
258
|
+
path: "/v1/sessions/end",
|
|
259
|
+
body: JSON.stringify(mapped.sessionEnd),
|
|
260
|
+
conversationId: conversation.id,
|
|
261
|
+
turnIndex: null
|
|
262
|
+
});
|
|
263
|
+
plan.conversations.push({ id: conversation.id, line: row.line, requests });
|
|
264
|
+
plan.turns += mapped.turns.length;
|
|
265
|
+
plan.systemMessages += mapped.systemMessages;
|
|
266
|
+
plan.toolMessages += mapped.toolMessages;
|
|
267
|
+
plan.unansweredUserMessages += mapped.unansweredUserMessages;
|
|
268
|
+
plan.invalidTimes += conversation.invalidTimes;
|
|
269
|
+
if (repliesBy === "person") plan.personReplies += 1;
|
|
270
|
+
else if (conversation.model === null) plan.modelNotSaid += 1;
|
|
271
|
+
}
|
|
272
|
+
return plan;
|
|
273
|
+
}
|
|
274
|
+
function requestCount(plan) {
|
|
275
|
+
return plan.turns + plan.conversations.length;
|
|
276
|
+
}
|
|
277
|
+
function estimatedMinutes(plan, rate) {
|
|
278
|
+
return Math.ceil(requestCount(plan) / rate);
|
|
279
|
+
}
|
|
280
|
+
function retryAfterMs(response) {
|
|
281
|
+
const raw = response.headers.get("retry-after");
|
|
282
|
+
if (raw === null || raw.trim() === "") return null;
|
|
283
|
+
const seconds = Number(raw);
|
|
284
|
+
if (!Number.isFinite(seconds)) return null;
|
|
285
|
+
return Math.min(Math.max(seconds, RETRY_AFTER_MIN_S), RETRY_AFTER_MAX_S) * 1e3;
|
|
286
|
+
}
|
|
287
|
+
function backoffMs(retry) {
|
|
288
|
+
return Math.min(BACKOFF_BASE_MS * 2 ** retry, BACKOFF_CAP_MS);
|
|
289
|
+
}
|
|
290
|
+
async function errorText(response) {
|
|
291
|
+
const text = await response.text().catch(() => "");
|
|
292
|
+
try {
|
|
293
|
+
const body = JSON.parse(text);
|
|
294
|
+
if (typeof body.error === "string") return body.error;
|
|
295
|
+
} catch {
|
|
296
|
+
}
|
|
297
|
+
return text.trim().slice(0, 300) || "no error text";
|
|
298
|
+
}
|
|
299
|
+
async function sendImport(plan, options, deps) {
|
|
300
|
+
const intervalMs = 6e4 / options.rate;
|
|
301
|
+
const progressEveryMs = options.progressEveryMs ?? PROGRESS_EVERY_MS;
|
|
302
|
+
const result = { conversationsSent: 0, turnsSent: 0, sessionEndsSent: 0, stopped: null };
|
|
303
|
+
const requestsTotal = requestCount(plan);
|
|
304
|
+
let requestsSent = 0;
|
|
305
|
+
let nextAt = deps.now();
|
|
306
|
+
let lastProgressAt = deps.now();
|
|
307
|
+
const paced = async (request) => {
|
|
308
|
+
const wait = nextAt - deps.now();
|
|
309
|
+
if (wait > 0) await deps.sleep(wait);
|
|
310
|
+
nextAt = Math.max(deps.now(), nextAt) + intervalMs;
|
|
311
|
+
try {
|
|
312
|
+
return await deps.fetch(`${options.api}${request.path}`, {
|
|
313
|
+
method: "POST",
|
|
314
|
+
redirect: "error",
|
|
315
|
+
headers: { Authorization: `Bearer ${options.apiKey}`, "content-type": "application/json" },
|
|
316
|
+
body: request.body,
|
|
317
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
318
|
+
});
|
|
319
|
+
} catch (error) {
|
|
320
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
const send = async (request) => {
|
|
324
|
+
for (let attempt = 0; ; attempt++) {
|
|
325
|
+
const answer = await paced(request);
|
|
326
|
+
if (answer instanceof Response && answer.ok) {
|
|
327
|
+
await answer.body?.cancel().catch(() => {
|
|
328
|
+
});
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
const retryable = !(answer instanceof Response) || answer.status === 429 || answer.status >= 500;
|
|
332
|
+
if (!retryable || attempt === MAX_RETRIES) {
|
|
333
|
+
return {
|
|
334
|
+
status: answer instanceof Response ? answer.status : null,
|
|
335
|
+
path: request.path,
|
|
336
|
+
conversationId: request.conversationId,
|
|
337
|
+
turnIndex: request.turnIndex,
|
|
338
|
+
detail: answer instanceof Response ? await errorText(answer) : answer.message,
|
|
339
|
+
attempts: attempt + 1
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
const wait = (answer instanceof Response ? retryAfterMs(answer) : null) ?? backoffMs(attempt);
|
|
343
|
+
if (answer instanceof Response) await answer.body?.cancel().catch(() => {
|
|
344
|
+
});
|
|
345
|
+
await deps.sleep(wait);
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
for (const conversation of plan.conversations) {
|
|
349
|
+
for (const request of conversation.requests) {
|
|
350
|
+
const stopped = await send(request);
|
|
351
|
+
if (stopped) return { ...result, stopped };
|
|
352
|
+
requestsSent += 1;
|
|
353
|
+
if (request.turnIndex === null) result.sessionEndsSent += 1;
|
|
354
|
+
else result.turnsSent += 1;
|
|
355
|
+
if (request.turnIndex === null) result.conversationsSent += 1;
|
|
356
|
+
if (options.onProgress && deps.now() - lastProgressAt >= progressEveryMs) {
|
|
357
|
+
lastProgressAt = deps.now();
|
|
358
|
+
options.onProgress({
|
|
359
|
+
requestsSent,
|
|
360
|
+
requestsTotal,
|
|
361
|
+
conversationsSent: result.conversationsSent,
|
|
362
|
+
conversationsTotal: plan.conversations.length
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return result;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// src/cli.ts
|
|
8
371
|
var DEFAULT_API = "https://api.cultured.computer";
|
|
9
372
|
function flag(args, name) {
|
|
10
373
|
const i = args.indexOf(name);
|
|
11
374
|
return i === -1 ? null : args[i + 1] ?? null;
|
|
12
375
|
}
|
|
376
|
+
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
377
|
function usage() {
|
|
14
378
|
console.log(
|
|
15
379
|
[
|
|
@@ -20,6 +384,7 @@ function usage() {
|
|
|
20
384
|
" sight auth logout",
|
|
21
385
|
" sight export --project <slug> --deployment <slug> [--readings|--conditions|--labels] [--out file.jsonl]",
|
|
22
386
|
" sight conditions --session <id-or-external-id> [--deployment <slug>] [--run <id>] [--since <iso>] [--until <iso>] [--base <dashboard-url>]",
|
|
387
|
+
` ${IMPORT_USAGE}`,
|
|
23
388
|
" sight account create [--openrouter --budget <usd>] [--api <base>]",
|
|
24
389
|
" sight openrouter connect --budget <usd> [--house-trial] [--api <base>]",
|
|
25
390
|
" sight openrouter status [--api <base>]",
|
|
@@ -30,16 +395,21 @@ function usage() {
|
|
|
30
395
|
" auth logout Delete the stored login token.",
|
|
31
396
|
" export Write a deployment's record (or --readings, --conditions, --labels) as JSONL. Needs auth login, owner role.",
|
|
32
397
|
" conditions Print a session's or a run's detector checks as NDJSON. Needs a key with studio:run.",
|
|
398
|
+
" import Send historical conversations from a JSONL file through the capture route, with their original times.",
|
|
399
|
+
" Sending the same file again adds nothing to the record. It is meant for a deployment that has no live traffic,",
|
|
400
|
+
" or for small files, because imported turns wait in the same queue as live ones. The hourly",
|
|
401
|
+
" aggregates cover the last seven days, so older conversations do not appear in them.",
|
|
402
|
+
" Needs a key with ingest. sight import --help describes the file.",
|
|
33
403
|
" account create Redeem SIGHT_PROVISION_TOKEN; save the key to ~/.config/sight/machine.json (0600).",
|
|
34
404
|
" openrouter connect Connect your OpenRouter key with a monthly USD budget. Needs a key with providers:write.",
|
|
35
405
|
" openrouter status Print the stored OpenRouter connection: status, last four characters, budget.",
|
|
36
406
|
" connect Connect a relay as a read-only observer, with a single-use invite code.",
|
|
37
407
|
"",
|
|
38
408
|
"Environment:",
|
|
39
|
-
" SIGHT_API_KEY Sight key for conditions and openrouter. Default: the key saved by account create.",
|
|
409
|
+
" SIGHT_API_KEY Sight key for conditions, import and openrouter. Default: the key saved by account create.",
|
|
40
410
|
" SIGHT_PROVISION_TOKEN One-time token redeemed by account create.",
|
|
41
411
|
" 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",
|
|
412
|
+
" SIGHT_API API base for account create, openrouter, connect, import. Default https://api.cultured.computer",
|
|
43
413
|
" SIGHT_BASE Dashboard base for auth login and conditions. Default https://sight.cultured.computer",
|
|
44
414
|
" SIGHT_NO_BROWSER 1 prints the auth login link without opening a browser (same as --no-browser).",
|
|
45
415
|
" XDG_CONFIG_HOME Directory for the stored login and key files. Default ~/.config",
|
|
@@ -419,6 +789,216 @@ async function conditions(args) {
|
|
|
419
789
|
process.stdout.write(await res.text());
|
|
420
790
|
return 0;
|
|
421
791
|
}
|
|
792
|
+
function importHelp() {
|
|
793
|
+
console.log(
|
|
794
|
+
[
|
|
795
|
+
"sight import: send historical conversations through the capture route.",
|
|
796
|
+
"",
|
|
797
|
+
"Usage:",
|
|
798
|
+
` ${IMPORT_USAGE}`,
|
|
799
|
+
"",
|
|
800
|
+
"It reads conversations from a file and sends each one through the capture route, the same route the SDK uses,",
|
|
801
|
+
"with their original times. Each assistant message becomes one turn; the turn carries the user messages that",
|
|
802
|
+
"came before it. When a conversation is sent, its session is ended.",
|
|
803
|
+
"",
|
|
804
|
+
"Sending the same file again adds nothing to the record: each turn has an id made from the deployment, the",
|
|
805
|
+
"conversation id and the turn's position, and a turn that arrives a second time is dropped. If an import stops,",
|
|
806
|
+
"run the same command again. Every request the capture route accepts is counted as an accepted turn, a repeat",
|
|
807
|
+
"included.",
|
|
808
|
+
"",
|
|
809
|
+
"It is meant for a deployment that has no live traffic, or for small files, because imported turns wait in the",
|
|
810
|
+
"same queue as live ones. The hourly aggregates cover the last seven days, so older conversations do not",
|
|
811
|
+
"appear in them.",
|
|
812
|
+
"",
|
|
813
|
+
"The file (format chat-jsonl) is JSONL, one conversation on each line:",
|
|
814
|
+
' { "id": "c-1", "messages": [{ "role": "user", "content": "Hello", "at": "2026-03-01T09:30:00Z" }, ...],',
|
|
815
|
+
' "model": "vendor/model", "user": "u-1" }',
|
|
816
|
+
" id Required. It becomes the session's external id. Each line needs its own.",
|
|
817
|
+
" messages Required. Each has a role (system, user, assistant or tool) and a content string.",
|
|
818
|
+
" System and tool messages are counted and not sent.",
|
|
819
|
+
" at Optional, on a message: an ISO 8601 time with a time zone. An assistant message's time becomes its",
|
|
820
|
+
" turn's time. Times must not go backwards within a conversation.",
|
|
821
|
+
" model Optional. vendor/model sets the provider and the model; a name with no slash sets the model.",
|
|
822
|
+
" user Optional. Your id for the person, stored as the session's user.",
|
|
823
|
+
' replies_by Optional: "model" or "person". Say "person" when the replies were written by a person and no',
|
|
824
|
+
" model took part, as in a call between two people. A conversation says a model or a person,",
|
|
825
|
+
" never both.",
|
|
826
|
+
"",
|
|
827
|
+
"A call between two people: give the agent's lines the role assistant and the other person's lines the role",
|
|
828
|
+
'user, and say "replies_by": "person" on the conversation, or pass --replies-by person for the whole file.',
|
|
829
|
+
"A conversation that names no model and does not say a person replies goes on the record, and an evaluator",
|
|
830
|
+
"run over it is refused until the file says one or the other. A session keeps what it was created with: to",
|
|
831
|
+
"change what a conversation says after it was sent, send it again under a new id.",
|
|
832
|
+
"",
|
|
833
|
+
"Flags:",
|
|
834
|
+
" --deployment <slug> Required. The deployment the conversations belong to.",
|
|
835
|
+
" --batch <name> Required. A name for this import, stored on every session it creates.",
|
|
836
|
+
" Letters, digits, dot, dash and underscore, 1 to 64 characters.",
|
|
837
|
+
` --format <name> The file format. Known formats: ${IMPORT_FORMATS.join(", ")}. Default ${IMPORT_FORMATS[0]}.`,
|
|
838
|
+
` --replies-by <who> Who replies in a conversation that does not say: ${REPLIES_BY.join(" or ")}. No default.`,
|
|
839
|
+
` --rate <n> Requests per minute, ${RATE_MIN} to ${RATE_MAX}. Default ${RATE_DEFAULT}.`,
|
|
840
|
+
" --dry-run Read and check the whole file, print the summary, send nothing.",
|
|
841
|
+
" --api <base> The API base. Default SIGHT_API, then the base saved by account create.",
|
|
842
|
+
"",
|
|
843
|
+
"A conversation with no assistant message is skipped. A line that cannot be sent as written is refused and",
|
|
844
|
+
"listed, and the rest of the file is sent; the command then exits 1. A request that answers 429 or 5xx is",
|
|
845
|
+
`sent again up to ${MAX_RETRIES} times. Any other refusal stops the import.`,
|
|
846
|
+
"",
|
|
847
|
+
"It needs a key with ingest: SIGHT_API_KEY, or the key saved by account create. A dry run needs no key."
|
|
848
|
+
].join("\n")
|
|
849
|
+
);
|
|
850
|
+
}
|
|
851
|
+
function importNotSent(plan) {
|
|
852
|
+
const lines = [];
|
|
853
|
+
lines.push(`skipped, no assistant message: ${plan.skipped.length}`);
|
|
854
|
+
for (const entry of plan.skipped.slice(0, LIST_LIMIT)) lines.push(` line ${entry.line}: ${entry.id}`);
|
|
855
|
+
if (plan.skipped.length > LIST_LIMIT) lines.push(` and ${plan.skipped.length - LIST_LIMIT} more`);
|
|
856
|
+
lines.push(`refused: ${plan.refused.length}`);
|
|
857
|
+
for (const entry of plan.refused.slice(0, LIST_LIMIT)) {
|
|
858
|
+
lines.push(` line ${entry.line}${entry.id === null ? "" : ` (${entry.id})`}: ${entry.reason}`);
|
|
859
|
+
}
|
|
860
|
+
if (plan.refused.length > LIST_LIMIT) lines.push(` and ${plan.refused.length - LIST_LIMIT} more`);
|
|
861
|
+
return lines;
|
|
862
|
+
}
|
|
863
|
+
async function importConversations(args) {
|
|
864
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
865
|
+
importHelp();
|
|
866
|
+
return 0;
|
|
867
|
+
}
|
|
868
|
+
const valueFlags = ["--deployment", "--batch", "--format", "--replies-by", "--rate", "--api"];
|
|
869
|
+
const files = [];
|
|
870
|
+
for (let i = 0; i < args.length; i++) {
|
|
871
|
+
const arg = args[i];
|
|
872
|
+
if (valueFlags.includes(arg)) {
|
|
873
|
+
const value = args[i + 1];
|
|
874
|
+
if (value === void 0 || value.startsWith("-")) {
|
|
875
|
+
console.error(`import: the flag ${arg} needs a value.
|
|
876
|
+
usage: ${IMPORT_USAGE}`);
|
|
877
|
+
return 1;
|
|
878
|
+
}
|
|
879
|
+
i++;
|
|
880
|
+
} else if (arg === "--dry-run") continue;
|
|
881
|
+
else if (arg.startsWith("-")) {
|
|
882
|
+
console.error(`import does not know the flag ${arg}.
|
|
883
|
+
usage: ${IMPORT_USAGE}`);
|
|
884
|
+
return 1;
|
|
885
|
+
} else files.push(arg);
|
|
886
|
+
}
|
|
887
|
+
const deployment = flag(args, "--deployment");
|
|
888
|
+
if (files.length !== 1 || !deployment) {
|
|
889
|
+
console.error(`usage: ${IMPORT_USAGE}
|
|
890
|
+
sight import --help describes the file and the flags.`);
|
|
891
|
+
return 1;
|
|
892
|
+
}
|
|
893
|
+
const format = parseFormat(flag(args, "--format"));
|
|
894
|
+
const batch = parseBatch(flag(args, "--batch"));
|
|
895
|
+
const rate = parseRate(flag(args, "--rate"));
|
|
896
|
+
const repliesBy = parseRepliesBy(flag(args, "--replies-by"));
|
|
897
|
+
for (const option of [format, batch, rate, repliesBy]) {
|
|
898
|
+
if (!option.ok) {
|
|
899
|
+
console.error(option.error);
|
|
900
|
+
return 1;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
if (!format.ok || !batch.ok || !rate.ok || !repliesBy.ok) return 1;
|
|
904
|
+
const dryRun = args.includes("--dry-run");
|
|
905
|
+
const stored = readMachineCredentials();
|
|
906
|
+
const sightKey = process.env["SIGHT_API_KEY"] ?? stored?.apiKey;
|
|
907
|
+
const api = (flag(args, "--api") ?? process.env["SIGHT_API"] ?? stored?.api ?? DEFAULT_API).replace(/\/+$/, "");
|
|
908
|
+
if (!dryRun && !sightKey) {
|
|
909
|
+
console.error("No Sight key found. Set SIGHT_API_KEY, or run sight account create.");
|
|
910
|
+
return 1;
|
|
911
|
+
}
|
|
912
|
+
const file = files[0];
|
|
913
|
+
let text;
|
|
914
|
+
try {
|
|
915
|
+
text = readFileSync(file, "utf8");
|
|
916
|
+
} catch (err) {
|
|
917
|
+
console.error(`could not read ${file}: ${err instanceof Error ? err.message : err}`);
|
|
918
|
+
return 1;
|
|
919
|
+
}
|
|
920
|
+
const plan = planImport(text, { deployment, batch: batch.value, format: format.value, repliesBy: repliesBy.value });
|
|
921
|
+
const notes = [];
|
|
922
|
+
if (plan.personReplies > 0) notes.push(`conversations in which a person replies: ${plan.personReplies}`);
|
|
923
|
+
if (plan.modelNotSaid > 0) {
|
|
924
|
+
notes.push(
|
|
925
|
+
`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".`
|
|
926
|
+
);
|
|
927
|
+
}
|
|
928
|
+
if (plan.unansweredUserMessages > 0) {
|
|
929
|
+
notes.push(`user messages after the last reply, not sent: ${plan.unansweredUserMessages}`);
|
|
930
|
+
}
|
|
931
|
+
if (plan.invalidTimes > 0) {
|
|
932
|
+
notes.push(
|
|
933
|
+
`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.`
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
const refusedCount = `${plan.refused.length} ${plan.refused.length === 1 ? "conversation was" : "conversations were"} refused`;
|
|
937
|
+
if (dryRun) {
|
|
938
|
+
const minutes = estimatedMinutes(plan, rate.value);
|
|
939
|
+
console.log(
|
|
940
|
+
[
|
|
941
|
+
"dry run: nothing was sent.",
|
|
942
|
+
`file: ${file} (format ${format.value}), deployment ${deployment}, batch ${batch.value}`,
|
|
943
|
+
`conversations to send: ${plan.conversations.length}`,
|
|
944
|
+
`turns to send: ${plan.turns}`,
|
|
945
|
+
...importNotSent(plan),
|
|
946
|
+
`system messages not sent: ${plan.systemMessages}`,
|
|
947
|
+
`tool messages not sent: ${plan.toolMessages}`,
|
|
948
|
+
...notes,
|
|
949
|
+
`estimated time: ${requestCount(plan) < rate.value ? "under a minute" : `about ${minutes} ${minutes === 1 ? "minute" : "minutes"}`} at ${rate.value} requests per minute (${requestCount(plan)} requests)`
|
|
950
|
+
].join("\n")
|
|
951
|
+
);
|
|
952
|
+
if (plan.refused.length > 0) {
|
|
953
|
+
console.error(`${refusedCount}. Correct the lines listed above; an import sends the rest of the file without them.`);
|
|
954
|
+
return 1;
|
|
955
|
+
}
|
|
956
|
+
return 0;
|
|
957
|
+
}
|
|
958
|
+
const result = await sendImport(
|
|
959
|
+
plan,
|
|
960
|
+
{
|
|
961
|
+
api,
|
|
962
|
+
apiKey: sightKey,
|
|
963
|
+
rate: rate.value,
|
|
964
|
+
onProgress: (progress) => {
|
|
965
|
+
console.error(
|
|
966
|
+
`sent ${progress.requestsSent} of ${progress.requestsTotal} requests (${progress.conversationsSent} of ${progress.conversationsTotal} conversations)`
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
},
|
|
970
|
+
{ fetch: (url, init) => fetch(url, init), now: () => Date.now(), sleep }
|
|
971
|
+
);
|
|
972
|
+
console.log(
|
|
973
|
+
[
|
|
974
|
+
result.stopped ? "import stopped before the end of the file." : "import finished.",
|
|
975
|
+
`conversations sent: ${result.conversationsSent}`,
|
|
976
|
+
`turns sent: ${result.turnsSent}`,
|
|
977
|
+
`session ends sent: ${result.sessionEndsSent}`,
|
|
978
|
+
...importNotSent(plan),
|
|
979
|
+
...notes
|
|
980
|
+
].join("\n")
|
|
981
|
+
);
|
|
982
|
+
if (result.stopped) {
|
|
983
|
+
const stop = result.stopped;
|
|
984
|
+
const what = stop.turnIndex === null ? "the session end" : `turn ${stop.turnIndex}`;
|
|
985
|
+
const answer = stop.status === null ? "got no answer" : `answered ${stop.status}`;
|
|
986
|
+
console.error(
|
|
987
|
+
[
|
|
988
|
+
`import stopped: POST ${stop.path} ${answer} for conversation ${stop.conversationId}, ${what}, after ${stop.attempts} ${stop.attempts === 1 ? "attempt" : "attempts"}: ${stop.detail}`,
|
|
989
|
+
"Nothing after it was sent. Running the same command again is safe: every turn keeps its id, so the turns already sent add nothing."
|
|
990
|
+
].join("\n")
|
|
991
|
+
);
|
|
992
|
+
return 1;
|
|
993
|
+
}
|
|
994
|
+
if (plan.refused.length > 0) {
|
|
995
|
+
console.error(
|
|
996
|
+
`${refusedCount} and not sent. Correct the lines listed above and run the command again: the conversations already sent add nothing.`
|
|
997
|
+
);
|
|
998
|
+
return 1;
|
|
999
|
+
}
|
|
1000
|
+
return 0;
|
|
1001
|
+
}
|
|
422
1002
|
var [, , command, ...rest] = process.argv;
|
|
423
1003
|
if (command === "connect") {
|
|
424
1004
|
connect(rest).then((code) => process.exit(code));
|
|
@@ -432,6 +1012,8 @@ if (command === "connect") {
|
|
|
432
1012
|
exportRecord(rest).then((code) => process.exit(code));
|
|
433
1013
|
} else if (command === "conditions") {
|
|
434
1014
|
conditions(rest).then((code) => process.exit(code));
|
|
1015
|
+
} else if (command === "import") {
|
|
1016
|
+
importConversations(rest).then((code) => process.exit(code));
|
|
435
1017
|
} else {
|
|
436
1018
|
usage();
|
|
437
1019
|
process.exit(command && command !== "--help" && command !== "-h" ? 1 : 0);
|