@himring/cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +54 -2
- package/dist/main.js +3744 -0
- package/package.json +46 -3
package/dist/main.js
ADDED
|
@@ -0,0 +1,3744 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/program.ts
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { DEFAULT_HIMRING_API_TIMEOUT_MS, DEFAULT_HIMRING_API_URL, describeError as describeError4 } from "@himring/sdk";
|
|
6
|
+
import { Command, CommanderError, InvalidArgumentError as InvalidArgumentError3, Option as Option11 } from "commander";
|
|
7
|
+
import * as v10 from "valibot";
|
|
8
|
+
|
|
9
|
+
// src/answer-log-commands.ts
|
|
10
|
+
import { HIMRING_OPERATION_CATALOGUE as HIMRING_OPERATION_CATALOGUE3 } from "@himring/sdk/catalogue";
|
|
11
|
+
import { Option as Option2 } from "commander";
|
|
12
|
+
import * as v2 from "valibot";
|
|
13
|
+
|
|
14
|
+
// src/command-context.ts
|
|
15
|
+
import { createHimringClient } from "@himring/sdk";
|
|
16
|
+
|
|
17
|
+
// src/credentials.ts
|
|
18
|
+
import { randomBytes } from "node:crypto";
|
|
19
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
20
|
+
import { homedir } from "node:os";
|
|
21
|
+
import { join } from "node:path";
|
|
22
|
+
import * as v from "valibot";
|
|
23
|
+
var OWNER_ONLY_FILE = 384;
|
|
24
|
+
var OWNER_ONLY_DIRECTORY = 448;
|
|
25
|
+
var TOKEN_MAXIMUM_LENGTH = 4096;
|
|
26
|
+
var tokenSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(TOKEN_MAXIMUM_LENGTH));
|
|
27
|
+
var apiCredentialsSchema = v.object({
|
|
28
|
+
sessionToken: v.optional(tokenSchema),
|
|
29
|
+
challengeToken: v.optional(tokenSchema),
|
|
30
|
+
knownDeviceTokens: v.optional(v.record(v.string(), tokenSchema), {})
|
|
31
|
+
});
|
|
32
|
+
var credentialsFileSchema = v.object({
|
|
33
|
+
version: v.literal(1),
|
|
34
|
+
apis: v.record(v.string(), apiCredentialsSchema)
|
|
35
|
+
});
|
|
36
|
+
var CredentialsFileError = class extends Error {
|
|
37
|
+
constructor(message, options = {}) {
|
|
38
|
+
super(message, { cause: options.cause });
|
|
39
|
+
this.name = "CredentialsFileError";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
function credentialsDirectory(environment) {
|
|
43
|
+
const explicit = environment.HIMRING_CONFIG_DIR;
|
|
44
|
+
if (explicit !== void 0 && explicit.length > 0) return explicit;
|
|
45
|
+
const xdg = environment.XDG_CONFIG_HOME;
|
|
46
|
+
return join(xdg !== void 0 && xdg.length > 0 ? xdg : join(homedir(), ".config"), "himring");
|
|
47
|
+
}
|
|
48
|
+
function credentialsPath(environment) {
|
|
49
|
+
return join(credentialsDirectory(environment), "credentials.json");
|
|
50
|
+
}
|
|
51
|
+
async function readCredentialsFile(path) {
|
|
52
|
+
let text;
|
|
53
|
+
try {
|
|
54
|
+
text = await readFile(path, "utf8");
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") return { version: 1, apis: {} };
|
|
57
|
+
throw new CredentialsFileError(`The CLI could not read ${path}. Check its permissions.`, { cause: error });
|
|
58
|
+
}
|
|
59
|
+
let parsed;
|
|
60
|
+
try {
|
|
61
|
+
parsed = JSON.parse(text);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
throw new CredentialsFileError(`${path} is not valid JSON. Delete it and sign in again.`, { cause: error });
|
|
64
|
+
}
|
|
65
|
+
const checked = v.safeParse(credentialsFileSchema, parsed);
|
|
66
|
+
if (!checked.success) throw new CredentialsFileError(`${path} has an unknown shape. Delete it and sign in again.`);
|
|
67
|
+
return checked.output;
|
|
68
|
+
}
|
|
69
|
+
function storedFor(file, apiUrl) {
|
|
70
|
+
return Object.hasOwn(file.apis, apiUrl) ? file.apis[apiUrl] ?? { knownDeviceTokens: {} } : { knownDeviceTokens: {} };
|
|
71
|
+
}
|
|
72
|
+
function createCredentialsStore(environment) {
|
|
73
|
+
const directory = credentialsDirectory(environment);
|
|
74
|
+
const path = credentialsPath(environment);
|
|
75
|
+
return {
|
|
76
|
+
path,
|
|
77
|
+
async read(apiUrl) {
|
|
78
|
+
return storedFor(await readCredentialsFile(path), apiUrl);
|
|
79
|
+
},
|
|
80
|
+
async update(apiUrl, change) {
|
|
81
|
+
const file = await readCredentialsFile(path);
|
|
82
|
+
const next = {
|
|
83
|
+
version: 1,
|
|
84
|
+
apis: { ...file.apis, [apiUrl]: change(storedFor(file, apiUrl)) }
|
|
85
|
+
};
|
|
86
|
+
const temporary = `${path}.${randomBytes(6).toString("hex")}.tmp`;
|
|
87
|
+
try {
|
|
88
|
+
await mkdir(directory, { recursive: true, mode: OWNER_ONLY_DIRECTORY });
|
|
89
|
+
await writeFile(temporary, `${JSON.stringify(next, null, 2)}
|
|
90
|
+
`, { mode: OWNER_ONLY_FILE, flag: "wx" });
|
|
91
|
+
await chmod(temporary, OWNER_ONLY_FILE);
|
|
92
|
+
await rename(temporary, path);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
await rm(temporary, { force: true });
|
|
95
|
+
throw new CredentialsFileError(`The CLI could not write ${path}. Check the permissions of ${directory}.`, {
|
|
96
|
+
cause: error
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// src/exit-codes.ts
|
|
104
|
+
import { isHimringApiError } from "@himring/sdk";
|
|
105
|
+
var EXIT_CODES = {
|
|
106
|
+
success: 0,
|
|
107
|
+
unexpected: 1,
|
|
108
|
+
usage: 2,
|
|
109
|
+
configuration: 3,
|
|
110
|
+
notFound: 4,
|
|
111
|
+
permissionDenied: 5,
|
|
112
|
+
conflict: 6,
|
|
113
|
+
rateLimited: 7,
|
|
114
|
+
network: 10,
|
|
115
|
+
notReady: 11,
|
|
116
|
+
serverError: 12,
|
|
117
|
+
partialFailure: 13
|
|
118
|
+
};
|
|
119
|
+
var EXIT_CODE_HELP = `
|
|
120
|
+
Exit codes:
|
|
121
|
+
0 The command succeeded.
|
|
122
|
+
1 The command failed for an unexpected reason.
|
|
123
|
+
2 The arguments, the input, or the environment were invalid.
|
|
124
|
+
3 The CLI could not read or write its credentials file.
|
|
125
|
+
4 The project, database, index, or other record does not exist.
|
|
126
|
+
5 The credential is missing, invalid, or not allowed to do this.
|
|
127
|
+
6 The change conflicts with the current state, such as a name in use.
|
|
128
|
+
7 The API limited the rate of requests. Wait, then try again.
|
|
129
|
+
10 The CLI could not reach the API, or the API did not respond in time.
|
|
130
|
+
11 The API responded, but a service behind it is not ready.
|
|
131
|
+
12 The API or a service behind it failed. Run the command again after 10 seconds.
|
|
132
|
+
13 Some files of the folder were sent and others failed. Run the upload again to send the rest.`;
|
|
133
|
+
var HTTP_UNAUTHORIZED = 401;
|
|
134
|
+
var HTTP_FORBIDDEN = 403;
|
|
135
|
+
var HTTP_NOT_FOUND = 404;
|
|
136
|
+
var HTTP_CONFLICT = 409;
|
|
137
|
+
var HTTP_GONE = 410;
|
|
138
|
+
var HTTP_TOO_MANY_REQUESTS = 429;
|
|
139
|
+
var HTTP_SERVER_ERROR = 500;
|
|
140
|
+
function exitCodeForStatus(status) {
|
|
141
|
+
if (status === void 0) return EXIT_CODES.unexpected;
|
|
142
|
+
if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) return EXIT_CODES.permissionDenied;
|
|
143
|
+
if (status === HTTP_NOT_FOUND) return EXIT_CODES.notFound;
|
|
144
|
+
if (status === HTTP_CONFLICT || status === HTTP_GONE) return EXIT_CODES.conflict;
|
|
145
|
+
if (status === HTTP_TOO_MANY_REQUESTS) return EXIT_CODES.rateLimited;
|
|
146
|
+
if (status >= HTTP_SERVER_ERROR) return EXIT_CODES.serverError;
|
|
147
|
+
return EXIT_CODES.usage;
|
|
148
|
+
}
|
|
149
|
+
function exitCodeForApiError(error) {
|
|
150
|
+
switch (error.kind) {
|
|
151
|
+
case "network":
|
|
152
|
+
case "timeout":
|
|
153
|
+
return EXIT_CODES.network;
|
|
154
|
+
case "invalid_input":
|
|
155
|
+
return EXIT_CODES.usage;
|
|
156
|
+
case "invalid_response":
|
|
157
|
+
return EXIT_CODES.unexpected;
|
|
158
|
+
case "refused":
|
|
159
|
+
return exitCodeForStatus(error.status);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function exitCodeForError(error) {
|
|
163
|
+
return isHimringApiError(error) ? exitCodeForApiError(error) : EXIT_CODES.unexpected;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/option-values.ts
|
|
167
|
+
var HTTP_URL_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:"]);
|
|
168
|
+
var WHOLE_NUMBER_TEXT = /^\d+$/;
|
|
169
|
+
function httpUrlOf(text) {
|
|
170
|
+
const trimmed = text.trim();
|
|
171
|
+
if (!URL.canParse(trimmed)) return void 0;
|
|
172
|
+
const url = new URL(trimmed);
|
|
173
|
+
if (!HTTP_URL_SCHEMES.has(url.protocol)) return void 0;
|
|
174
|
+
if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") return void 0;
|
|
175
|
+
return trimmed;
|
|
176
|
+
}
|
|
177
|
+
function wholeNumberInRangeOf(text, smallest, largest) {
|
|
178
|
+
const trimmed = text.trim();
|
|
179
|
+
if (!WHOLE_NUMBER_TEXT.test(trimmed)) return void 0;
|
|
180
|
+
const value = Number(trimmed);
|
|
181
|
+
return Number.isSafeInteger(value) && value >= smallest && value <= largest ? value : void 0;
|
|
182
|
+
}
|
|
183
|
+
function nonEmptyText(value) {
|
|
184
|
+
return value !== void 0 && value.length > 0 ? value : void 0;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// src/output.ts
|
|
188
|
+
import { describeError, isHimringApiError as isHimringApiError2 } from "@himring/sdk";
|
|
189
|
+
|
|
190
|
+
// src/text-cells.ts
|
|
191
|
+
var ACRONYMS = /* @__PURE__ */ new Map([
|
|
192
|
+
["id", "ID"],
|
|
193
|
+
["ids", "IDs"],
|
|
194
|
+
["url", "URL"],
|
|
195
|
+
["uri", "URI"],
|
|
196
|
+
["api", "API"],
|
|
197
|
+
["totp", "TOTP"],
|
|
198
|
+
["sql", "SQL"]
|
|
199
|
+
]);
|
|
200
|
+
var LABEL_OVERRIDES = /* @__PURE__ */ new Map([
|
|
201
|
+
["is_operator", "Operator"],
|
|
202
|
+
["duration_ms", "Search time (ms)"],
|
|
203
|
+
["match", "Matched part"],
|
|
204
|
+
["match_citation", "Matched part"]
|
|
205
|
+
]);
|
|
206
|
+
var WIDE_CHARACTER = new RegExp("\\p{Emoji_Presentation}|\\u{FE0F}|[\\u{1100}-\\u{115F}\\u{2E80}-\\u{303E}\\u{3041}-\\u{33FF}\\u{3400}-\\u{4DBF}\\u{4E00}-\\u{9FFF}\\u{A000}-\\u{A4CF}\\u{AC00}-\\u{D7A3}\\u{F900}-\\u{FAFF}\\u{FE30}-\\u{FE4F}\\u{FF00}-\\u{FF60}\\u{FFE0}-\\u{FFE6}\\u{20000}-\\u{3FFFD}]", "u");
|
|
207
|
+
var ZERO_WIDTH_GRAPHEME = new RegExp("^\\p{Default_Ignorable_Code_Point}+$", "u");
|
|
208
|
+
var graphemes = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
209
|
+
function isRecord(value) {
|
|
210
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
211
|
+
}
|
|
212
|
+
function isScalar(value) {
|
|
213
|
+
return value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
214
|
+
}
|
|
215
|
+
function wordsOf(key) {
|
|
216
|
+
return key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s_-]+/).filter((word) => word.length > 0).map((word) => ACRONYMS.get(word.toLowerCase()) ?? word.toLowerCase());
|
|
217
|
+
}
|
|
218
|
+
function nounOf(key) {
|
|
219
|
+
const words = wordsOf(key);
|
|
220
|
+
return words.length === 0 ? "items" : printable(words.join(" "), false);
|
|
221
|
+
}
|
|
222
|
+
function labelOf(key) {
|
|
223
|
+
const override = LABEL_OVERRIDES.get(key);
|
|
224
|
+
if (override !== void 0) return override;
|
|
225
|
+
const words = wordsOf(key);
|
|
226
|
+
if (words.length === 0) return printable(key, false);
|
|
227
|
+
const sentence = words.join(" ");
|
|
228
|
+
return printable(`${sentence.charAt(0).toUpperCase()}${sentence.slice(1)}`, false);
|
|
229
|
+
}
|
|
230
|
+
function isHiddenFromTerminal(codePoint) {
|
|
231
|
+
return codePoint < 32 || codePoint >= 127 && codePoint < 160 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297;
|
|
232
|
+
}
|
|
233
|
+
function printable(text, keepLineBreaks) {
|
|
234
|
+
const source = keepLineBreaks ? text.replace(/\r\n/g, "\n") : text;
|
|
235
|
+
let result = "";
|
|
236
|
+
for (const character of source) {
|
|
237
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
238
|
+
if (keepLineBreaks && (character === "\n" || character === " ")) result += character;
|
|
239
|
+
else if (isHiddenFromTerminal(codePoint)) result += `\\u${codePoint.toString(16).padStart(4, "0")}`;
|
|
240
|
+
else result += character;
|
|
241
|
+
}
|
|
242
|
+
return result;
|
|
243
|
+
}
|
|
244
|
+
function scalarText(value, keepLineBreaks) {
|
|
245
|
+
if (value === null || value === void 0) return "-";
|
|
246
|
+
if (typeof value === "boolean") return value ? "yes" : "no";
|
|
247
|
+
if (typeof value === "number") return String(value);
|
|
248
|
+
if (value.length === 0) return '""';
|
|
249
|
+
return printable(value, keepLineBreaks);
|
|
250
|
+
}
|
|
251
|
+
function cellText(value) {
|
|
252
|
+
if (isScalar(value)) return scalarText(value, false);
|
|
253
|
+
return printable(JSON.stringify(value), false);
|
|
254
|
+
}
|
|
255
|
+
function displayWidth(text) {
|
|
256
|
+
let width = 0;
|
|
257
|
+
for (const { segment } of graphemes.segment(text)) {
|
|
258
|
+
if (ZERO_WIDTH_GRAPHEME.test(segment)) continue;
|
|
259
|
+
width += WIDE_CHARACTER.test(segment) ? 2 : 1;
|
|
260
|
+
}
|
|
261
|
+
return width;
|
|
262
|
+
}
|
|
263
|
+
function padEnd(text, width) {
|
|
264
|
+
return `${text}${" ".repeat(Math.max(0, width - displayWidth(text)))}`;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/text-output.ts
|
|
268
|
+
import { citationText } from "@himring/sdk";
|
|
269
|
+
|
|
270
|
+
// src/spec-shapes.ts
|
|
271
|
+
import { HIMRING_OPERATION_CATALOGUE as HIMRING_OPERATION_CATALOGUE2 } from "@himring/sdk/catalogue";
|
|
272
|
+
|
|
273
|
+
// src/spec-schemas.ts
|
|
274
|
+
import { HimringApiError } from "@himring/sdk";
|
|
275
|
+
import { HIMRING_OPERATION_CATALOGUE } from "@himring/sdk/catalogue";
|
|
276
|
+
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
277
|
+
|
|
278
|
+
// src/spec-rules.ts
|
|
279
|
+
var RULES_KEYWORD = "x-himring-rules";
|
|
280
|
+
var BOUND_PATTERN = /^(>=|<=)(-?\d+(?:\.\d+)?)$/;
|
|
281
|
+
var NUMERIC_TEXT = /^-?\d+(?:\.\d+)?$/;
|
|
282
|
+
var QUOTED_CHOICE = /"((?:[^"\\]|\\.)*)"/g;
|
|
283
|
+
var LIST_SEPARATOR = ",";
|
|
284
|
+
function isRecord2(value) {
|
|
285
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
286
|
+
}
|
|
287
|
+
function specRulesOf(schema) {
|
|
288
|
+
if (!isRecord2(schema)) return [];
|
|
289
|
+
const rules = schema[RULES_KEYWORD];
|
|
290
|
+
if (!Array.isArray(rules)) return [];
|
|
291
|
+
return rules.flatMap((rule) => {
|
|
292
|
+
if (!isRecord2(rule) || typeof rule.kind !== "string") return [];
|
|
293
|
+
return [
|
|
294
|
+
{
|
|
295
|
+
kind: rule.kind,
|
|
296
|
+
expects: typeof rule.expects === "string" ? rule.expects : null,
|
|
297
|
+
message: typeof rule.message === "string" ? rule.message : void 0
|
|
298
|
+
}
|
|
299
|
+
];
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
function picklistChoicesOf(rule) {
|
|
303
|
+
if (rule.kind !== "picklist" || rule.expects === null) return [];
|
|
304
|
+
return [...rule.expects.matchAll(QUOTED_CHOICE)].flatMap((match) => match[1] === void 0 ? [] : [match[1]]);
|
|
305
|
+
}
|
|
306
|
+
function isListRules(rules) {
|
|
307
|
+
return rules.some((rule) => rule.kind === "array");
|
|
308
|
+
}
|
|
309
|
+
function boundOf(rule) {
|
|
310
|
+
const found = rule.expects === null ? null : BOUND_PATTERN.exec(rule.expects);
|
|
311
|
+
const digits = found?.[2];
|
|
312
|
+
return digits === void 0 ? void 0 : Number(digits);
|
|
313
|
+
}
|
|
314
|
+
function numberOf(data) {
|
|
315
|
+
if (typeof data === "number") return data;
|
|
316
|
+
if (typeof data === "string" && NUMERIC_TEXT.test(data)) return Number(data);
|
|
317
|
+
return void 0;
|
|
318
|
+
}
|
|
319
|
+
function lengthOf(data) {
|
|
320
|
+
if (typeof data === "string" || Array.isArray(data)) return data.length;
|
|
321
|
+
return void 0;
|
|
322
|
+
}
|
|
323
|
+
function listItemsOf(text) {
|
|
324
|
+
return text.split(LIST_SEPARATOR).map((item) => item.trim()).filter((item) => item.length > 0);
|
|
325
|
+
}
|
|
326
|
+
function messageOf(rule, fallback) {
|
|
327
|
+
return rule.message ?? fallback;
|
|
328
|
+
}
|
|
329
|
+
function boundFailure(rule, value, atLeast) {
|
|
330
|
+
const bound = boundOf(rule);
|
|
331
|
+
if (bound === void 0 || value === void 0) return void 0;
|
|
332
|
+
const breaks = atLeast ? value < bound : value > bound;
|
|
333
|
+
return breaks ? messageOf(rule, `must be ${atLeast ? "at least" : "at most"} ${bound}`) : void 0;
|
|
334
|
+
}
|
|
335
|
+
function picklistFailure(rule, data, listed) {
|
|
336
|
+
if (typeof data !== "string") return void 0;
|
|
337
|
+
const choices = picklistChoicesOf(rule);
|
|
338
|
+
if (choices.length === 0) return void 0;
|
|
339
|
+
const values = listed ? listItemsOf(data) : [data];
|
|
340
|
+
const unknown = values.find((value) => !choices.includes(value));
|
|
341
|
+
return unknown === void 0 ? void 0 : messageOf(rule, `must be one of ${choices.join(", ")}`);
|
|
342
|
+
}
|
|
343
|
+
function ruleFailure(rule, data, listed) {
|
|
344
|
+
switch (rule.kind) {
|
|
345
|
+
case "number":
|
|
346
|
+
if (typeof data !== "string") return void 0;
|
|
347
|
+
return numberOf(data.trim()) === void 0 ? messageOf(rule, "must be a number") : void 0;
|
|
348
|
+
case "min_value":
|
|
349
|
+
return boundFailure(rule, numberOf(data), true);
|
|
350
|
+
case "max_value":
|
|
351
|
+
return boundFailure(rule, numberOf(data), false);
|
|
352
|
+
case "min_length":
|
|
353
|
+
return listed ? void 0 : boundFailure(rule, lengthOf(data), true);
|
|
354
|
+
case "max_length":
|
|
355
|
+
return listed ? void 0 : boundFailure(rule, lengthOf(data), false);
|
|
356
|
+
case "picklist":
|
|
357
|
+
return picklistFailure(rule, data, listed);
|
|
358
|
+
default:
|
|
359
|
+
return void 0;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function ruleFailuresOf(rulesValue, data) {
|
|
363
|
+
const rules = specRulesOf({ [RULES_KEYWORD]: rulesValue });
|
|
364
|
+
const listed = isListRules(rules);
|
|
365
|
+
return rules.flatMap((rule) => {
|
|
366
|
+
const failure = ruleFailure(rule, data, listed);
|
|
367
|
+
return failure === void 0 ? [] : [failure];
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// src/usage-error.ts
|
|
372
|
+
var UsageError = class extends Error {
|
|
373
|
+
suggestion;
|
|
374
|
+
constructor(message, suggestion) {
|
|
375
|
+
super(message);
|
|
376
|
+
this.name = "UsageError";
|
|
377
|
+
this.suggestion = suggestion;
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
|
|
381
|
+
// src/spec-schemas.ts
|
|
382
|
+
var checkRules = (rules, data) => {
|
|
383
|
+
const failures = ruleFailuresOf(rules, data);
|
|
384
|
+
checkRules.errors = failures.map((message) => ({ keyword: RULES_KEYWORD, message, params: {} }));
|
|
385
|
+
return failures.length === 0;
|
|
386
|
+
};
|
|
387
|
+
var ajv = new Ajv2020({ strict: false, allErrors: true, verbose: true, validateFormats: false });
|
|
388
|
+
ajv.addKeyword({ keyword: RULES_KEYWORD, schemaType: "array", errors: true, validate: checkRules });
|
|
389
|
+
var RULE_KINDS_OF_KEYWORD = {
|
|
390
|
+
maxLength: ["max_length"],
|
|
391
|
+
minLength: ["min_length"],
|
|
392
|
+
maxItems: ["max_length"],
|
|
393
|
+
minItems: ["min_length"],
|
|
394
|
+
maximum: ["max_value"],
|
|
395
|
+
minimum: ["min_value"],
|
|
396
|
+
pattern: ["number", "regex"],
|
|
397
|
+
enum: ["picklist"]
|
|
398
|
+
};
|
|
399
|
+
var COMBINING_KEYWORDS = /* @__PURE__ */ new Set(["anyOf", "oneOf", "if"]);
|
|
400
|
+
var SENTENCE_END = /[.!?]$/;
|
|
401
|
+
function isRecord3(value) {
|
|
402
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
403
|
+
}
|
|
404
|
+
function inputSchemaOf(id) {
|
|
405
|
+
return HIMRING_OPERATION_CATALOGUE[id].inputSchema;
|
|
406
|
+
}
|
|
407
|
+
function inputPropertiesOf(id) {
|
|
408
|
+
const properties = inputSchemaOf(id).properties;
|
|
409
|
+
if (!isRecord3(properties)) return {};
|
|
410
|
+
return Object.fromEntries(
|
|
411
|
+
Object.entries(properties).filter((entry) => isRecord3(entry[1]))
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
function requiredInputsOf(id) {
|
|
415
|
+
const required2 = inputSchemaOf(id).required;
|
|
416
|
+
return new Set(Array.isArray(required2) ? required2.filter((name) => typeof name === "string") : []);
|
|
417
|
+
}
|
|
418
|
+
function propertySchemaOf(id, name) {
|
|
419
|
+
const schema = inputPropertiesOf(id)[name];
|
|
420
|
+
if (schema === void 0) throw new Error(`The spec of ${id} has no field called ${name}.`);
|
|
421
|
+
return schema;
|
|
422
|
+
}
|
|
423
|
+
var validators = /* @__PURE__ */ new Map();
|
|
424
|
+
function validatorOf(key, schema) {
|
|
425
|
+
const known = validators.get(key);
|
|
426
|
+
if (known !== void 0) return known;
|
|
427
|
+
const compiled = ajv.compile(schema());
|
|
428
|
+
validators.set(key, compiled);
|
|
429
|
+
return compiled;
|
|
430
|
+
}
|
|
431
|
+
function compiledGuard(schema) {
|
|
432
|
+
const validate = ajv.compile(schema);
|
|
433
|
+
return (value) => validate(value);
|
|
434
|
+
}
|
|
435
|
+
function fieldPathOf(instancePath) {
|
|
436
|
+
return instancePath.split("/").filter((part) => part.length > 0).map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~")).join(".");
|
|
437
|
+
}
|
|
438
|
+
function textParameter(error, name) {
|
|
439
|
+
const value = Reflect.get(error.params, name);
|
|
440
|
+
return typeof value === "string" ? value : void 0;
|
|
441
|
+
}
|
|
442
|
+
function plainMessageOf(error) {
|
|
443
|
+
const missing = textParameter(error, "missingProperty");
|
|
444
|
+
if (error.keyword === "required" && missing !== void 0) return `${missing} is missing`;
|
|
445
|
+
const extra = textParameter(error, "additionalProperty");
|
|
446
|
+
if (error.keyword === "additionalProperties" && extra !== void 0) {
|
|
447
|
+
return `${extra} is not a field that this operation takes`;
|
|
448
|
+
}
|
|
449
|
+
const allowed = Reflect.get(error.params, "allowedValues");
|
|
450
|
+
if (error.keyword === "enum" && Array.isArray(allowed)) return `must be one of ${allowed.map(String).join(", ")}`;
|
|
451
|
+
return error.message ?? "is invalid";
|
|
452
|
+
}
|
|
453
|
+
function specMessageOf(error) {
|
|
454
|
+
if (error.keyword === RULES_KEYWORD) return error.message;
|
|
455
|
+
const kinds = RULE_KINDS_OF_KEYWORD[error.keyword];
|
|
456
|
+
if (kinds === void 0) return void 0;
|
|
457
|
+
return specRulesOf(error.parentSchema).find((rule) => kinds.includes(rule.kind) && rule.message !== void 0)?.message;
|
|
458
|
+
}
|
|
459
|
+
function unique(values) {
|
|
460
|
+
return [...new Set(values)];
|
|
461
|
+
}
|
|
462
|
+
function sentenceOf(text) {
|
|
463
|
+
return SENTENCE_END.test(text) ? text : `${text}.`;
|
|
464
|
+
}
|
|
465
|
+
function issuesTextOf(errors) {
|
|
466
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
467
|
+
for (const error of errors) {
|
|
468
|
+
const path = fieldPathOf(error.instancePath);
|
|
469
|
+
byPath.set(path, [...byPath.get(path) ?? [], error]);
|
|
470
|
+
}
|
|
471
|
+
const sentences = [...byPath.entries()].map(([path, found]) => {
|
|
472
|
+
const spec = unique(found.flatMap((error) => specMessageOf(error) ?? []));
|
|
473
|
+
const plain = unique(found.filter((error) => !COMBINING_KEYWORDS.has(error.keyword)).map(plainMessageOf));
|
|
474
|
+
const chosen = spec.length > 0 ? spec : plain.length > 0 ? plain : unique(found.map(plainMessageOf));
|
|
475
|
+
const text = chosen.map(sentenceOf).join(" ");
|
|
476
|
+
return path.length === 0 ? text : `${path}: ${text}`;
|
|
477
|
+
});
|
|
478
|
+
return sentences.join(" ");
|
|
479
|
+
}
|
|
480
|
+
function pickedSchemaOf(id, fields) {
|
|
481
|
+
const properties = inputPropertiesOf(id);
|
|
482
|
+
const required2 = requiredInputsOf(id);
|
|
483
|
+
return {
|
|
484
|
+
type: "object",
|
|
485
|
+
properties: Object.fromEntries(
|
|
486
|
+
fields.flatMap((name) => properties[name] === void 0 ? [] : [[name, properties[name]]])
|
|
487
|
+
),
|
|
488
|
+
required: fields.filter((name) => required2.has(name)),
|
|
489
|
+
additionalProperties: false
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
function checkInput(id, input, suggestion, fields) {
|
|
493
|
+
const validate = fields === void 0 ? validatorOf(`input:${id}`, () => inputSchemaOf(id)) : validatorOf(`input:${id}:${fields.join(",")}`, () => pickedSchemaOf(id, fields));
|
|
494
|
+
if (validate(input)) return;
|
|
495
|
+
throw new UsageError(`The input is invalid: ${issuesTextOf(validate.errors ?? [])}`, suggestion);
|
|
496
|
+
}
|
|
497
|
+
function checkOutput(id, output) {
|
|
498
|
+
const schema = HIMRING_OPERATION_CATALOGUE[id].outputSchema;
|
|
499
|
+
if (schema === null) return;
|
|
500
|
+
const validate = validatorOf(`output:${id}`, () => schema);
|
|
501
|
+
if (validate(output)) return;
|
|
502
|
+
throw new HimringApiError(
|
|
503
|
+
"invalid_response",
|
|
504
|
+
`The API answered ${id} with data that its documented schema does not allow.`,
|
|
505
|
+
{
|
|
506
|
+
details: issuesTextOf(validate.errors ?? [])
|
|
507
|
+
}
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// src/spec-shapes.ts
|
|
512
|
+
var KEY_ACCESS_FIELD = "access";
|
|
513
|
+
function isSchema(value) {
|
|
514
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
515
|
+
}
|
|
516
|
+
function outputSchemaAt(id, keys) {
|
|
517
|
+
let current = HIMRING_OPERATION_CATALOGUE2[id].outputSchema;
|
|
518
|
+
for (const key of keys) current = isSchema(current) ? current[key] : void 0;
|
|
519
|
+
if (!isSchema(current)) throw new Error(`The spec of ${id} has no output schema at ${keys.join(".")}.`);
|
|
520
|
+
return current;
|
|
521
|
+
}
|
|
522
|
+
function lazyGuard(schema) {
|
|
523
|
+
let guard;
|
|
524
|
+
return (value) => {
|
|
525
|
+
guard ??= compiledGuard(schema());
|
|
526
|
+
return guard(value);
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
var PASSAGE_FIELDS = ["properties", "passages", "items", "properties"];
|
|
530
|
+
var KEY_PERMISSIONS_FIELDS = ["properties", "api_keys", "items", "properties", "permissions"];
|
|
531
|
+
var isCitation = lazyGuard(
|
|
532
|
+
() => outputSchemaAt("search_knowledge_base", [...PASSAGE_FIELDS, "citation"])
|
|
533
|
+
);
|
|
534
|
+
var isPassageMatch = lazyGuard(
|
|
535
|
+
() => outputSchemaAt("search_knowledge_base", [...PASSAGE_FIELDS, "match"])
|
|
536
|
+
);
|
|
537
|
+
var isUnreadParts = lazyGuard(
|
|
538
|
+
() => outputSchemaAt("list_files", ["properties", "files", "items", "properties", "unread_parts"])
|
|
539
|
+
);
|
|
540
|
+
var isKeyPermissions = lazyGuard(() => outputSchemaAt("list_api_keys", KEY_PERMISSIONS_FIELDS));
|
|
541
|
+
function keyResourceKinds() {
|
|
542
|
+
const properties = outputSchemaAt("list_api_keys", [...KEY_PERMISSIONS_FIELDS, "properties"]);
|
|
543
|
+
return Object.keys(properties).filter((kind) => kind !== KEY_ACCESS_FIELD);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// src/key-permissions-text.ts
|
|
547
|
+
var KEY_PERMISSION_FIELDS = /* @__PURE__ */ new Set([
|
|
548
|
+
"permissions",
|
|
549
|
+
"permissions_before",
|
|
550
|
+
"permissions_after"
|
|
551
|
+
]);
|
|
552
|
+
var FULL_ACCESS = "full";
|
|
553
|
+
var NO_ACCESS_LEVEL = "none";
|
|
554
|
+
var FULL_ACCESS_TEXT = "full access";
|
|
555
|
+
var NO_PERMISSIONS_TEXT = "-";
|
|
556
|
+
function grantText(kind, grant) {
|
|
557
|
+
if (!isRecord(grant) || typeof grant.level !== "string" || grant.level === NO_ACCESS_LEVEL) return [];
|
|
558
|
+
const listed = Array.isArray(grant.resource_ids) ? ` (${grant.resource_ids.length} listed)` : "";
|
|
559
|
+
return [`${kind} ${grant.level}${listed}`];
|
|
560
|
+
}
|
|
561
|
+
function keyPermissionsText(value) {
|
|
562
|
+
if (value === null) return NO_PERMISSIONS_TEXT;
|
|
563
|
+
if (!isKeyPermissions(value)) return void 0;
|
|
564
|
+
if (value.access === FULL_ACCESS) return FULL_ACCESS_TEXT;
|
|
565
|
+
const grants = keyResourceKinds().flatMap((kind) => grantText(kind, Reflect.get(value, kind)));
|
|
566
|
+
return grants.length === 0 ? NO_PERMISSIONS_TEXT : grants.join(", ");
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// src/unread-parts-text.ts
|
|
570
|
+
import { formatClock } from "@himring/sdk";
|
|
571
|
+
var UNREAD_PARTS_FIELD = "unread_parts";
|
|
572
|
+
var EVERY_PART_READ = "-";
|
|
573
|
+
function stretchOf(part) {
|
|
574
|
+
if (part.first_page !== null && part.last_page !== null) {
|
|
575
|
+
return part.first_page === part.last_page ? `page ${part.first_page}` : `pages ${part.first_page}-${part.last_page}`;
|
|
576
|
+
}
|
|
577
|
+
if (part.start_second !== null && part.end_second !== null) {
|
|
578
|
+
return `${formatClock(part.start_second)}-${formatClock(part.end_second)}`;
|
|
579
|
+
}
|
|
580
|
+
return "whole file";
|
|
581
|
+
}
|
|
582
|
+
function unreadPartsText(value) {
|
|
583
|
+
if (!isUnreadParts(value)) return void 0;
|
|
584
|
+
if (value.length === 0) return EVERY_PART_READ;
|
|
585
|
+
return value.map(stretchOf).join(", ");
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// src/text-table.ts
|
|
589
|
+
var COLUMN_GAP = " ";
|
|
590
|
+
var COLUMN_PREFERENCES = {
|
|
591
|
+
projects: ["id", "name", "role", "region", "created_at", "deleted_at", "purge_after"],
|
|
592
|
+
members: ["account_id", "name", "email", "role", "added_at"],
|
|
593
|
+
invitations: ["id", "email", "role", "created_at", "expires_at", "accepted_at", "revoked_at"],
|
|
594
|
+
api_keys: [
|
|
595
|
+
"id",
|
|
596
|
+
"name",
|
|
597
|
+
"display_prefix",
|
|
598
|
+
"permissions",
|
|
599
|
+
"created_by_name",
|
|
600
|
+
"created_at",
|
|
601
|
+
"expires_at",
|
|
602
|
+
"last_used_at",
|
|
603
|
+
"revoked_at"
|
|
604
|
+
],
|
|
605
|
+
changes: ["changed_at", "changed_by_name", "permissions_before", "permissions_after"],
|
|
606
|
+
databases: ["id", "name", "migration_version", "created_at", "deleted_at", "purge_after"],
|
|
607
|
+
migrations: ["version", "name", "added_at"],
|
|
608
|
+
indexes: ["id", "name", "created_at", "deleted_at", "purge_after"],
|
|
609
|
+
operations: ["id", "method", "path", "access"],
|
|
610
|
+
knowledge_bases: ["id", "name", "language", "chunk_tokens", "created_at", "deleted_at", "purge_after"],
|
|
611
|
+
files: [
|
|
612
|
+
"id",
|
|
613
|
+
"path",
|
|
614
|
+
"kind",
|
|
615
|
+
"status",
|
|
616
|
+
UNREAD_PARTS_FIELD,
|
|
617
|
+
"current_version",
|
|
618
|
+
"size_bytes",
|
|
619
|
+
"updated_at",
|
|
620
|
+
"deleted_at",
|
|
621
|
+
"purge_after"
|
|
622
|
+
],
|
|
623
|
+
versions: [
|
|
624
|
+
"version",
|
|
625
|
+
"status",
|
|
626
|
+
UNREAD_PARTS_FIELD,
|
|
627
|
+
"size_bytes",
|
|
628
|
+
"page_count",
|
|
629
|
+
"ocr_page_count",
|
|
630
|
+
"received_at",
|
|
631
|
+
"processed_at"
|
|
632
|
+
],
|
|
633
|
+
entries: ["type", "name", "file_count", "ready_count", "failed_count", "size_bytes", "updated_at"],
|
|
634
|
+
blocks: ["position", "kind", "text"],
|
|
635
|
+
questions: ["id", "asked_at", "end_user_id", "question"],
|
|
636
|
+
passages: [],
|
|
637
|
+
uploads: ["path", "outcome", "size_bytes", "file_id", "detail"]
|
|
638
|
+
};
|
|
639
|
+
function cellOf(column, value) {
|
|
640
|
+
if (KEY_PERMISSION_FIELDS.has(column)) return keyPermissionsText(value) ?? cellText(value);
|
|
641
|
+
if (column !== UNREAD_PARTS_FIELD) return cellText(value);
|
|
642
|
+
return unreadPartsText(value) ?? cellText(value);
|
|
643
|
+
}
|
|
644
|
+
function scalarFieldsOf(records) {
|
|
645
|
+
const fields = [];
|
|
646
|
+
for (const record2 of records) {
|
|
647
|
+
for (const field of Object.keys(record2)) if (!fields.includes(field)) fields.push(field);
|
|
648
|
+
}
|
|
649
|
+
return fields.filter((field) => records.every((record2) => isScalar(record2[field])));
|
|
650
|
+
}
|
|
651
|
+
function hasValue(records, field) {
|
|
652
|
+
return records.some((record2) => record2[field] !== null && record2[field] !== void 0);
|
|
653
|
+
}
|
|
654
|
+
function columnsFor(listKey, records) {
|
|
655
|
+
const preferred = Object.hasOwn(COLUMN_PREFERENCES, listKey) ? COLUMN_PREFERENCES[listKey] : void 0;
|
|
656
|
+
const candidates = preferred ?? scalarFieldsOf(records);
|
|
657
|
+
return candidates.filter((field) => hasValue(records, field));
|
|
658
|
+
}
|
|
659
|
+
function tableLines(columns, records) {
|
|
660
|
+
const rows = [
|
|
661
|
+
columns.map((column) => labelOf(column).toUpperCase()),
|
|
662
|
+
...records.map((record2) => columns.map((column) => cellOf(column, record2[column])))
|
|
663
|
+
];
|
|
664
|
+
const widths = columns.map((_, position) => Math.max(...rows.map((row) => displayWidth(row[position] ?? ""))));
|
|
665
|
+
return rows.map(
|
|
666
|
+
(row) => row.map((cell, position) => position === row.length - 1 ? cell : padEnd(cell, widths[position] ?? 0)).join(COLUMN_GAP)
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// src/text-output.ts
|
|
671
|
+
var LABEL_GAP = " ";
|
|
672
|
+
var NESTED_INDENT = " ";
|
|
673
|
+
var COMPACT_JSON_LIMIT = 80;
|
|
674
|
+
var CITATION_FIELDS = /* @__PURE__ */ new Set(["citation", "match_citation"]);
|
|
675
|
+
var MATCH_FIELD = "match";
|
|
676
|
+
var SECTION_FIELDS = /* @__PURE__ */ new Set(["account", "api_key", "invitation", "session"]);
|
|
677
|
+
function isRecordList(value) {
|
|
678
|
+
return Array.isArray(value) && value.every(isRecord);
|
|
679
|
+
}
|
|
680
|
+
function isSection(field, value) {
|
|
681
|
+
return SECTION_FIELDS.has(field) && isRecord(value);
|
|
682
|
+
}
|
|
683
|
+
function jsonLines(value) {
|
|
684
|
+
const compact = JSON.stringify(value) ?? String(value);
|
|
685
|
+
const text = displayWidth(compact) <= COMPACT_JSON_LIMIT ? compact : JSON.stringify(value, null, 2);
|
|
686
|
+
return printable(text, true).split("\n");
|
|
687
|
+
}
|
|
688
|
+
function valueLines(value) {
|
|
689
|
+
if (isScalar(value)) return scalarText(value, true).split("\n");
|
|
690
|
+
if (Array.isArray(value) && value.every(isScalar)) {
|
|
691
|
+
return value.length === 0 ? ["-"] : value.map((item) => scalarText(item, false));
|
|
692
|
+
}
|
|
693
|
+
return jsonLines(value);
|
|
694
|
+
}
|
|
695
|
+
function fieldLines(label, value, labelWidth, indent) {
|
|
696
|
+
const prefix = `${indent}${padEnd(label, labelWidth)}${LABEL_GAP}`;
|
|
697
|
+
const continuation = " ".repeat(displayWidth(prefix));
|
|
698
|
+
return valueLines(value).map((line, position) => `${position === 0 ? prefix : continuation}${line}`.trimEnd());
|
|
699
|
+
}
|
|
700
|
+
function readableCitation(value) {
|
|
701
|
+
if (!isCitation(value)) return value;
|
|
702
|
+
const text = citationText(value);
|
|
703
|
+
return value.kind === "web_page" && value.address !== null ? `${text}, at ${value.address}` : text;
|
|
704
|
+
}
|
|
705
|
+
function readableValue(field, value) {
|
|
706
|
+
if (CITATION_FIELDS.has(field)) return readableCitation(value);
|
|
707
|
+
if (field === UNREAD_PARTS_FIELD) return unreadPartsText(value) ?? value;
|
|
708
|
+
if (field !== MATCH_FIELD) return value;
|
|
709
|
+
return isPassageMatch(value) ? readableCitation(value.citation) : value;
|
|
710
|
+
}
|
|
711
|
+
function blockLines(record2, indent) {
|
|
712
|
+
const entries = Object.entries(record2);
|
|
713
|
+
const inline = entries.filter(([field, value]) => !isSection(field, value));
|
|
714
|
+
const labelWidth = Math.max(0, ...inline.map(([field]) => displayWidth(labelOf(field))));
|
|
715
|
+
const lines = inline.flatMap(
|
|
716
|
+
([field, value]) => fieldLines(labelOf(field), readableValue(field, value), labelWidth, indent)
|
|
717
|
+
);
|
|
718
|
+
for (const [field, value] of entries) {
|
|
719
|
+
if (!isSection(field, value) || !isRecord(value)) continue;
|
|
720
|
+
if (lines.length > 0) lines.push("");
|
|
721
|
+
lines.push(`${indent}${labelOf(field)}`, ...blockLines(value, `${indent}${NESTED_INDENT}`));
|
|
722
|
+
}
|
|
723
|
+
return lines;
|
|
724
|
+
}
|
|
725
|
+
function listPayloadOf(data) {
|
|
726
|
+
const lists = Object.entries(data).filter(([, value]) => Array.isArray(value));
|
|
727
|
+
const only = lists.length === 1 ? lists[0] : void 0;
|
|
728
|
+
if (only === void 0) return void 0;
|
|
729
|
+
const [listKey, records] = only;
|
|
730
|
+
if (!isRecordList(records)) return void 0;
|
|
731
|
+
const extras = Object.fromEntries(Object.entries(data).filter(([field]) => field !== listKey));
|
|
732
|
+
if (!Object.values(extras).every(isScalar)) return void 0;
|
|
733
|
+
return { listKey, records, extras };
|
|
734
|
+
}
|
|
735
|
+
function separateBlocks(records) {
|
|
736
|
+
return records.flatMap((record2, position) => [...position === 0 ? [] : [""], ...blockLines(record2, "")]);
|
|
737
|
+
}
|
|
738
|
+
function pageWindowOf(extras) {
|
|
739
|
+
const { total_count: totalCount, limit, offset } = extras;
|
|
740
|
+
if (typeof totalCount !== "number" || typeof limit !== "number" || typeof offset !== "number") return void 0;
|
|
741
|
+
return { totalCount, limit, offset };
|
|
742
|
+
}
|
|
743
|
+
function pageSentence(noun, shown, page) {
|
|
744
|
+
if (shown === 0) {
|
|
745
|
+
return `No ${noun} on this page. The list holds ${page.totalCount}, and the offset ${page.offset} passes its end.`;
|
|
746
|
+
}
|
|
747
|
+
const last = page.offset + shown;
|
|
748
|
+
const showing = `Showing ${page.offset + 1}\u2013${last} of ${page.totalCount} ${noun}.`;
|
|
749
|
+
return last < page.totalCount ? `${showing} Pass --offset ${last} for the next page.` : showing;
|
|
750
|
+
}
|
|
751
|
+
function recordLines(listKey, records) {
|
|
752
|
+
const columns = columnsFor(listKey, records);
|
|
753
|
+
if (records.length === 0) return [`No ${nounOf(listKey)}.`];
|
|
754
|
+
return columns.length === 0 ? separateBlocks(records) : tableLines(columns, records);
|
|
755
|
+
}
|
|
756
|
+
function listLines({ listKey, records, extras }) {
|
|
757
|
+
const page = pageWindowOf(extras);
|
|
758
|
+
if (page !== void 0) {
|
|
759
|
+
if (page.totalCount === 0) return [`No ${nounOf(listKey)}.`];
|
|
760
|
+
const body2 = records.length === 0 ? [] : [...recordLines(listKey, records), ""];
|
|
761
|
+
return [...body2, pageSentence(nounOf(listKey), records.length, page)];
|
|
762
|
+
}
|
|
763
|
+
const body = recordLines(listKey, records);
|
|
764
|
+
return Object.keys(extras).length === 0 ? body : [...body, "", ...blockLines(extras, "")];
|
|
765
|
+
}
|
|
766
|
+
function textLinesOf(data) {
|
|
767
|
+
if (isScalar(data)) return scalarText(data, true).split("\n");
|
|
768
|
+
if (isRecordList(data)) return listLines({ listKey: "items", records: data, extras: {} });
|
|
769
|
+
if (!isRecord(data)) return valueLines(data);
|
|
770
|
+
const list = listPayloadOf(data);
|
|
771
|
+
if (list !== void 0) return listLines(list);
|
|
772
|
+
const entries = Object.entries(data);
|
|
773
|
+
const wrapped = entries.length === 1 ? entries[0] : void 0;
|
|
774
|
+
if (wrapped !== void 0 && isSection(wrapped[0], wrapped[1]) && isRecord(wrapped[1])) {
|
|
775
|
+
return blockLines(wrapped[1], "");
|
|
776
|
+
}
|
|
777
|
+
return blockLines(data, "");
|
|
778
|
+
}
|
|
779
|
+
function formatText(data) {
|
|
780
|
+
const lines = textLinesOf(data);
|
|
781
|
+
return lines.length === 0 ? "" : `${lines.join("\n")}
|
|
782
|
+
`;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// src/output.ts
|
|
786
|
+
var OUTPUT_FORMATS = ["text", "json"];
|
|
787
|
+
function writeEnvelope(io, envelope) {
|
|
788
|
+
io.writeStdout(`${JSON.stringify(envelope)}
|
|
789
|
+
`);
|
|
790
|
+
}
|
|
791
|
+
function writeFailureText(io, failure) {
|
|
792
|
+
io.writeStderr(`Error: ${printable(failure.message, true)}
|
|
793
|
+
${printable(failure.suggestion, true)}
|
|
794
|
+
`);
|
|
795
|
+
}
|
|
796
|
+
function writeSuccess(io, format, data, metadata) {
|
|
797
|
+
if (format === "json") {
|
|
798
|
+
writeEnvelope(io, { status: "success", data, error: null, metadata });
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
io.writeStdout(formatText(data));
|
|
802
|
+
}
|
|
803
|
+
function writeFailure(io, format, failure, metadata) {
|
|
804
|
+
if (format === "json") {
|
|
805
|
+
writeEnvelope(io, { status: "error", data: null, error: failure, metadata });
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
writeFailureText(io, failure);
|
|
809
|
+
}
|
|
810
|
+
var SUGGESTION_BY_KIND = {
|
|
811
|
+
network: "Check that the API runs, and pass its address with --api-url or HIMRING_API_URL.",
|
|
812
|
+
timeout: "Try again, or raise the time limit with --timeout-ms or HIMRING_API_TIMEOUT_MS.",
|
|
813
|
+
invalid_input: "Correct the input as the message says. Read the --help of the command for its options.",
|
|
814
|
+
invalid_response: "Check that --api-url points at the Himring API.",
|
|
815
|
+
refused: "Follow the message of the API, then run the command again."
|
|
816
|
+
};
|
|
817
|
+
var SERVER_ERROR_MINIMUM = 500;
|
|
818
|
+
function suggestionFor(error) {
|
|
819
|
+
const suggestion = SUGGESTION_BY_KIND[error.kind];
|
|
820
|
+
const serverFailed = error.status !== void 0 && error.status >= SERVER_ERROR_MINIMUM;
|
|
821
|
+
if (!serverFailed || error.requestId === void 0) return suggestion;
|
|
822
|
+
return `${suggestion} If it keeps failing, report request ${error.requestId} to Himring.`;
|
|
823
|
+
}
|
|
824
|
+
function failureFor(error) {
|
|
825
|
+
const exitCode = exitCodeForError(error);
|
|
826
|
+
if (!isHimringApiError2(error)) {
|
|
827
|
+
return {
|
|
828
|
+
failure: { code: "unexpected_error", message: describeError(error), suggestion: "Report this to Himring." },
|
|
829
|
+
exitCode
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
return {
|
|
833
|
+
failure: {
|
|
834
|
+
code: error.code ?? error.kind,
|
|
835
|
+
message: describeError(error),
|
|
836
|
+
suggestion: suggestionFor(error),
|
|
837
|
+
...error.missingPermission === void 0 ? {} : { missing_permission: error.missingPermission }
|
|
838
|
+
},
|
|
839
|
+
exitCode
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// src/command-context.ts
|
|
844
|
+
function writePartial(io, format, partial, metadata) {
|
|
845
|
+
if (format === "json") {
|
|
846
|
+
writeEnvelope(io, { status: "error", data: partial.data, error: partial.failure, metadata });
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
io.writeStdout(formatText(partial.data));
|
|
850
|
+
writeFailureText(io, partial.failure);
|
|
851
|
+
}
|
|
852
|
+
var PartialResult = class {
|
|
853
|
+
data;
|
|
854
|
+
failure;
|
|
855
|
+
exitCode;
|
|
856
|
+
constructor(data, failure, exitCode) {
|
|
857
|
+
this.data = data;
|
|
858
|
+
this.failure = failure;
|
|
859
|
+
this.exitCode = exitCode;
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
async function credentialFor(context) {
|
|
863
|
+
const fromEnvironment = nonEmptyText(context.environment.HIMRING_API_KEY) ?? nonEmptyText(context.environment.HIMRING_SESSION_TOKEN);
|
|
864
|
+
if (fromEnvironment !== void 0) return fromEnvironment;
|
|
865
|
+
return (await context.credentials.read(context.options.apiUrl)).sessionToken;
|
|
866
|
+
}
|
|
867
|
+
function clientFor(context, credential) {
|
|
868
|
+
context.protectSecret(credential);
|
|
869
|
+
return createHimringClient({ baseUrl: context.options.apiUrl, timeoutMs: context.options.timeoutMs, credential });
|
|
870
|
+
}
|
|
871
|
+
async function signedInClient(context) {
|
|
872
|
+
return clientFor(context, await credentialFor(context));
|
|
873
|
+
}
|
|
874
|
+
async function runCommand(context, work) {
|
|
875
|
+
const startedAt = performance.now();
|
|
876
|
+
const metadata = { api_url: context.options.apiUrl };
|
|
877
|
+
const finished = () => ({ ...metadata, duration_ms: Math.round(performance.now() - startedAt) });
|
|
878
|
+
try {
|
|
879
|
+
const data = await work(metadata);
|
|
880
|
+
if (data instanceof PartialResult) {
|
|
881
|
+
writePartial(context.io, context.options.output, data, finished());
|
|
882
|
+
return data.exitCode;
|
|
883
|
+
}
|
|
884
|
+
writeSuccess(context.io, context.options.output, data, finished());
|
|
885
|
+
return EXIT_CODES.success;
|
|
886
|
+
} catch (error) {
|
|
887
|
+
if (error instanceof UsageError) {
|
|
888
|
+
writeFailure(
|
|
889
|
+
context.io,
|
|
890
|
+
context.options.output,
|
|
891
|
+
{ code: "usage", message: error.message, suggestion: error.suggestion },
|
|
892
|
+
finished()
|
|
893
|
+
);
|
|
894
|
+
return EXIT_CODES.usage;
|
|
895
|
+
}
|
|
896
|
+
if (error instanceof CredentialsFileError) {
|
|
897
|
+
writeFailure(
|
|
898
|
+
context.io,
|
|
899
|
+
context.options.output,
|
|
900
|
+
{
|
|
901
|
+
code: "credentials_file",
|
|
902
|
+
message: error.message,
|
|
903
|
+
suggestion: "Set HIMRING_CONFIG_DIR to a writable folder."
|
|
904
|
+
},
|
|
905
|
+
finished()
|
|
906
|
+
);
|
|
907
|
+
return EXIT_CODES.configuration;
|
|
908
|
+
}
|
|
909
|
+
const { failure, exitCode } = failureFor(error);
|
|
910
|
+
writeFailure(context.io, context.options.output, failure, finished());
|
|
911
|
+
return exitCode;
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
// src/file-body-command.ts
|
|
916
|
+
import { resolve } from "node:path";
|
|
917
|
+
import { HIMRING_OPERATIONS as HIMRING_OPERATIONS2 } from "@himring/sdk";
|
|
918
|
+
import { Option } from "commander";
|
|
919
|
+
|
|
920
|
+
// src/bounded-file-read.ts
|
|
921
|
+
import { boundedBytesOf, openLocalFile } from "@himring/sdk/folders";
|
|
922
|
+
var BYTES_PER_MEBIBYTE = 1024 * 1024;
|
|
923
|
+
function sizeText(bytes) {
|
|
924
|
+
return bytes % BYTES_PER_MEBIBYTE === 0 ? `${bytes / BYTES_PER_MEBIBYTE} MiB` : `${bytes} bytes`;
|
|
925
|
+
}
|
|
926
|
+
async function boundedFileBytesOf(read) {
|
|
927
|
+
const opened = await openLocalFile(read.absolutePath).catch(() => void 0);
|
|
928
|
+
if (opened === void 0) {
|
|
929
|
+
throw new UsageError(`${read.givenPath} is not a file that the CLI can read.`, "Pass the path of a readable file.");
|
|
930
|
+
}
|
|
931
|
+
let content;
|
|
932
|
+
try {
|
|
933
|
+
content = await boundedBytesOf(opened, read.maximumBytes);
|
|
934
|
+
} finally {
|
|
935
|
+
await opened.close();
|
|
936
|
+
}
|
|
937
|
+
if (content === void 0) {
|
|
938
|
+
throw new UsageError(`${read.givenPath} holds more than ${sizeText(read.maximumBytes)}.`, read.splitHint);
|
|
939
|
+
}
|
|
940
|
+
return content;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// src/dry-run.ts
|
|
944
|
+
import { HIMRING_OPERATIONS } from "@himring/sdk";
|
|
945
|
+
function requestPathOf(id, input) {
|
|
946
|
+
return HIMRING_OPERATIONS[id].path.replace(
|
|
947
|
+
/\{([^}]+)\}/g,
|
|
948
|
+
(_whole, name) => encodeURIComponent(String(input[name]))
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
function withoutPathFields(id, input) {
|
|
952
|
+
const pathNames = new Set(HIMRING_OPERATIONS[id].pathParameters);
|
|
953
|
+
return Object.fromEntries(Object.entries(input).filter(([name]) => !pathNames.has(name)));
|
|
954
|
+
}
|
|
955
|
+
function dryRunOf(id, input, sent) {
|
|
956
|
+
return {
|
|
957
|
+
dry_run: true,
|
|
958
|
+
operation: id,
|
|
959
|
+
method: HIMRING_OPERATIONS[id].method,
|
|
960
|
+
path: requestPathOf(id, input),
|
|
961
|
+
input: sent,
|
|
962
|
+
applied: false
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// src/file-body-command.ts
|
|
967
|
+
var PROJECT_VARIABLE = "HIMRING_PROJECT";
|
|
968
|
+
function definedFieldsOf(input) {
|
|
969
|
+
return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0));
|
|
970
|
+
}
|
|
971
|
+
function choicesOf(id, field) {
|
|
972
|
+
const choices = propertySchemaOf(id, field).enum;
|
|
973
|
+
return Array.isArray(choices) ? choices.filter((choice) => typeof choice === "string") : [];
|
|
974
|
+
}
|
|
975
|
+
function addProjectOption(command) {
|
|
976
|
+
return command.addOption(new Option("--project <value>", "project_id (required)").env(PROJECT_VARIABLE));
|
|
977
|
+
}
|
|
978
|
+
async function sendFileBody(context, request) {
|
|
979
|
+
const description = HIMRING_OPERATIONS2[request.id];
|
|
980
|
+
if (description.body !== "file") throw new Error(`${request.id} takes no file.`);
|
|
981
|
+
if (request.from === void 0) throw new UsageError("The command needs a file.", "Pass its path with --from.");
|
|
982
|
+
const input = definedFieldsOf(request.input);
|
|
983
|
+
checkInput(request.id, input, request.suggestion);
|
|
984
|
+
const absolutePath = resolve(request.from);
|
|
985
|
+
const content = await boundedFileBytesOf({
|
|
986
|
+
givenPath: request.from,
|
|
987
|
+
absolutePath,
|
|
988
|
+
maximumBytes: description.maximumBodyBytes,
|
|
989
|
+
splitHint: request.splitHint
|
|
990
|
+
});
|
|
991
|
+
if (request.dryRun) {
|
|
992
|
+
const sent = withoutPathFields(request.id, input);
|
|
993
|
+
return dryRunOf(request.id, input, { ...sent, from: absolutePath, size_bytes: content.byteLength });
|
|
994
|
+
}
|
|
995
|
+
const result = await (await signedInClient(context)).invoke(request.id, { ...input, content });
|
|
996
|
+
checkOutput(request.id, result);
|
|
997
|
+
return result;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
// src/answer-log-commands.ts
|
|
1001
|
+
var OPERATION = "import_answer_log";
|
|
1002
|
+
var commandOptionsSchema = v2.object({
|
|
1003
|
+
project: v2.optional(v2.string()),
|
|
1004
|
+
knowledgeBase: v2.optional(v2.string()),
|
|
1005
|
+
from: v2.optional(v2.string()),
|
|
1006
|
+
dryRun: v2.optional(v2.boolean())
|
|
1007
|
+
});
|
|
1008
|
+
var IMPORT_EXAMPLES = `
|
|
1009
|
+
Examples:
|
|
1010
|
+
$ himring answer-events import --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --from answers.jsonl
|
|
1011
|
+
$ himring answer-events import --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --from answers.jsonl --output json
|
|
1012
|
+
|
|
1013
|
+
Each JSON line holds one event, such as {"question_id": "qst_...", "answer": "...", "follow_up": "...", "thumbs_down": true}.`;
|
|
1014
|
+
function addAnswerLogCommands(program, contextFor, recordExitCode) {
|
|
1015
|
+
const group = program.commands.find((command) => command.name() === "answer-events");
|
|
1016
|
+
if (group === void 0) throw new Error("The import command needs the answer-events group.");
|
|
1017
|
+
addProjectOption(group.command("import").description(HIMRING_OPERATION_CATALOGUE3[OPERATION].summary)).addOption(new Option2("--knowledge-base <value>", "knowledge_base_id (required)")).requiredOption("--from <path>", "the local log of answers, in JSON Lines").option("--dry-run", "check the input and show the request, without sending it").addHelpText("after", IMPORT_EXAMPLES).action(async (_options, invoked) => {
|
|
1018
|
+
const context = contextFor(invoked);
|
|
1019
|
+
if (context === void 0) return;
|
|
1020
|
+
const options = v2.parse(commandOptionsSchema, invoked.opts());
|
|
1021
|
+
recordExitCode(
|
|
1022
|
+
await runCommand(
|
|
1023
|
+
context,
|
|
1024
|
+
() => sendFileBody(context, {
|
|
1025
|
+
id: OPERATION,
|
|
1026
|
+
input: { project_id: options.project, knowledge_base_id: options.knowledgeBase },
|
|
1027
|
+
from: options.from,
|
|
1028
|
+
dryRun: options.dryRun === true,
|
|
1029
|
+
suggestion: "Pass --project and --knowledge-base.",
|
|
1030
|
+
splitHint: "Split the log into several files and import each one."
|
|
1031
|
+
})
|
|
1032
|
+
)
|
|
1033
|
+
);
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
// src/auth-commands.ts
|
|
1038
|
+
import { Option as Option3 } from "commander";
|
|
1039
|
+
import * as v3 from "valibot";
|
|
1040
|
+
|
|
1041
|
+
// src/input-sources.ts
|
|
1042
|
+
import { resolve as resolve2 } from "node:path";
|
|
1043
|
+
|
|
1044
|
+
// src/input-limits.ts
|
|
1045
|
+
var MAXIMUM_LOCAL_INPUT_BYTES = 8 * 1024 * 1024;
|
|
1046
|
+
|
|
1047
|
+
// src/input-sources.ts
|
|
1048
|
+
var STDIN_PATH = "-";
|
|
1049
|
+
var SPLIT_HINT = "Split the input into smaller requests.";
|
|
1050
|
+
async function readLocalFile(path) {
|
|
1051
|
+
const bytes = await boundedFileBytesOf({
|
|
1052
|
+
givenPath: path,
|
|
1053
|
+
absolutePath: resolve2(path),
|
|
1054
|
+
maximumBytes: MAXIMUM_LOCAL_INPUT_BYTES,
|
|
1055
|
+
splitHint: SPLIT_HINT
|
|
1056
|
+
});
|
|
1057
|
+
return Buffer.from(bytes).toString("utf8");
|
|
1058
|
+
}
|
|
1059
|
+
async function readTextSource(context, path, label) {
|
|
1060
|
+
const text = path === STDIN_PATH ? await context.io.readStdin() : await readLocalFile(path);
|
|
1061
|
+
if (Buffer.byteLength(text, "utf8") > MAXIMUM_LOCAL_INPUT_BYTES) {
|
|
1062
|
+
throw new UsageError(`${label} is larger than ${sizeText(MAXIMUM_LOCAL_INPUT_BYTES)}.`, SPLIT_HINT);
|
|
1063
|
+
}
|
|
1064
|
+
return text;
|
|
1065
|
+
}
|
|
1066
|
+
async function readJsonSource(context, path, label) {
|
|
1067
|
+
const text = await readTextSource(context, path, label);
|
|
1068
|
+
try {
|
|
1069
|
+
return JSON.parse(text);
|
|
1070
|
+
} catch {
|
|
1071
|
+
throw new UsageError(`${label} in ${path === STDIN_PATH ? "stdin" : path} is not valid JSON.`, "Fix the JSON.");
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
var PASSWORD_VARIABLE = "HIMRING_PASSWORD";
|
|
1075
|
+
async function readPassword(context, fromStdin) {
|
|
1076
|
+
if (fromStdin) {
|
|
1077
|
+
if (context.io.stdinIsTerminal) {
|
|
1078
|
+
throw new UsageError(
|
|
1079
|
+
"--password-stdin reads a pipe, and stdin is a terminal.",
|
|
1080
|
+
'Pipe the password, as in printf "%s" "$PASSWORD" | himring \u2026'
|
|
1081
|
+
);
|
|
1082
|
+
}
|
|
1083
|
+
const firstLine = (await context.io.readStdin()).split(/\r?\n/, 1)[0] ?? "";
|
|
1084
|
+
if (firstLine.length === 0) {
|
|
1085
|
+
throw new UsageError("stdin held no password.", "Pipe the password on the first line of stdin.");
|
|
1086
|
+
}
|
|
1087
|
+
context.protectSecret(firstLine);
|
|
1088
|
+
return firstLine;
|
|
1089
|
+
}
|
|
1090
|
+
const fromEnvironment = context.environment[PASSWORD_VARIABLE];
|
|
1091
|
+
if (fromEnvironment !== void 0 && fromEnvironment.length > 0) {
|
|
1092
|
+
context.protectSecret(fromEnvironment);
|
|
1093
|
+
return fromEnvironment;
|
|
1094
|
+
}
|
|
1095
|
+
throw new UsageError(
|
|
1096
|
+
"The command needs the password of the account.",
|
|
1097
|
+
`Pipe it with --password-stdin, or set ${PASSWORD_VARIABLE}, so that it never shows in your shell history.`
|
|
1098
|
+
);
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
// src/auth-commands.ts
|
|
1102
|
+
var optionsSchema = v3.object({
|
|
1103
|
+
email: v3.optional(v3.string()),
|
|
1104
|
+
name: v3.optional(v3.string()),
|
|
1105
|
+
passwordStdin: v3.optional(v3.boolean(), false),
|
|
1106
|
+
code: v3.optional(v3.string()),
|
|
1107
|
+
backupCode: v3.optional(v3.string())
|
|
1108
|
+
});
|
|
1109
|
+
var AUTH_SUGGESTION = "Correct the options and try again.";
|
|
1110
|
+
function required(value, flag, example) {
|
|
1111
|
+
if (value === void 0 || value.length === 0) throw new UsageError(`Pass ${flag}.`, `For example: ${example}`);
|
|
1112
|
+
return value;
|
|
1113
|
+
}
|
|
1114
|
+
function deviceKeyOf(email) {
|
|
1115
|
+
return email.trim().toLowerCase();
|
|
1116
|
+
}
|
|
1117
|
+
function secondFactorOf(options) {
|
|
1118
|
+
if (options.code !== void 0 && options.backupCode !== void 0) {
|
|
1119
|
+
throw new UsageError("Pass --code or --backup-code, not both.", "Use the code that your authenticator app shows.");
|
|
1120
|
+
}
|
|
1121
|
+
if (options.code !== void 0) return { method: "totp", code: options.code };
|
|
1122
|
+
if (options.backupCode !== void 0) return { method: "backup_code", code: options.backupCode };
|
|
1123
|
+
return void 0;
|
|
1124
|
+
}
|
|
1125
|
+
async function saveSession(context, signedIn) {
|
|
1126
|
+
context.protectSecret(signedIn.session_token);
|
|
1127
|
+
await context.credentials.update(context.options.apiUrl, (current) => {
|
|
1128
|
+
const { challengeToken: _challenge, ...rest } = current;
|
|
1129
|
+
return { ...rest, sessionToken: signedIn.session_token };
|
|
1130
|
+
});
|
|
1131
|
+
return {
|
|
1132
|
+
state: "signed_in",
|
|
1133
|
+
account: signedIn.session.account,
|
|
1134
|
+
expires_at: signedIn.session.expires_at,
|
|
1135
|
+
credentials_file: context.credentials.path
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
async function verifyWith(context, challengeToken, secondFactor) {
|
|
1139
|
+
context.protectSecret(challengeToken);
|
|
1140
|
+
context.protectSecret(secondFactor.code);
|
|
1141
|
+
const input = { challenge_token: challengeToken, ...secondFactor };
|
|
1142
|
+
checkInput("verify_second_factor", input, AUTH_SUGGESTION);
|
|
1143
|
+
const signedIn = await clientFor(context, void 0).verifySecondFactor(input);
|
|
1144
|
+
checkOutput("verify_second_factor", signedIn);
|
|
1145
|
+
return saveSession(context, signedIn);
|
|
1146
|
+
}
|
|
1147
|
+
async function signUp(context, options) {
|
|
1148
|
+
const example = 'himring auth sign-up --email owner@example.com --name "Support lead"';
|
|
1149
|
+
const email = required(options.email, "--email", example);
|
|
1150
|
+
const name = required(options.name, "--name", example);
|
|
1151
|
+
const input = { email, name, password: await readPassword(context, options.passwordStdin) };
|
|
1152
|
+
checkInput("sign_up", input, AUTH_SUGGESTION);
|
|
1153
|
+
const result = await clientFor(context, void 0).signUp(input);
|
|
1154
|
+
checkOutput("sign_up", result);
|
|
1155
|
+
return { ...result, next: `himring auth sign-in --email ${result.email} --password-stdin` };
|
|
1156
|
+
}
|
|
1157
|
+
async function finishWithChallenge(context, challengeToken, options) {
|
|
1158
|
+
const secondFactor = secondFactorOf(options);
|
|
1159
|
+
if (secondFactor === void 0) {
|
|
1160
|
+
await context.credentials.update(context.options.apiUrl, (current) => ({ ...current, challengeToken }));
|
|
1161
|
+
return { state: "second_factor_required", next: "himring auth verify --code <six digits>" };
|
|
1162
|
+
}
|
|
1163
|
+
return verifyWith(context, challengeToken, secondFactor);
|
|
1164
|
+
}
|
|
1165
|
+
async function signIn(context, options) {
|
|
1166
|
+
const email = required(options.email, "--email", "himring auth sign-in --email owner@example.com --password-stdin");
|
|
1167
|
+
const password = await readPassword(context, options.passwordStdin);
|
|
1168
|
+
const stored = await context.credentials.read(context.options.apiUrl);
|
|
1169
|
+
const deviceKey = deviceKeyOf(email);
|
|
1170
|
+
const knownDeviceToken = Object.hasOwn(stored.knownDeviceTokens, deviceKey) ? stored.knownDeviceTokens[deviceKey] : void 0;
|
|
1171
|
+
context.protectSecret(knownDeviceToken);
|
|
1172
|
+
const input = { email, password, ...knownDeviceToken === void 0 ? {} : { known_device_token: knownDeviceToken } };
|
|
1173
|
+
checkInput("sign_in", input, AUTH_SUGGESTION);
|
|
1174
|
+
const step = await clientFor(context, void 0).signIn(input);
|
|
1175
|
+
checkOutput("sign_in", step);
|
|
1176
|
+
await context.credentials.update(context.options.apiUrl, (current) => ({
|
|
1177
|
+
...current,
|
|
1178
|
+
knownDeviceTokens: { ...current.knownDeviceTokens, [deviceKey]: step.known_device_token }
|
|
1179
|
+
}));
|
|
1180
|
+
if (step.state === "second_factor_required") return finishWithChallenge(context, step.challenge_token, options);
|
|
1181
|
+
await context.credentials.update(context.options.apiUrl, (current) => ({
|
|
1182
|
+
...current,
|
|
1183
|
+
sessionToken: step.session_token
|
|
1184
|
+
}));
|
|
1185
|
+
return {
|
|
1186
|
+
state: "second_factor_setup_required",
|
|
1187
|
+
next: "himring auth second-factor setup --password-stdin",
|
|
1188
|
+
credentials_file: context.credentials.path
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
async function verify(context, options) {
|
|
1192
|
+
const secondFactor = secondFactorOf(options);
|
|
1193
|
+
if (secondFactor === void 0) {
|
|
1194
|
+
throw new UsageError("Pass --code or --backup-code.", "For example: himring auth verify --code 123456");
|
|
1195
|
+
}
|
|
1196
|
+
const { challengeToken } = await context.credentials.read(context.options.apiUrl);
|
|
1197
|
+
if (challengeToken === void 0) {
|
|
1198
|
+
throw new UsageError("No sign-in waits for a second factor.", "Run himring auth sign-in first.");
|
|
1199
|
+
}
|
|
1200
|
+
return verifyWith(context, challengeToken, secondFactor);
|
|
1201
|
+
}
|
|
1202
|
+
async function sessionClient(context) {
|
|
1203
|
+
const credential = await credentialFor(context);
|
|
1204
|
+
if (credential === void 0) throw new UsageError("You are not signed in.", "Run himring auth sign-in first.");
|
|
1205
|
+
return clientFor(context, credential);
|
|
1206
|
+
}
|
|
1207
|
+
async function beginSetup(context, options) {
|
|
1208
|
+
const input = { password: await readPassword(context, options.passwordStdin) };
|
|
1209
|
+
checkInput("begin_second_factor_setup", input, AUTH_SUGGESTION);
|
|
1210
|
+
const setup = await (await sessionClient(context)).beginSecondFactorSetup(input);
|
|
1211
|
+
checkOutput("begin_second_factor_setup", setup);
|
|
1212
|
+
return {
|
|
1213
|
+
...setup,
|
|
1214
|
+
next: "Add totp_uri to your authenticator app, keep the backup codes, then run himring auth second-factor confirm --code <six digits>"
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
async function confirmSetup(context, options) {
|
|
1218
|
+
const input = { code: required(options.code, "--code", "himring auth second-factor confirm --code 123456") };
|
|
1219
|
+
context.protectSecret(input.code);
|
|
1220
|
+
checkInput("confirm_second_factor_setup", input, AUTH_SUGGESTION);
|
|
1221
|
+
const signedIn = await (await sessionClient(context)).confirmSecondFactorSetup(input);
|
|
1222
|
+
checkOutput("confirm_second_factor_setup", signedIn);
|
|
1223
|
+
return saveSession(context, signedIn);
|
|
1224
|
+
}
|
|
1225
|
+
async function signOut(context) {
|
|
1226
|
+
const result = await (await sessionClient(context)).signOut({});
|
|
1227
|
+
checkOutput("sign_out", result);
|
|
1228
|
+
await context.credentials.update(context.options.apiUrl, (current) => {
|
|
1229
|
+
const { sessionToken: _session, challengeToken: _challenge, ...rest } = current;
|
|
1230
|
+
return rest;
|
|
1231
|
+
});
|
|
1232
|
+
return result;
|
|
1233
|
+
}
|
|
1234
|
+
function addAuthAction(command, action, contextFor, recordExitCode) {
|
|
1235
|
+
return command.action(async (_options, invoked) => {
|
|
1236
|
+
const context = contextFor(invoked);
|
|
1237
|
+
if (context === void 0) return;
|
|
1238
|
+
recordExitCode(await runCommand(context, () => action(context, v3.parse(optionsSchema, invoked.opts()))));
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
function passwordStdin() {
|
|
1242
|
+
return new Option3("--password-stdin", "read the password from the first line of stdin, or set HIMRING_PASSWORD");
|
|
1243
|
+
}
|
|
1244
|
+
function examples(...lines) {
|
|
1245
|
+
return `
|
|
1246
|
+
Examples:
|
|
1247
|
+
${lines.map((line) => ` $ ${line}`).join("\n")}`;
|
|
1248
|
+
}
|
|
1249
|
+
function withSecondFactorCodes(command) {
|
|
1250
|
+
return command.option("--code <digits>", "the six digits that your authenticator app shows").option("--backup-code <code>", "one of your backup codes, in place of --code");
|
|
1251
|
+
}
|
|
1252
|
+
function addAuthCommands(program, contextFor, recordExitCode) {
|
|
1253
|
+
const auth = program.command("auth").description("Sign up, sign in, set up your second factor, and sign out.");
|
|
1254
|
+
const add = (command, action) => addAuthAction(command, action, contextFor, recordExitCode);
|
|
1255
|
+
add(
|
|
1256
|
+
auth.command("sign-up").description("Create an account, which waits until a Himring operator approves it.").option("--email <address>", "your email address").option("--name <name>", "your name").addOption(passwordStdin()).addHelpText(
|
|
1257
|
+
"after",
|
|
1258
|
+
examples(
|
|
1259
|
+
'printf "%s" "$PASSWORD" | himring auth sign-up --email owner@example.com --name "Support lead" --password-stdin',
|
|
1260
|
+
'HIMRING_PASSWORD=\u2026 himring auth sign-up --email owner@example.com --name "Support lead" --output json'
|
|
1261
|
+
)
|
|
1262
|
+
),
|
|
1263
|
+
signUp
|
|
1264
|
+
);
|
|
1265
|
+
add(
|
|
1266
|
+
withSecondFactorCodes(
|
|
1267
|
+
auth.command("sign-in").description("Sign in with your password and second factor, and keep the session in the credentials file.").option("--email <address>", "your email address").addOption(passwordStdin())
|
|
1268
|
+
).addHelpText(
|
|
1269
|
+
"after",
|
|
1270
|
+
examples(
|
|
1271
|
+
'printf "%s" "$PASSWORD" | himring auth sign-in --email owner@example.com --password-stdin --code 123456',
|
|
1272
|
+
"HIMRING_PASSWORD=\u2026 himring auth sign-in --email owner@example.com && himring auth verify --code 123456"
|
|
1273
|
+
)
|
|
1274
|
+
),
|
|
1275
|
+
signIn
|
|
1276
|
+
);
|
|
1277
|
+
add(
|
|
1278
|
+
withSecondFactorCodes(
|
|
1279
|
+
auth.command("verify").description("Finish a sign-in that waits for your second factor.")
|
|
1280
|
+
).addHelpText(
|
|
1281
|
+
"after",
|
|
1282
|
+
examples("himring auth verify --code 123456", "himring auth verify --backup-code 4f7a-9c2e1b")
|
|
1283
|
+
),
|
|
1284
|
+
verify
|
|
1285
|
+
);
|
|
1286
|
+
const secondFactor = auth.command("second-factor").description("Set up the authenticator app for your account.");
|
|
1287
|
+
add(
|
|
1288
|
+
secondFactor.command("setup").description("Start the setup, and receive the authenticator URI and ten backup codes.").addOption(passwordStdin()).addHelpText(
|
|
1289
|
+
"after",
|
|
1290
|
+
examples(
|
|
1291
|
+
'printf "%s" "$PASSWORD" | himring auth second-factor setup --password-stdin',
|
|
1292
|
+
"HIMRING_PASSWORD=\u2026 himring auth second-factor setup --output json"
|
|
1293
|
+
)
|
|
1294
|
+
),
|
|
1295
|
+
beginSetup
|
|
1296
|
+
);
|
|
1297
|
+
add(
|
|
1298
|
+
secondFactor.command("confirm").description("Finish the setup with a code from the authenticator app.").option("--code <digits>", "the six digits that your authenticator app shows").addHelpText(
|
|
1299
|
+
"after",
|
|
1300
|
+
examples(
|
|
1301
|
+
"himring auth second-factor confirm --code 123456",
|
|
1302
|
+
"himring auth second-factor confirm --code 123456 --output json"
|
|
1303
|
+
)
|
|
1304
|
+
),
|
|
1305
|
+
confirmSetup
|
|
1306
|
+
);
|
|
1307
|
+
add(
|
|
1308
|
+
auth.command("sign-out").description("End the session, and remove it from the credentials file.").addHelpText("after", examples("himring auth sign-out", "himring auth sign-out --output json")),
|
|
1309
|
+
(context) => signOut(context)
|
|
1310
|
+
);
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
// src/file-commands.ts
|
|
1314
|
+
import { stat as stat3 } from "node:fs/promises";
|
|
1315
|
+
import { basename, resolve as resolve5 } from "node:path";
|
|
1316
|
+
import { uploadLocalFile } from "@himring/sdk/folders";
|
|
1317
|
+
import { Option as Option6 } from "commander";
|
|
1318
|
+
import * as v6 from "valibot";
|
|
1319
|
+
|
|
1320
|
+
// src/file-download-command.ts
|
|
1321
|
+
import { Option as Option4 } from "commander";
|
|
1322
|
+
import * as v4 from "valibot";
|
|
1323
|
+
|
|
1324
|
+
// src/download-target.ts
|
|
1325
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1326
|
+
import { rmSync } from "node:fs";
|
|
1327
|
+
import { link, rename as rename2, rm as rm2, stat } from "node:fs/promises";
|
|
1328
|
+
import { dirname, join as join2, resolve as resolve3 } from "node:path";
|
|
1329
|
+
import { HimringApiError as HimringApiError2, safeDownloadName } from "@himring/sdk";
|
|
1330
|
+
import { isDownload, saveDownload } from "@himring/sdk/folders";
|
|
1331
|
+
var FALLBACK_FILE_NAME = "download";
|
|
1332
|
+
var INTERRUPTED_EXIT_CODE = 130;
|
|
1333
|
+
var WRITE_FAILURE_CODES = /* @__PURE__ */ new Set(["ENOENT", "EACCES", "EPERM", "EISDIR", "ENOTDIR", "EROFS"]);
|
|
1334
|
+
var NO_HARD_LINK_CODES = /* @__PURE__ */ new Set(["EPERM", "ENOTSUP", "EXDEV", "EOPNOTSUPP"]);
|
|
1335
|
+
function withIdleLimit(body, idleTimeoutMs) {
|
|
1336
|
+
const reader = body.getReader();
|
|
1337
|
+
return new ReadableStream(
|
|
1338
|
+
{
|
|
1339
|
+
async pull(controller) {
|
|
1340
|
+
let timer;
|
|
1341
|
+
const stalled = new Promise((_resolve, reject) => {
|
|
1342
|
+
timer = setTimeout(() => {
|
|
1343
|
+
reject(
|
|
1344
|
+
new HimringApiError2(
|
|
1345
|
+
"timeout",
|
|
1346
|
+
`The download sent no data for ${idleTimeoutMs} ms, so the CLI stopped it.`
|
|
1347
|
+
)
|
|
1348
|
+
);
|
|
1349
|
+
}, idleTimeoutMs);
|
|
1350
|
+
});
|
|
1351
|
+
try {
|
|
1352
|
+
const read = await Promise.race([reader.read(), stalled]);
|
|
1353
|
+
if (read.done) controller.close();
|
|
1354
|
+
else controller.enqueue(read.value);
|
|
1355
|
+
} catch (error) {
|
|
1356
|
+
await reader.cancel(error).catch(() => void 0);
|
|
1357
|
+
throw error;
|
|
1358
|
+
} finally {
|
|
1359
|
+
clearTimeout(timer);
|
|
1360
|
+
}
|
|
1361
|
+
},
|
|
1362
|
+
cancel(reason) {
|
|
1363
|
+
return reader.cancel(reason);
|
|
1364
|
+
}
|
|
1365
|
+
},
|
|
1366
|
+
{ highWaterMark: 0 }
|
|
1367
|
+
);
|
|
1368
|
+
}
|
|
1369
|
+
function codeOf(error) {
|
|
1370
|
+
if (!(error instanceof Error) || !("code" in error)) return void 0;
|
|
1371
|
+
return typeof error.code === "string" ? error.code : void 0;
|
|
1372
|
+
}
|
|
1373
|
+
async function exists(path) {
|
|
1374
|
+
return await stat(path).catch(() => void 0) !== void 0;
|
|
1375
|
+
}
|
|
1376
|
+
function alreadyExists(path) {
|
|
1377
|
+
return new UsageError(`${path} already exists.`, "Pass --force to replace it, or --out with another path.");
|
|
1378
|
+
}
|
|
1379
|
+
function downloadFailure(error, path) {
|
|
1380
|
+
if (error instanceof UsageError || error instanceof HimringApiError2) return error;
|
|
1381
|
+
const code = codeOf(error);
|
|
1382
|
+
if (code !== void 0 && WRITE_FAILURE_CODES.has(code)) {
|
|
1383
|
+
return new UsageError(
|
|
1384
|
+
`The CLI could not write ${path} (${code}).`,
|
|
1385
|
+
"Pass --out with a path in a folder that you can write."
|
|
1386
|
+
);
|
|
1387
|
+
}
|
|
1388
|
+
return new HimringApiError2(
|
|
1389
|
+
"network",
|
|
1390
|
+
`The download of ${path} stopped before the whole file arrived, so the CLI kept no part of it.`,
|
|
1391
|
+
{ cause: error }
|
|
1392
|
+
);
|
|
1393
|
+
}
|
|
1394
|
+
async function placeWithoutReplacing(temporary, target) {
|
|
1395
|
+
try {
|
|
1396
|
+
await link(temporary, target);
|
|
1397
|
+
} catch (error) {
|
|
1398
|
+
const code = codeOf(error);
|
|
1399
|
+
if (code === "EEXIST") throw alreadyExists(target);
|
|
1400
|
+
if (code === void 0 || !NO_HARD_LINK_CODES.has(code)) throw error;
|
|
1401
|
+
if (await exists(target)) throw alreadyExists(target);
|
|
1402
|
+
await rename2(temporary, target);
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
async function saveDownloadTo(result, target) {
|
|
1406
|
+
if (!isDownload(result))
|
|
1407
|
+
throw new HimringApiError2("invalid_response", "The API answered the download without a file.");
|
|
1408
|
+
const path = resolve3(target.out ?? safeDownloadName(result.file_name, FALLBACK_FILE_NAME));
|
|
1409
|
+
if (!target.force && await exists(path)) {
|
|
1410
|
+
await result.body.cancel().catch(() => void 0);
|
|
1411
|
+
throw alreadyExists(path);
|
|
1412
|
+
}
|
|
1413
|
+
const temporary = join2(dirname(path), `.himring-download-${randomBytes2(8).toString("hex")}.part`);
|
|
1414
|
+
const removeOnInterrupt = () => {
|
|
1415
|
+
rmSync(temporary, { force: true });
|
|
1416
|
+
process.exit(INTERRUPTED_EXIT_CODE);
|
|
1417
|
+
};
|
|
1418
|
+
process.once("SIGINT", removeOnInterrupt);
|
|
1419
|
+
try {
|
|
1420
|
+
const saved = await saveDownload({ ...result, body: withIdleLimit(result.body, target.idleTimeoutMs) }, temporary);
|
|
1421
|
+
if (target.force) await rename2(temporary, path);
|
|
1422
|
+
else await placeWithoutReplacing(temporary, path);
|
|
1423
|
+
return { file: path, bytes: saved.bytes, content_type: saved.content_type };
|
|
1424
|
+
} catch (error) {
|
|
1425
|
+
await result.body.cancel().catch(() => void 0);
|
|
1426
|
+
throw downloadFailure(error, path);
|
|
1427
|
+
} finally {
|
|
1428
|
+
process.off("SIGINT", removeOnInterrupt);
|
|
1429
|
+
await rm2(temporary, { force: true });
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
// src/file-download-command.ts
|
|
1434
|
+
var OPERATION2 = "get_download_link";
|
|
1435
|
+
var DOWNLOAD_FIELDS = ["project_id", "knowledge_base_id", "file_id", "version", "rendition"];
|
|
1436
|
+
var downloadOptionsSchema = v4.object({
|
|
1437
|
+
project: v4.optional(v4.string()),
|
|
1438
|
+
knowledgeBase: v4.optional(v4.string()),
|
|
1439
|
+
file: v4.optional(v4.string()),
|
|
1440
|
+
version: v4.optional(v4.string()),
|
|
1441
|
+
rendition: v4.optional(v4.string()),
|
|
1442
|
+
out: v4.optional(v4.string()),
|
|
1443
|
+
force: v4.optional(v4.boolean())
|
|
1444
|
+
});
|
|
1445
|
+
var DOWNLOAD_EXAMPLES = `
|
|
1446
|
+
Examples:
|
|
1447
|
+
$ himring files download --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --file fil_0a1b2c3d4e5f60718293a4b5c6d7e8f9 --version 2
|
|
1448
|
+
$ himring files download --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --file fil_0a1b2c3d4e5f60718293a4b5c6d7e8f9 --version 1 --rendition pdf --out handbook.pdf`;
|
|
1449
|
+
function isRendition(value) {
|
|
1450
|
+
return choicesOf(OPERATION2, "rendition").includes(value);
|
|
1451
|
+
}
|
|
1452
|
+
function definedOnly(input) {
|
|
1453
|
+
return Object.fromEntries(Object.entries(input).filter((entry) => entry[1] !== void 0));
|
|
1454
|
+
}
|
|
1455
|
+
async function downloadOne(context, options) {
|
|
1456
|
+
const input = definedOnly({
|
|
1457
|
+
project_id: options.project,
|
|
1458
|
+
knowledge_base_id: options.knowledgeBase,
|
|
1459
|
+
file_id: options.file,
|
|
1460
|
+
version: options.version,
|
|
1461
|
+
rendition: options.rendition
|
|
1462
|
+
});
|
|
1463
|
+
checkInput(OPERATION2, input, "Pass --project, --knowledge-base, --file, and --version.", DOWNLOAD_FIELDS);
|
|
1464
|
+
const { project_id, knowledge_base_id, file_id, version, rendition } = input;
|
|
1465
|
+
if (project_id === void 0 || knowledge_base_id === void 0 || file_id === void 0 || version === void 0) {
|
|
1466
|
+
throw new Error("The checked download input lost a required field.");
|
|
1467
|
+
}
|
|
1468
|
+
const client = await signedInClient(context);
|
|
1469
|
+
const download = await client.downloadFile({
|
|
1470
|
+
project_id,
|
|
1471
|
+
knowledge_base_id,
|
|
1472
|
+
file_id,
|
|
1473
|
+
version: Number(version),
|
|
1474
|
+
...rendition !== void 0 && isRendition(rendition) ? { rendition } : {}
|
|
1475
|
+
});
|
|
1476
|
+
return saveDownloadTo(download, {
|
|
1477
|
+
out: options.out,
|
|
1478
|
+
force: options.force === true,
|
|
1479
|
+
idleTimeoutMs: context.options.timeoutMs
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
function addFileDownloadCommand(group, contextFor, recordExitCode) {
|
|
1483
|
+
addProjectOption(
|
|
1484
|
+
group.command("download").description(
|
|
1485
|
+
"Download one version of a file straight from storage, through a link that Himring signs for a few minutes, or with --rendition pdf the PDF that Himring made of a Word file or a slide deck."
|
|
1486
|
+
)
|
|
1487
|
+
).addOption(new Option4("--knowledge-base <value>", "knowledge_base_id (required)")).option("--file <value>", "file_id (required)").option("--version <value>", "the version of the file (required)").addOption(
|
|
1488
|
+
new Option4("--rendition <value>", "pdf for the PDF that Himring made of the file").choices(
|
|
1489
|
+
choicesOf(OPERATION2, "rendition")
|
|
1490
|
+
)
|
|
1491
|
+
).option(
|
|
1492
|
+
"--out <path>",
|
|
1493
|
+
"write the file to this path; without it, the CLI writes the file under its own name in this folder"
|
|
1494
|
+
).option("--force", "replace a file that already exists").addHelpText("after", DOWNLOAD_EXAMPLES).action(async (_options, invoked) => {
|
|
1495
|
+
const context = contextFor(invoked);
|
|
1496
|
+
if (context === void 0) return;
|
|
1497
|
+
const options = v4.parse(downloadOptionsSchema, invoked.opts());
|
|
1498
|
+
recordExitCode(await runCommand(context, () => downloadOne(context, options)));
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// src/folder-upload-command.ts
|
|
1503
|
+
import { stat as stat2 } from "node:fs/promises";
|
|
1504
|
+
import { resolve as resolve4 } from "node:path";
|
|
1505
|
+
import { describeError as describeError2, HimringApiError as HimringApiError3 } from "@himring/sdk";
|
|
1506
|
+
import {
|
|
1507
|
+
ATTEMPTS_PER_REQUEST,
|
|
1508
|
+
SYNC_CONCURRENCY_DEFAULT,
|
|
1509
|
+
SYNC_CONCURRENCY_MAXIMUM,
|
|
1510
|
+
syncFolder
|
|
1511
|
+
} from "@himring/sdk/folders";
|
|
1512
|
+
import { InvalidArgumentError, Option as Option5 } from "commander";
|
|
1513
|
+
import * as v5 from "valibot";
|
|
1514
|
+
var TARGET_OPERATION = "create_upload";
|
|
1515
|
+
var TARGET_FIELDS = ["project_id", "knowledge_base_id"];
|
|
1516
|
+
var MILLISECONDS_PER_SECOND = 1e3;
|
|
1517
|
+
var commandOptionsSchema2 = v5.object({
|
|
1518
|
+
project: v5.optional(v5.string()),
|
|
1519
|
+
knowledgeBase: v5.optional(v5.string()),
|
|
1520
|
+
folder: v5.optional(v5.string()),
|
|
1521
|
+
concurrency: v5.optional(v5.number()),
|
|
1522
|
+
dryRun: v5.optional(v5.boolean()),
|
|
1523
|
+
delete: v5.optional(v5.boolean()),
|
|
1524
|
+
yes: v5.optional(v5.boolean())
|
|
1525
|
+
});
|
|
1526
|
+
var UPLOAD_EXAMPLES = `
|
|
1527
|
+
Examples:
|
|
1528
|
+
$ himring files upload --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --folder ./policies
|
|
1529
|
+
$ himring files upload --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --folder ./policies --dry-run --output json
|
|
1530
|
+
$ himring files upload --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --folder ./policies --delete --yes`;
|
|
1531
|
+
function retryReporter(context) {
|
|
1532
|
+
return (notice) => {
|
|
1533
|
+
const seconds = Math.max(1, Math.round(notice.delayMs / MILLISECONDS_PER_SECOND));
|
|
1534
|
+
context.io.writeStderr(
|
|
1535
|
+
`${describeError2(notice.error)} The CLI sends ${notice.path} again in ${seconds} s, as attempt ${notice.attempt + 1} of ${ATTEMPTS_PER_REQUEST}.
|
|
1536
|
+
`
|
|
1537
|
+
);
|
|
1538
|
+
};
|
|
1539
|
+
}
|
|
1540
|
+
function parseConcurrency(value) {
|
|
1541
|
+
const concurrency = wholeNumberInRangeOf(value, 1, SYNC_CONCURRENCY_MAXIMUM);
|
|
1542
|
+
if (concurrency !== void 0) return concurrency;
|
|
1543
|
+
throw new InvalidArgumentError(`Pass a whole number from 1 to ${SYNC_CONCURRENCY_MAXIMUM}.`);
|
|
1544
|
+
}
|
|
1545
|
+
function targetOf(options) {
|
|
1546
|
+
const { project, knowledgeBase } = options;
|
|
1547
|
+
const input = {
|
|
1548
|
+
...project === void 0 ? {} : { project_id: project },
|
|
1549
|
+
...knowledgeBase === void 0 ? {} : { knowledge_base_id: knowledgeBase }
|
|
1550
|
+
};
|
|
1551
|
+
checkInput(TARGET_OPERATION, input, "Pass --project and --knowledge-base.", TARGET_FIELDS);
|
|
1552
|
+
if (project === void 0 || knowledgeBase === void 0) {
|
|
1553
|
+
throw new UsageError("The command needs a project and a knowledge base.", "Pass --project and --knowledge-base.");
|
|
1554
|
+
}
|
|
1555
|
+
return { projectId: project, knowledgeBaseId: knowledgeBase };
|
|
1556
|
+
}
|
|
1557
|
+
function summaryOf(report) {
|
|
1558
|
+
const count = (outcome) => report.files.filter((file) => file.outcome === outcome).length;
|
|
1559
|
+
return {
|
|
1560
|
+
uploads: [
|
|
1561
|
+
...report.files.map((file) => ({
|
|
1562
|
+
path: file.path,
|
|
1563
|
+
outcome: file.outcome,
|
|
1564
|
+
size_bytes: file.sizeBytes ?? null,
|
|
1565
|
+
file_id: file.fileId ?? null,
|
|
1566
|
+
detail: file.failure?.message ?? null
|
|
1567
|
+
})),
|
|
1568
|
+
...report.ignored.map((entry) => ({
|
|
1569
|
+
path: entry.path,
|
|
1570
|
+
outcome: "ignored",
|
|
1571
|
+
size_bytes: null,
|
|
1572
|
+
file_id: null,
|
|
1573
|
+
detail: entry.reason
|
|
1574
|
+
}))
|
|
1575
|
+
],
|
|
1576
|
+
added: count("added"),
|
|
1577
|
+
new_versions: count("new_version"),
|
|
1578
|
+
unchanged: count("unchanged") + count("skipped"),
|
|
1579
|
+
planned: count("planned"),
|
|
1580
|
+
deleted: count("deleted"),
|
|
1581
|
+
planned_deletions: count("planned_deletion"),
|
|
1582
|
+
failed: count("failed"),
|
|
1583
|
+
not_sent: count("not_sent"),
|
|
1584
|
+
ignored: report.ignored.length,
|
|
1585
|
+
stopped_by: report.stoppedBy?.message ?? null
|
|
1586
|
+
};
|
|
1587
|
+
}
|
|
1588
|
+
function exitCodeOfStop(stop) {
|
|
1589
|
+
const kind = stop.status === void 0 ? "network" : "refused";
|
|
1590
|
+
return exitCodeForApiError(new HimringApiError3(kind, stop.message, { status: stop.status, code: stop.code }));
|
|
1591
|
+
}
|
|
1592
|
+
async function syncedReport(context, options, root) {
|
|
1593
|
+
const interrupted = new AbortController();
|
|
1594
|
+
const stopOnInterrupt = () => interrupted.abort();
|
|
1595
|
+
process.once("SIGINT", stopOnInterrupt);
|
|
1596
|
+
try {
|
|
1597
|
+
return await syncFolder({
|
|
1598
|
+
client: await signedInClient(context),
|
|
1599
|
+
...targetOf(options),
|
|
1600
|
+
root,
|
|
1601
|
+
concurrency: options.concurrency ?? SYNC_CONCURRENCY_DEFAULT,
|
|
1602
|
+
dryRun: options.dryRun === true,
|
|
1603
|
+
deleteMissing: options.delete === true,
|
|
1604
|
+
signal: interrupted.signal,
|
|
1605
|
+
onRetry: retryReporter(context)
|
|
1606
|
+
});
|
|
1607
|
+
} finally {
|
|
1608
|
+
process.off("SIGINT", stopOnInterrupt);
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
async function uploadFolder(context, options) {
|
|
1612
|
+
if (options.folder === void 0) throw new UsageError("The command needs a folder.", "Pass its path with --folder.");
|
|
1613
|
+
targetOf(options);
|
|
1614
|
+
const root = resolve4(options.folder);
|
|
1615
|
+
const details = await stat2(root).catch(() => void 0);
|
|
1616
|
+
if (details?.isDirectory() !== true) {
|
|
1617
|
+
throw new UsageError(`${options.folder} is not a folder that the CLI can read.`, "Pass a folder to --folder.");
|
|
1618
|
+
}
|
|
1619
|
+
if (options.delete === true && options.dryRun !== true && options.yes !== true) {
|
|
1620
|
+
throw new UsageError(
|
|
1621
|
+
"The upload deletes each file of the knowledge base that the folder no longer holds, so it needs your confirmation.",
|
|
1622
|
+
"Pass --yes to go ahead, or --dry-run to list those files first."
|
|
1623
|
+
);
|
|
1624
|
+
}
|
|
1625
|
+
const report = await syncedReport(context, options, root);
|
|
1626
|
+
const summary = summaryOf(report);
|
|
1627
|
+
if (report.stoppedBy !== void 0) {
|
|
1628
|
+
return new PartialResult(
|
|
1629
|
+
summary,
|
|
1630
|
+
{
|
|
1631
|
+
code: report.stoppedBy.code ?? "upload_stopped",
|
|
1632
|
+
message: `The upload stopped: ${report.stoppedBy.message}`,
|
|
1633
|
+
suggestion: "Fix the cause, then run the same command again. It skips the files already sent."
|
|
1634
|
+
},
|
|
1635
|
+
exitCodeOfStop(report.stoppedBy)
|
|
1636
|
+
);
|
|
1637
|
+
}
|
|
1638
|
+
if (summary.failed > 0) {
|
|
1639
|
+
return new PartialResult(
|
|
1640
|
+
summary,
|
|
1641
|
+
{
|
|
1642
|
+
code: "upload_partly_failed",
|
|
1643
|
+
message: `${summary.failed} of the files failed to send. Their rows give the reason.`,
|
|
1644
|
+
suggestion: "Fix those files, then run the same command again. It skips the files already sent."
|
|
1645
|
+
},
|
|
1646
|
+
EXIT_CODES.partialFailure
|
|
1647
|
+
);
|
|
1648
|
+
}
|
|
1649
|
+
return summary;
|
|
1650
|
+
}
|
|
1651
|
+
function addFolderUploadCommand(group, contextFor, recordExitCode) {
|
|
1652
|
+
addProjectOption(
|
|
1653
|
+
group.command("upload").description(
|
|
1654
|
+
"Send every file of a local folder that Himring reads, with its path inside the folder. Files whose content the knowledge base already holds are skipped, and hidden files, symbolic links, and files of other kinds stay local."
|
|
1655
|
+
)
|
|
1656
|
+
).addOption(new Option5("--knowledge-base <value>", "knowledge_base_id (required)")).requiredOption("--folder <path>", "the local folder to send").addOption(
|
|
1657
|
+
new Option5("--concurrency <number>", `how many files to send at once, from 1 to ${SYNC_CONCURRENCY_MAXIMUM}`).default(SYNC_CONCURRENCY_DEFAULT).argParser(parseConcurrency)
|
|
1658
|
+
).option(
|
|
1659
|
+
"--delete",
|
|
1660
|
+
"also delete each file of the knowledge base that the folder no longer holds, which you can restore until Himring purges it"
|
|
1661
|
+
).option("--yes", "confirm the deletions that --delete makes").option("--dry-run", "list the files that the upload would send or delete, without changing anything").addHelpText("after", UPLOAD_EXAMPLES).action(async (_options, invoked) => {
|
|
1662
|
+
const context = contextFor(invoked);
|
|
1663
|
+
if (context === void 0) return;
|
|
1664
|
+
const options = v5.parse(commandOptionsSchema2, invoked.opts());
|
|
1665
|
+
recordExitCode(await runCommand(context, () => uploadFolder(context, options)));
|
|
1666
|
+
});
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
// src/file-commands.ts
|
|
1670
|
+
var OPERATION3 = "create_upload";
|
|
1671
|
+
var ADDED_FILE_FIELDS = ["project_id", "knowledge_base_id", "path", "address", "metadata"];
|
|
1672
|
+
var commandOptionsSchema3 = v6.object({
|
|
1673
|
+
project: v6.optional(v6.string()),
|
|
1674
|
+
knowledgeBase: v6.optional(v6.string()),
|
|
1675
|
+
from: v6.optional(v6.string()),
|
|
1676
|
+
path: v6.optional(v6.string()),
|
|
1677
|
+
address: v6.optional(v6.string()),
|
|
1678
|
+
metadata: v6.optional(v6.string()),
|
|
1679
|
+
dryRun: v6.optional(v6.boolean())
|
|
1680
|
+
});
|
|
1681
|
+
var ADD_EXAMPLES = `
|
|
1682
|
+
Examples:
|
|
1683
|
+
$ himring files add --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --from ./refunds.pdf
|
|
1684
|
+
$ himring files add --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --from ./export/faq.html --path help/faq.html --address https://example.com/help/faq
|
|
1685
|
+
$ himring files add --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --from ./travel.pdf --path policies/travel.pdf --metadata '{"department": "finance"}'`;
|
|
1686
|
+
var INPUT_SUGGESTION = "Pass --project and --knowledge-base, --path with a relative path that ends in an extension that Himring reads, and --metadata as a JSON object of text values.";
|
|
1687
|
+
function isTextRecord(value) {
|
|
1688
|
+
return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
|
|
1689
|
+
}
|
|
1690
|
+
function metadataOf(text) {
|
|
1691
|
+
if (text === void 0) return void 0;
|
|
1692
|
+
let parsed;
|
|
1693
|
+
try {
|
|
1694
|
+
parsed = JSON.parse(text);
|
|
1695
|
+
} catch {
|
|
1696
|
+
throw new UsageError("--metadata is not valid JSON.", "Pass --metadata as a JSON object of text values.");
|
|
1697
|
+
}
|
|
1698
|
+
if (!isTextRecord(parsed)) {
|
|
1699
|
+
throw new UsageError(
|
|
1700
|
+
"--metadata must be one JSON object of text values.",
|
|
1701
|
+
'Pass labels such as {"region": "emea"}.'
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
1704
|
+
return parsed;
|
|
1705
|
+
}
|
|
1706
|
+
async function regularFileOf(path) {
|
|
1707
|
+
const absolutePath = resolve5(path);
|
|
1708
|
+
const details = await stat3(absolutePath).catch(() => void 0);
|
|
1709
|
+
if (details?.isFile() !== true) {
|
|
1710
|
+
throw new UsageError(`${path} is not a file that the CLI can read.`, "Pass the path of a readable file to --from.");
|
|
1711
|
+
}
|
|
1712
|
+
return { absolutePath, sizeBytes: details.size };
|
|
1713
|
+
}
|
|
1714
|
+
function definedFieldsOf2(input) {
|
|
1715
|
+
return Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0));
|
|
1716
|
+
}
|
|
1717
|
+
async function addOne(context, options) {
|
|
1718
|
+
if (options.from === void 0) throw new UsageError("The command needs a file.", "Pass its path with --from.");
|
|
1719
|
+
const local = await regularFileOf(options.from);
|
|
1720
|
+
const metadata = metadataOf(options.metadata);
|
|
1721
|
+
const path = options.path ?? basename(local.absolutePath);
|
|
1722
|
+
const input = definedFieldsOf2({
|
|
1723
|
+
project_id: options.project,
|
|
1724
|
+
knowledge_base_id: options.knowledgeBase,
|
|
1725
|
+
path,
|
|
1726
|
+
address: options.address,
|
|
1727
|
+
metadata
|
|
1728
|
+
});
|
|
1729
|
+
checkInput(OPERATION3, input, INPUT_SUGGESTION, ADDED_FILE_FIELDS);
|
|
1730
|
+
const { project_id: projectId, knowledge_base_id: knowledgeBaseId } = input;
|
|
1731
|
+
if (typeof projectId !== "string" || typeof knowledgeBaseId !== "string") {
|
|
1732
|
+
throw new UsageError("The command needs a project and a knowledge base.", INPUT_SUGGESTION);
|
|
1733
|
+
}
|
|
1734
|
+
if (options.dryRun === true) {
|
|
1735
|
+
const sent = { path, address: options.address, metadata, from: local.absolutePath, size_bytes: local.sizeBytes };
|
|
1736
|
+
return dryRunOf(OPERATION3, input, sent);
|
|
1737
|
+
}
|
|
1738
|
+
return uploadLocalFile({
|
|
1739
|
+
client: await signedInClient(context),
|
|
1740
|
+
projectId,
|
|
1741
|
+
knowledgeBaseId,
|
|
1742
|
+
absolutePath: local.absolutePath,
|
|
1743
|
+
path,
|
|
1744
|
+
address: options.address,
|
|
1745
|
+
metadata,
|
|
1746
|
+
onRetry: retryReporter(context)
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1749
|
+
function addFileCommands(program, contextFor, recordExitCode) {
|
|
1750
|
+
const group = program.commands.find((command) => command.name() === "files");
|
|
1751
|
+
if (group === void 0) throw new Error("The files commands need the files group.");
|
|
1752
|
+
addProjectOption(
|
|
1753
|
+
group.command("add").description(
|
|
1754
|
+
"Send one local file to a knowledge base. The CLI sends its bytes straight to storage through links that Himring signs for a few minutes. Himring skips the file when the knowledge base already holds the same content at that path, and keeps any other content as a new version."
|
|
1755
|
+
)
|
|
1756
|
+
).addOption(new Option6("--knowledge-base <value>", "knowledge_base_id (required)")).option("--from <path>", "the local file to send (required)").option("--path <value>", "its path inside the knowledge base, by default the name of the file").option("--address <value>", "the web address that a citation of this file links to").option(
|
|
1757
|
+
"--metadata <json>",
|
|
1758
|
+
"labels that a search can filter by, as a JSON object of text values, which replace the labels that the file had"
|
|
1759
|
+
).option("--dry-run", "check the input and show the request, without sending it").addHelpText("after", ADD_EXAMPLES).action(async (_options, invoked) => {
|
|
1760
|
+
const context = contextFor(invoked);
|
|
1761
|
+
if (context === void 0) return;
|
|
1762
|
+
const options = v6.parse(commandOptionsSchema3, invoked.opts());
|
|
1763
|
+
recordExitCode(await runCommand(context, () => addOne(context, options)));
|
|
1764
|
+
});
|
|
1765
|
+
addFolderUploadCommand(group, contextFor, recordExitCode);
|
|
1766
|
+
addFileDownloadCommand(group, contextFor, recordExitCode);
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
// src/index-record-file-commands.ts
|
|
1770
|
+
import { extname } from "node:path";
|
|
1771
|
+
import { HIMRING_OPERATION_CATALOGUE as HIMRING_OPERATION_CATALOGUE4 } from "@himring/sdk/catalogue";
|
|
1772
|
+
import { Option as Option7 } from "commander";
|
|
1773
|
+
import * as v7 from "valibot";
|
|
1774
|
+
var OPERATION4 = "import_index_records";
|
|
1775
|
+
var commandOptionsSchema4 = v7.object({
|
|
1776
|
+
project: v7.optional(v7.string()),
|
|
1777
|
+
index: v7.optional(v7.string()),
|
|
1778
|
+
from: v7.optional(v7.string()),
|
|
1779
|
+
format: v7.optional(v7.string()),
|
|
1780
|
+
dryRun: v7.optional(v7.boolean())
|
|
1781
|
+
});
|
|
1782
|
+
var FORMAT_OF_EXTENSION = /* @__PURE__ */ new Map([
|
|
1783
|
+
[".json", "json"],
|
|
1784
|
+
[".ndjson", "ndjson"],
|
|
1785
|
+
[".jsonl", "ndjson"],
|
|
1786
|
+
[".csv", "csv"]
|
|
1787
|
+
]);
|
|
1788
|
+
var IMPORT_EXAMPLES2 = `
|
|
1789
|
+
Examples:
|
|
1790
|
+
$ himring records import --index ix_8c4b2a0f1e3d5c7b9a8f6e4d2c0b1a3f --from articles.ndjson
|
|
1791
|
+
$ himring records import --index ix_8c4b2a0f1e3d5c7b9a8f6e4d2c0b1a3f --from articles.csv --output json
|
|
1792
|
+
|
|
1793
|
+
A JSON file holds a list of records, an NDJSON file holds one record on each line, and a CSV file starts with a header row of field names, where a dotted name such as author.name fills a nested field.`;
|
|
1794
|
+
function formatOf(options) {
|
|
1795
|
+
if (options.format !== void 0) return options.format;
|
|
1796
|
+
if (options.from === void 0) return void 0;
|
|
1797
|
+
const choices = choicesOf(OPERATION4, "format");
|
|
1798
|
+
const format = FORMAT_OF_EXTENSION.get(extname(options.from).toLowerCase());
|
|
1799
|
+
if (format === void 0 || !choices.includes(format)) {
|
|
1800
|
+
throw new UsageError(
|
|
1801
|
+
`The CLI cannot tell the format of ${options.from} from its extension.`,
|
|
1802
|
+
`Pass --format with one of ${choices.join(", ")}.`
|
|
1803
|
+
);
|
|
1804
|
+
}
|
|
1805
|
+
return format;
|
|
1806
|
+
}
|
|
1807
|
+
function addIndexRecordFileCommands(program, contextFor, recordExitCode) {
|
|
1808
|
+
const group = program.commands.find((command) => command.name() === "records");
|
|
1809
|
+
if (group === void 0) throw new Error("The import command needs the records group.");
|
|
1810
|
+
addProjectOption(group.command("import").description(HIMRING_OPERATION_CATALOGUE4[OPERATION4].summary)).addOption(new Option7("--index <value>", "index_id (required)")).requiredOption("--from <path>", "the local file of records, in JSON, NDJSON, or CSV").addOption(
|
|
1811
|
+
new Option7(
|
|
1812
|
+
"--format <value>",
|
|
1813
|
+
"the format of the file, by default from its extension: .json, .ndjson or .jsonl, or .csv"
|
|
1814
|
+
).choices(choicesOf(OPERATION4, "format"))
|
|
1815
|
+
).option("--dry-run", "check the input and show the request, without sending it").addHelpText("after", IMPORT_EXAMPLES2).action(async (_options, invoked) => {
|
|
1816
|
+
const context = contextFor(invoked);
|
|
1817
|
+
if (context === void 0) return;
|
|
1818
|
+
const options = v7.parse(commandOptionsSchema4, invoked.opts());
|
|
1819
|
+
recordExitCode(
|
|
1820
|
+
await runCommand(
|
|
1821
|
+
context,
|
|
1822
|
+
() => sendFileBody(context, {
|
|
1823
|
+
id: OPERATION4,
|
|
1824
|
+
input: { project_id: options.project, index_id: options.index, format: formatOf(options) },
|
|
1825
|
+
from: options.from,
|
|
1826
|
+
dryRun: options.dryRun === true,
|
|
1827
|
+
suggestion: "Pass --project and --index.",
|
|
1828
|
+
splitHint: "Split the records into several files and import each one."
|
|
1829
|
+
})
|
|
1830
|
+
)
|
|
1831
|
+
);
|
|
1832
|
+
});
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
// src/operation-commands.ts
|
|
1836
|
+
import { HIMRING_OPERATIONS as HIMRING_OPERATIONS3 } from "@himring/sdk";
|
|
1837
|
+
import { HIMRING_OPERATION_CATALOGUE as HIMRING_OPERATION_CATALOGUE5 } from "@himring/sdk/catalogue";
|
|
1838
|
+
|
|
1839
|
+
// src/operation-fields.ts
|
|
1840
|
+
import { InvalidArgumentError as InvalidArgumentError2, Option as Option8 } from "commander";
|
|
1841
|
+
|
|
1842
|
+
// src/field-hints.ts
|
|
1843
|
+
var PARSED_DEFAULT_KEYWORD = "x-himring-parsed-default";
|
|
1844
|
+
function optionsOf(schema) {
|
|
1845
|
+
return Array.isArray(schema.anyOf) ? schema.anyOf.filter(isRecord) : [];
|
|
1846
|
+
}
|
|
1847
|
+
function enumChoicesOf(schema) {
|
|
1848
|
+
if (Array.isArray(schema.enum)) return schema.enum.map(String);
|
|
1849
|
+
for (const option of optionsOf(schema)) {
|
|
1850
|
+
const found = enumChoicesOf(option);
|
|
1851
|
+
if (found.length > 0) return found;
|
|
1852
|
+
}
|
|
1853
|
+
return [];
|
|
1854
|
+
}
|
|
1855
|
+
function choicesOf2(schema) {
|
|
1856
|
+
const direct = enumChoicesOf(schema);
|
|
1857
|
+
if (direct.length > 0) return { choices: direct, manyChoices: false };
|
|
1858
|
+
if (schema.type === "array" && isRecord(schema.items)) {
|
|
1859
|
+
const listed = enumChoicesOf(schema.items);
|
|
1860
|
+
if (listed.length > 0) return { choices: listed, manyChoices: true };
|
|
1861
|
+
}
|
|
1862
|
+
const rules = specRulesOf(schema);
|
|
1863
|
+
const picklist2 = rules.find((rule) => rule.kind === "picklist");
|
|
1864
|
+
const choices = picklist2 === void 0 ? [] : picklistChoicesOf(picklist2);
|
|
1865
|
+
return { choices, manyChoices: choices.length > 0 && isListRules(rules) };
|
|
1866
|
+
}
|
|
1867
|
+
function fallbackOf(schema) {
|
|
1868
|
+
const fallback = schema.default ?? schema[PARSED_DEFAULT_KEYWORD];
|
|
1869
|
+
if (!isScalar(fallback) || fallback === void 0 || fallback === null || fallback === "") return void 0;
|
|
1870
|
+
return String(fallback);
|
|
1871
|
+
}
|
|
1872
|
+
function fieldHintOf(schema) {
|
|
1873
|
+
return { ...choicesOf2(schema), fallback: fallbackOf(schema) };
|
|
1874
|
+
}
|
|
1875
|
+
function hintText(hint) {
|
|
1876
|
+
const parts = [];
|
|
1877
|
+
if (hint.choices.length > 0) {
|
|
1878
|
+
const listed = hint.choices.join(", ");
|
|
1879
|
+
parts.push(hint.manyChoices ? `any of ${listed}, separated by commas` : `one of ${listed}`);
|
|
1880
|
+
}
|
|
1881
|
+
if (hint.fallback !== void 0) parts.push(`default ${hint.fallback}`);
|
|
1882
|
+
return parts.length === 0 ? "" : ` (${parts.join("; ")})`;
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
// src/operation-fields.ts
|
|
1886
|
+
var TEXT_FILE_FIELDS = /* @__PURE__ */ new Map([
|
|
1887
|
+
["sql", "verbatim"],
|
|
1888
|
+
["token", "trimmed"]
|
|
1889
|
+
]);
|
|
1890
|
+
var ID_SUFFIX = "_id";
|
|
1891
|
+
var PROJECT_FIELD = "project_id";
|
|
1892
|
+
var PROJECT_VARIABLE2 = "HIMRING_PROJECT";
|
|
1893
|
+
var INPUT_FILE_ATTRIBUTE = "inputFile";
|
|
1894
|
+
var LIST_SEPARATOR2 = ",";
|
|
1895
|
+
function kebab(name) {
|
|
1896
|
+
return name.replaceAll("_", "-");
|
|
1897
|
+
}
|
|
1898
|
+
function camel(flag) {
|
|
1899
|
+
return flag.replace(/-([a-z0-9])/g, (_, letter) => letter.toUpperCase());
|
|
1900
|
+
}
|
|
1901
|
+
function optionsOf2(schema) {
|
|
1902
|
+
return Array.isArray(schema.anyOf) ? schema.anyOf.filter(isRecord) : [];
|
|
1903
|
+
}
|
|
1904
|
+
function isNullSchema(schema) {
|
|
1905
|
+
return schema.type === "null";
|
|
1906
|
+
}
|
|
1907
|
+
function isObjectSchema(schema) {
|
|
1908
|
+
if (schema.type === "object") return true;
|
|
1909
|
+
const options = optionsOf2(schema);
|
|
1910
|
+
return options.length > 0 && options.every(isObjectSchema);
|
|
1911
|
+
}
|
|
1912
|
+
function kindOfAnyOf(options) {
|
|
1913
|
+
const present = options.filter((option) => !isNullSchema(option));
|
|
1914
|
+
const [only] = present;
|
|
1915
|
+
if (only !== void 0 && present.length === 1) {
|
|
1916
|
+
const kind = kindOf(only);
|
|
1917
|
+
if (present.length === options.length) return kind;
|
|
1918
|
+
return kind === "json" || kind === "list" ? "json" : "scalar";
|
|
1919
|
+
}
|
|
1920
|
+
return present.length > 0 && present.every(isObjectSchema) ? "json" : "scalar";
|
|
1921
|
+
}
|
|
1922
|
+
function kindOf(schema) {
|
|
1923
|
+
const options = optionsOf2(schema);
|
|
1924
|
+
if (options.length > 0) return kindOfAnyOf(options);
|
|
1925
|
+
if (schema.type === "boolean") return "boolean";
|
|
1926
|
+
if (schema.type === "array") {
|
|
1927
|
+
return isRecord(schema.items) && schema.items.type === "string" && schema.items.enum === void 0 ? "list" : "json";
|
|
1928
|
+
}
|
|
1929
|
+
return schema.type === "object" ? "json" : "scalar";
|
|
1930
|
+
}
|
|
1931
|
+
function helpOf(name, schema, kind, required2) {
|
|
1932
|
+
if (kind === "json") return `read ${name} as JSON from a file, or - for stdin${required2 ? " (required)" : ""}`;
|
|
1933
|
+
const shape = kind === "list" ? ", separated by commas" : kind === "boolean" ? " (true or false)" : "";
|
|
1934
|
+
const hint = hintText(fieldHintOf(schema));
|
|
1935
|
+
const description = typeof schema.description === "string" ? `: ${schema.description}` : "";
|
|
1936
|
+
return `${name}${required2 ? " (required)" : ""}${shape}${hint}${description}`;
|
|
1937
|
+
}
|
|
1938
|
+
function fieldOptionsOf(id) {
|
|
1939
|
+
const required2 = requiredInputsOf(id);
|
|
1940
|
+
return Object.entries(inputPropertiesOf(id)).map(([name, schema]) => {
|
|
1941
|
+
const kind = kindOf(schema);
|
|
1942
|
+
const flag = kebab(name.endsWith(ID_SUFFIX) ? name.slice(0, -ID_SUFFIX.length) : name);
|
|
1943
|
+
const optionFlag = kind === "json" ? `${flag}-file` : flag;
|
|
1944
|
+
return {
|
|
1945
|
+
name,
|
|
1946
|
+
flag: optionFlag,
|
|
1947
|
+
attribute: camel(optionFlag),
|
|
1948
|
+
kind,
|
|
1949
|
+
required: required2.has(name),
|
|
1950
|
+
help: helpOf(name, schema, kind, required2.has(name)),
|
|
1951
|
+
textFile: TEXT_FILE_FIELDS.get(name)
|
|
1952
|
+
};
|
|
1953
|
+
});
|
|
1954
|
+
}
|
|
1955
|
+
function parseBoolean(value) {
|
|
1956
|
+
if (value === "true") return true;
|
|
1957
|
+
if (value === "false") return false;
|
|
1958
|
+
throw new InvalidArgumentError2("Pass true or false.");
|
|
1959
|
+
}
|
|
1960
|
+
function parseList(value) {
|
|
1961
|
+
return value.split(LIST_SEPARATOR2).map((item) => item.trim()).filter((item) => item.length > 0);
|
|
1962
|
+
}
|
|
1963
|
+
function textFileAttributeOf(field) {
|
|
1964
|
+
return camel(`${field.flag}-file`);
|
|
1965
|
+
}
|
|
1966
|
+
function addFieldOptions(command, fields) {
|
|
1967
|
+
for (const field of fields) {
|
|
1968
|
+
const placeholder = field.kind === "json" ? "<path>" : "<value>";
|
|
1969
|
+
const option = new Option8(`--${field.flag} ${placeholder}`, field.help);
|
|
1970
|
+
if (field.kind === "boolean") option.argParser(parseBoolean);
|
|
1971
|
+
if (field.kind === "list") option.argParser(parseList);
|
|
1972
|
+
if (field.name === PROJECT_FIELD) option.env(PROJECT_VARIABLE2);
|
|
1973
|
+
command.addOption(option);
|
|
1974
|
+
if (field.textFile !== void 0) {
|
|
1975
|
+
command.addOption(new Option8(`--${field.flag}-file <path>`, `read ${field.name} from a file, or - for stdin`));
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
async function inputFrom(context, fields, options) {
|
|
1980
|
+
const input = {};
|
|
1981
|
+
const inputFile = options[INPUT_FILE_ATTRIBUTE];
|
|
1982
|
+
if (typeof inputFile === "string") {
|
|
1983
|
+
const whole = await readJsonSource(context, inputFile, "the input");
|
|
1984
|
+
if (!isRecord(whole)) throw new UsageError("The input file must hold one JSON object.", "Wrap the fields in { }.");
|
|
1985
|
+
for (const [name, value] of Object.entries(whole))
|
|
1986
|
+
Object.defineProperty(input, name, { value, enumerable: true, writable: true, configurable: true });
|
|
1987
|
+
}
|
|
1988
|
+
for (const field of fields) {
|
|
1989
|
+
const value = options[field.attribute];
|
|
1990
|
+
const textFile = field.textFile === void 0 ? void 0 : options[textFileAttributeOf(field)];
|
|
1991
|
+
if (typeof textFile === "string") {
|
|
1992
|
+
const text = await readTextSource(context, textFile, field.name);
|
|
1993
|
+
input[field.name] = field.textFile === "trimmed" ? text.trim() : text;
|
|
1994
|
+
} else if (field.kind === "json" && typeof value === "string") {
|
|
1995
|
+
input[field.name] = await readJsonSource(context, value, field.name);
|
|
1996
|
+
} else if (value !== void 0) input[field.name] = value;
|
|
1997
|
+
}
|
|
1998
|
+
return input;
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
// src/database-workspace-specs.ts
|
|
2002
|
+
var DATABASE_WORKSPACE_RESOURCE_DESCRIPTIONS = {
|
|
2003
|
+
tables: "List the tables and views of a database, with their columns, keys, and indexes, and create a table through a migration that Himring writes.",
|
|
2004
|
+
rows: "Read, add, change, and delete the rows of a table.",
|
|
2005
|
+
sql: "Run SQL against a database, and confirm the statements that change rows when the database has the write preview on.",
|
|
2006
|
+
"saved-queries": "Save, list, and delete the queries that the members of a project keep for a database.",
|
|
2007
|
+
"change-proposals": "Turn a plain request into a migration for review.",
|
|
2008
|
+
columns: "Add, rename, retype, and drop the columns of a table, and change NOT NULL and defaults, through a migration that Himring writes.",
|
|
2009
|
+
imports: "Upload a CSV or XLSX file, check every row against a table, and insert the passing rows in one transaction."
|
|
2010
|
+
};
|
|
2011
|
+
var DB = "--database db_3a9e5c7b1d2f4e6a8c0b9d7f5e3a1c2b";
|
|
2012
|
+
var TABLE = "--table-name orders";
|
|
2013
|
+
var IMPORT = "--import 9f2c4e6a8b0d1f3e5a7c9b1d3f5e7a9c";
|
|
2014
|
+
var DATABASE_WORKSPACE_COMMANDS = {
|
|
2015
|
+
list_database_tables: {
|
|
2016
|
+
resource: "tables",
|
|
2017
|
+
verb: "list",
|
|
2018
|
+
examples: [`himring tables list ${DB}`, `himring tables list ${DB} --output json`]
|
|
2019
|
+
},
|
|
2020
|
+
list_table_rows: {
|
|
2021
|
+
resource: "rows",
|
|
2022
|
+
verb: "list",
|
|
2023
|
+
examples: [
|
|
2024
|
+
`himring rows list ${DB} ${TABLE}`,
|
|
2025
|
+
`himring rows list ${DB} ${TABLE} --filters-file filters.json --sorts-file sorts.json --page-size 50 --output json`
|
|
2026
|
+
]
|
|
2027
|
+
},
|
|
2028
|
+
get_table_row: {
|
|
2029
|
+
resource: "rows",
|
|
2030
|
+
verb: "get",
|
|
2031
|
+
examples: [`echo '[42]' | himring rows get ${DB} ${TABLE} --key-file -`]
|
|
2032
|
+
},
|
|
2033
|
+
insert_table_row: {
|
|
2034
|
+
resource: "rows",
|
|
2035
|
+
verb: "add",
|
|
2036
|
+
examples: [`echo '{"customer_id":1042,"total":120}' | himring rows add ${DB} ${TABLE} --values-file -`]
|
|
2037
|
+
},
|
|
2038
|
+
update_table_row: {
|
|
2039
|
+
resource: "rows",
|
|
2040
|
+
verb: "update",
|
|
2041
|
+
confirm: true,
|
|
2042
|
+
examples: [`himring rows update ${DB} ${TABLE} --input-file change.json --yes`]
|
|
2043
|
+
},
|
|
2044
|
+
delete_table_rows: {
|
|
2045
|
+
resource: "rows",
|
|
2046
|
+
verb: "delete",
|
|
2047
|
+
confirm: true,
|
|
2048
|
+
examples: [`echo '[[42],[43]]' | himring rows delete ${DB} ${TABLE} --keys-file - --yes`]
|
|
2049
|
+
},
|
|
2050
|
+
run_database_sql: {
|
|
2051
|
+
resource: "sql",
|
|
2052
|
+
verb: "run",
|
|
2053
|
+
examples: [
|
|
2054
|
+
`himring sql run ${DB} --sql "SELECT status, count(*) FROM orders GROUP BY status"`,
|
|
2055
|
+
`himring sql run ${DB} --sql "UPDATE orders SET status = 'shipped' WHERE id = 42"`,
|
|
2056
|
+
`himring sql run ${DB} --sql-file archive.sql --confirmation-token "$TOKEN" --output json`
|
|
2057
|
+
]
|
|
2058
|
+
},
|
|
2059
|
+
list_saved_queries: {
|
|
2060
|
+
resource: "saved-queries",
|
|
2061
|
+
verb: "list",
|
|
2062
|
+
examples: [`himring saved-queries list ${DB}`, `himring saved-queries list ${DB} --output json`]
|
|
2063
|
+
},
|
|
2064
|
+
save_query: {
|
|
2065
|
+
resource: "saved-queries",
|
|
2066
|
+
verb: "save",
|
|
2067
|
+
examples: [`himring saved-queries save ${DB} --name "Open orders" --sql-file open-orders.sql`]
|
|
2068
|
+
},
|
|
2069
|
+
delete_saved_query: {
|
|
2070
|
+
resource: "saved-queries",
|
|
2071
|
+
verb: "delete",
|
|
2072
|
+
confirm: true,
|
|
2073
|
+
examples: [`himring saved-queries delete ${DB} --saved-query sql_5c1e9a3b7d2f4e6a8c0b9d7f5e3a1c2b --yes`]
|
|
2074
|
+
},
|
|
2075
|
+
propose_database_change: {
|
|
2076
|
+
resource: "change-proposals",
|
|
2077
|
+
verb: "create",
|
|
2078
|
+
examples: [
|
|
2079
|
+
`himring change-proposals create ${DB} --request "Add a delivered_at column to orders"`,
|
|
2080
|
+
`himring change-proposals create ${DB} --request "Split customers.name into first and last names" --output json`
|
|
2081
|
+
]
|
|
2082
|
+
},
|
|
2083
|
+
preview_table_column_changes: {
|
|
2084
|
+
resource: "columns",
|
|
2085
|
+
verb: "preview",
|
|
2086
|
+
examples: [
|
|
2087
|
+
`echo '[{"kind":"alter","column":"total","type":"real"}]' | himring columns preview ${DB} ${TABLE} --changes-file -`,
|
|
2088
|
+
`himring columns preview ${DB} ${TABLE} --changes-file changes.json --output json`
|
|
2089
|
+
]
|
|
2090
|
+
},
|
|
2091
|
+
change_table_columns: {
|
|
2092
|
+
resource: "columns",
|
|
2093
|
+
verb: "change",
|
|
2094
|
+
confirm: true,
|
|
2095
|
+
examples: [
|
|
2096
|
+
`echo '[{"kind":"add","name":"delivered_at","type":"datetime"}]' | himring columns change ${DB} ${TABLE} --changes-file - --expected-migration-version 4 --yes`
|
|
2097
|
+
]
|
|
2098
|
+
},
|
|
2099
|
+
preview_create_table: {
|
|
2100
|
+
resource: "tables",
|
|
2101
|
+
verb: "preview",
|
|
2102
|
+
examples: [
|
|
2103
|
+
`echo '[{"name":"id","type":"integer","primary_key":true},{"name":"email","type":"text","not_null":true,"unique":true}]' | himring tables preview ${DB} --table-name customers --columns-file -`
|
|
2104
|
+
]
|
|
2105
|
+
},
|
|
2106
|
+
create_table: {
|
|
2107
|
+
resource: "tables",
|
|
2108
|
+
verb: "create",
|
|
2109
|
+
examples: [
|
|
2110
|
+
`himring tables create ${DB} --table-name customers --columns-file columns.json --expected-migration-version 3`,
|
|
2111
|
+
`himring tables create ${DB} --table-name customers --columns-file columns.json --expected-migration-version 3 --output json`
|
|
2112
|
+
]
|
|
2113
|
+
},
|
|
2114
|
+
export_table_rows: {
|
|
2115
|
+
resource: "rows",
|
|
2116
|
+
verb: "export",
|
|
2117
|
+
examples: [
|
|
2118
|
+
`himring rows export ${DB} ${TABLE} --format csv --out orders.csv`,
|
|
2119
|
+
`echo '[{"column":"status","operator":"eq","value":"open"}]' | himring rows export ${DB} ${TABLE} --format sql --filters-file -`
|
|
2120
|
+
]
|
|
2121
|
+
},
|
|
2122
|
+
check_table_import: {
|
|
2123
|
+
resource: "imports",
|
|
2124
|
+
verb: "check",
|
|
2125
|
+
examples: [
|
|
2126
|
+
`echo '[{"source_index":0,"column_name":"id"},{"source_index":1,"column_name":"status"}]' | himring imports check ${DB} ${IMPORT} ${TABLE} --columns-file -`
|
|
2127
|
+
]
|
|
2128
|
+
},
|
|
2129
|
+
apply_table_import: {
|
|
2130
|
+
resource: "imports",
|
|
2131
|
+
verb: "apply",
|
|
2132
|
+
examples: [
|
|
2133
|
+
`himring imports apply ${DB} ${IMPORT} ${TABLE} --columns-file columns.json --expected-failed 0 --expected-migration-version 4`
|
|
2134
|
+
]
|
|
2135
|
+
},
|
|
2136
|
+
discard_table_import: {
|
|
2137
|
+
resource: "imports",
|
|
2138
|
+
verb: "discard",
|
|
2139
|
+
examples: [`himring imports discard ${DB} ${IMPORT}`]
|
|
2140
|
+
}
|
|
2141
|
+
};
|
|
2142
|
+
|
|
2143
|
+
// src/flagged-question-specs.ts
|
|
2144
|
+
var FLAGGED_QUESTION_RESOURCE_DESCRIPTIONS = {
|
|
2145
|
+
"answer-events": "Send what your agent answered, the follow-up, thumbs-downs, and handoffs for each search.",
|
|
2146
|
+
"flagged-questions": "Read the likely wrong answers from live traffic, choose the passage for an unsure one, and start a review."
|
|
2147
|
+
};
|
|
2148
|
+
var KB = "--knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f";
|
|
2149
|
+
var QUESTION = "--question qst_6d8f0a2c4e1b3d5f7a9c0e2b4d6f8a1c";
|
|
2150
|
+
var FLAGGED_QUESTION_COMMANDS = {
|
|
2151
|
+
record_answer_events: {
|
|
2152
|
+
resource: "answer-events",
|
|
2153
|
+
verb: "record",
|
|
2154
|
+
examples: [
|
|
2155
|
+
`echo '[{"question_id":"qst_6d8f0a2c4e1b3d5f7a9c0e2b4d6f8a1c","answer":"Refunds take 5 days."}]' | himring answer-events record ${KB} --events-file -`,
|
|
2156
|
+
`himring answer-events record ${KB} --origin sdk --events-file events.json --output json`
|
|
2157
|
+
]
|
|
2158
|
+
},
|
|
2159
|
+
list_flagged_questions: {
|
|
2160
|
+
resource: "flagged-questions",
|
|
2161
|
+
verb: "list",
|
|
2162
|
+
examples: [
|
|
2163
|
+
`himring flagged-questions list ${KB} --status unsure`,
|
|
2164
|
+
`himring flagged-questions list ${KB} --status unanswerable,saved --limit 20 --output json`
|
|
2165
|
+
]
|
|
2166
|
+
},
|
|
2167
|
+
get_flagged_question: {
|
|
2168
|
+
resource: "flagged-questions",
|
|
2169
|
+
verb: "get",
|
|
2170
|
+
examples: [
|
|
2171
|
+
`himring flagged-questions get ${KB} ${QUESTION}`,
|
|
2172
|
+
`himring flagged-questions get ${KB} ${QUESTION} --output json`
|
|
2173
|
+
]
|
|
2174
|
+
},
|
|
2175
|
+
settle_flagged_question: {
|
|
2176
|
+
resource: "flagged-questions",
|
|
2177
|
+
verb: "settle",
|
|
2178
|
+
examples: [
|
|
2179
|
+
`himring flagged-questions settle ${KB} ${QUESTION} --chunk chk_2b4d6f8a0c1e3a5c7e9b8d6f4a2c0e1b`,
|
|
2180
|
+
`himring flagged-questions settle ${KB} ${QUESTION} --file fil_0a1b2c3d4e5f60718293a4b5c6d7e8f9 --first-position 12 --last-position 14 --output json`
|
|
2181
|
+
]
|
|
2182
|
+
},
|
|
2183
|
+
dismiss_flagged_question: {
|
|
2184
|
+
resource: "flagged-questions",
|
|
2185
|
+
verb: "dismiss",
|
|
2186
|
+
confirm: true,
|
|
2187
|
+
examples: [
|
|
2188
|
+
`himring flagged-questions dismiss ${KB} ${QUESTION} --yes`,
|
|
2189
|
+
`himring flagged-questions dismiss ${KB} ${QUESTION} --dry-run`
|
|
2190
|
+
]
|
|
2191
|
+
},
|
|
2192
|
+
review_flagged_questions: {
|
|
2193
|
+
resource: "flagged-questions",
|
|
2194
|
+
verb: "review",
|
|
2195
|
+
examples: [`himring flagged-questions review ${KB}`, `himring flagged-questions review ${KB} --output json`]
|
|
2196
|
+
}
|
|
2197
|
+
};
|
|
2198
|
+
|
|
2199
|
+
// src/index-record-specs.ts
|
|
2200
|
+
var INDEX_RECORD_RESOURCE_DESCRIPTIONS = {
|
|
2201
|
+
records: "List, read, write, delete, and import the records of a search index."
|
|
2202
|
+
};
|
|
2203
|
+
var INDEX = "--index ix_8c4b2a0f1e3d5c7b9a8f6e4d2c0b1a3f";
|
|
2204
|
+
var INDEX_RECORD_COMMANDS = {
|
|
2205
|
+
update_index: {
|
|
2206
|
+
resource: "indexes",
|
|
2207
|
+
verb: "update",
|
|
2208
|
+
examples: [
|
|
2209
|
+
`himring indexes update ${INDEX} --language french`,
|
|
2210
|
+
`himring indexes update ${INDEX} --bm25-file bm25.json --synonyms-file synonyms.json`,
|
|
2211
|
+
`himring indexes update ${INDEX} --stop-words-file stop-words.json`
|
|
2212
|
+
]
|
|
2213
|
+
},
|
|
2214
|
+
preview_index_search: {
|
|
2215
|
+
resource: "indexes",
|
|
2216
|
+
verb: "preview-search",
|
|
2217
|
+
examples: [
|
|
2218
|
+
`himring indexes preview-search ${INDEX} --query "refund policy"`,
|
|
2219
|
+
`himring indexes preview-search ${INDEX} --query refunds --mode keyword --output json`,
|
|
2220
|
+
`himring indexes preview-search ${INDEX} --query refunds --offset 20 --limit 20`,
|
|
2221
|
+
`himring indexes preview-search ${INDEX} --query "refnd polcy" --tolerance 2 --boosts title:3,body:1 --term-match all`,
|
|
2222
|
+
`himring indexes preview-search ${INDEX} --query refunds --group-by topic --group-size 2 --facet-ranges-file ranges.json`
|
|
2223
|
+
]
|
|
2224
|
+
},
|
|
2225
|
+
compare_index_search: {
|
|
2226
|
+
resource: "indexes",
|
|
2227
|
+
verb: "compare-search",
|
|
2228
|
+
examples: [
|
|
2229
|
+
`himring indexes compare-search ${INDEX} --query "refund policy" --boosts title:3`,
|
|
2230
|
+
`himring indexes compare-search ${INDEX} --query refunds --mode keyword --bm25-file bm25.json --output json`
|
|
2231
|
+
]
|
|
2232
|
+
},
|
|
2233
|
+
get_index_stats: {
|
|
2234
|
+
resource: "indexes",
|
|
2235
|
+
verb: "stats",
|
|
2236
|
+
examples: [`himring indexes stats ${INDEX}`, `himring indexes stats ${INDEX} --output json`]
|
|
2237
|
+
},
|
|
2238
|
+
suggest_index_terms: {
|
|
2239
|
+
resource: "indexes",
|
|
2240
|
+
verb: "suggest",
|
|
2241
|
+
examples: [
|
|
2242
|
+
`himring indexes suggest ${INDEX} --prefix refu`,
|
|
2243
|
+
`himring indexes suggest ${INDEX} --prefix ship --limit 5 --output json`
|
|
2244
|
+
]
|
|
2245
|
+
},
|
|
2246
|
+
list_index_records: {
|
|
2247
|
+
resource: "records",
|
|
2248
|
+
verb: "list",
|
|
2249
|
+
examples: [
|
|
2250
|
+
`himring records list ${INDEX} --search refunds`,
|
|
2251
|
+
`himring records list ${INDEX} --filters '{"fields":{"category":{"eq":"billing"}}}' --output json`
|
|
2252
|
+
]
|
|
2253
|
+
},
|
|
2254
|
+
export_index_records: {
|
|
2255
|
+
resource: "records",
|
|
2256
|
+
verb: "export",
|
|
2257
|
+
examples: [`himring records export ${INDEX}`, `himring records export ${INDEX} --out articles.ndjson --force`]
|
|
2258
|
+
},
|
|
2259
|
+
get_index_record: {
|
|
2260
|
+
resource: "records",
|
|
2261
|
+
verb: "get",
|
|
2262
|
+
examples: [
|
|
2263
|
+
`himring records get ${INDEX} --record article-1042`,
|
|
2264
|
+
`himring records get ${INDEX} --record article-1042 --output json`
|
|
2265
|
+
]
|
|
2266
|
+
},
|
|
2267
|
+
save_index_record: {
|
|
2268
|
+
resource: "records",
|
|
2269
|
+
verb: "save",
|
|
2270
|
+
examples: [
|
|
2271
|
+
`himring records save ${INDEX} --record article-1042 --record-file article.json`,
|
|
2272
|
+
`cat article.json | himring records save ${INDEX} --record article-1042 --record-file -`
|
|
2273
|
+
]
|
|
2274
|
+
},
|
|
2275
|
+
delete_index_record: {
|
|
2276
|
+
resource: "records",
|
|
2277
|
+
verb: "delete",
|
|
2278
|
+
confirm: true,
|
|
2279
|
+
examples: [
|
|
2280
|
+
`himring records delete ${INDEX} --record article-1042 --yes`,
|
|
2281
|
+
`himring records delete ${INDEX} --record article-1042 --dry-run`
|
|
2282
|
+
]
|
|
2283
|
+
}
|
|
2284
|
+
};
|
|
2285
|
+
|
|
2286
|
+
// src/knowledge-base-specs.ts
|
|
2287
|
+
var KNOWLEDGE_BASE_RESOURCE_DESCRIPTIONS = {
|
|
2288
|
+
"knowledge-bases": "Create, read, change, delete, restore, and search the knowledge bases of a project.",
|
|
2289
|
+
files: "Send files and folders to a knowledge base, and list, read, delete, and restore its files.",
|
|
2290
|
+
metadata: "List the metadata keys and values that the files of a knowledge base carry, to filter a search by.",
|
|
2291
|
+
questions: "List the questions that a knowledge base answered, with the passages that it returned.",
|
|
2292
|
+
"end-users": "Erase every question that one end user asked."
|
|
2293
|
+
};
|
|
2294
|
+
var KB2 = "--knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f";
|
|
2295
|
+
var FILE = "--file fil_0a1b2c3d4e5f60718293a4b5c6d7e8f9";
|
|
2296
|
+
var KNOWLEDGE_BASE_COMMANDS = {
|
|
2297
|
+
create_knowledge_base: {
|
|
2298
|
+
resource: "knowledge-bases",
|
|
2299
|
+
verb: "create",
|
|
2300
|
+
examples: [
|
|
2301
|
+
'himring knowledge-bases create --name "Support policies"',
|
|
2302
|
+
"himring knowledge-bases create --name Handbook --language french --chunk-tokens 800 --output json",
|
|
2303
|
+
'himring knowledge-bases create --name "Support policies" --question-log-retention-days 0'
|
|
2304
|
+
]
|
|
2305
|
+
},
|
|
2306
|
+
list_knowledge_bases: {
|
|
2307
|
+
resource: "knowledge-bases",
|
|
2308
|
+
verb: "list",
|
|
2309
|
+
examples: [
|
|
2310
|
+
"himring knowledge-bases list --search support --sort name --direction asc",
|
|
2311
|
+
"himring knowledge-bases list --state deleted --sort purge_after --direction asc --output json"
|
|
2312
|
+
]
|
|
2313
|
+
},
|
|
2314
|
+
get_knowledge_base: {
|
|
2315
|
+
resource: "knowledge-bases",
|
|
2316
|
+
verb: "get",
|
|
2317
|
+
examples: [`himring knowledge-bases get ${KB2}`, `himring knowledge-bases get ${KB2} --output json`]
|
|
2318
|
+
},
|
|
2319
|
+
update_knowledge_base: {
|
|
2320
|
+
resource: "knowledge-bases",
|
|
2321
|
+
verb: "update",
|
|
2322
|
+
confirm: true,
|
|
2323
|
+
examples: [
|
|
2324
|
+
`himring knowledge-bases update ${KB2} --question-log-retention-days 90 --yes`,
|
|
2325
|
+
`himring knowledge-bases update ${KB2} --question-log-retention-days unlimited --dry-run`
|
|
2326
|
+
]
|
|
2327
|
+
},
|
|
2328
|
+
delete_knowledge_base: {
|
|
2329
|
+
resource: "knowledge-bases",
|
|
2330
|
+
verb: "delete",
|
|
2331
|
+
confirm: true,
|
|
2332
|
+
examples: [`himring knowledge-bases delete ${KB2} --yes`, `himring knowledge-bases delete ${KB2} --dry-run`]
|
|
2333
|
+
},
|
|
2334
|
+
restore_knowledge_base: {
|
|
2335
|
+
resource: "knowledge-bases",
|
|
2336
|
+
verb: "restore",
|
|
2337
|
+
examples: [`himring knowledge-bases restore ${KB2}`, `himring knowledge-bases restore ${KB2} --output json`]
|
|
2338
|
+
},
|
|
2339
|
+
search_knowledge_base: {
|
|
2340
|
+
resource: "knowledge-bases",
|
|
2341
|
+
verb: "search",
|
|
2342
|
+
examples: [
|
|
2343
|
+
`himring knowledge-bases search ${KB2} --question "How long do refunds take?"`,
|
|
2344
|
+
`himring knowledge-bases search ${KB2} --question "Opening hours" --limit 3 --end-user customer-42 --output json`,
|
|
2345
|
+
`himring knowledge-bases search ${KB2} --question "Travel allowance" --folder policies/travel --metadata-file filter.json`
|
|
2346
|
+
]
|
|
2347
|
+
},
|
|
2348
|
+
answer_question: {
|
|
2349
|
+
resource: "knowledge-bases",
|
|
2350
|
+
verb: "answer",
|
|
2351
|
+
examples: [
|
|
2352
|
+
`himring knowledge-bases answer ${KB2} --question "How long do refunds take?"`,
|
|
2353
|
+
`himring knowledge-bases answer ${KB2} --question "Travel allowance" --folder policies/travel --output json`
|
|
2354
|
+
]
|
|
2355
|
+
},
|
|
2356
|
+
list_files: {
|
|
2357
|
+
resource: "files",
|
|
2358
|
+
verb: "list",
|
|
2359
|
+
examples: [
|
|
2360
|
+
`himring files list ${KB2} --status failed`,
|
|
2361
|
+
`himring files list ${KB2} --search policies/ --sort path --direction asc --output json`
|
|
2362
|
+
]
|
|
2363
|
+
},
|
|
2364
|
+
list_folder: {
|
|
2365
|
+
resource: "files",
|
|
2366
|
+
verb: "folder",
|
|
2367
|
+
examples: [
|
|
2368
|
+
`himring files folder ${KB2}`,
|
|
2369
|
+
`himring files folder ${KB2} --folder policies/travel --sort updated_at --direction desc --output json`
|
|
2370
|
+
]
|
|
2371
|
+
},
|
|
2372
|
+
search_folders: {
|
|
2373
|
+
resource: "files",
|
|
2374
|
+
verb: "folders",
|
|
2375
|
+
examples: [`himring files folders ${KB2}`, `himring files folders ${KB2} --search travel --output json`]
|
|
2376
|
+
},
|
|
2377
|
+
list_metadata_keys: {
|
|
2378
|
+
resource: "metadata",
|
|
2379
|
+
verb: "keys",
|
|
2380
|
+
examples: [`himring metadata keys ${KB2}`, `himring metadata keys ${KB2} --search reg --output json`]
|
|
2381
|
+
},
|
|
2382
|
+
list_metadata_values: {
|
|
2383
|
+
resource: "metadata",
|
|
2384
|
+
verb: "values",
|
|
2385
|
+
examples: [
|
|
2386
|
+
`himring metadata values ${KB2} --key region`,
|
|
2387
|
+
`himring metadata values ${KB2} --key region --search em --output json`
|
|
2388
|
+
]
|
|
2389
|
+
},
|
|
2390
|
+
get_file: {
|
|
2391
|
+
resource: "files",
|
|
2392
|
+
verb: "get",
|
|
2393
|
+
examples: [`himring files get ${KB2} ${FILE}`, `himring files get ${KB2} ${FILE} --output json`]
|
|
2394
|
+
},
|
|
2395
|
+
list_file_versions: {
|
|
2396
|
+
resource: "files",
|
|
2397
|
+
verb: "versions",
|
|
2398
|
+
examples: [
|
|
2399
|
+
`himring files versions ${KB2} ${FILE}`,
|
|
2400
|
+
`himring files versions ${KB2} ${FILE} --limit 20 --offset 20 --output json`
|
|
2401
|
+
]
|
|
2402
|
+
},
|
|
2403
|
+
list_version_blocks: {
|
|
2404
|
+
resource: "files",
|
|
2405
|
+
verb: "blocks",
|
|
2406
|
+
examples: [
|
|
2407
|
+
`himring files blocks ${KB2} ${FILE} --version 2`,
|
|
2408
|
+
`himring files blocks ${KB2} ${FILE} --version 2 --limit 200 --offset 200 --output json`,
|
|
2409
|
+
`himring files blocks ${KB2} ${FILE} --version 2 --sheet Rates --from-row 40 --limit 10`
|
|
2410
|
+
]
|
|
2411
|
+
},
|
|
2412
|
+
delete_file: {
|
|
2413
|
+
resource: "files",
|
|
2414
|
+
verb: "delete",
|
|
2415
|
+
confirm: true,
|
|
2416
|
+
examples: [`himring files delete ${KB2} ${FILE} --yes`, `himring files delete ${KB2} ${FILE} --dry-run`]
|
|
2417
|
+
},
|
|
2418
|
+
restore_file: {
|
|
2419
|
+
resource: "files",
|
|
2420
|
+
verb: "restore",
|
|
2421
|
+
examples: [`himring files restore ${KB2} ${FILE}`, `himring files restore ${KB2} ${FILE} --output json`]
|
|
2422
|
+
},
|
|
2423
|
+
get_download_link: {
|
|
2424
|
+
resource: "files",
|
|
2425
|
+
verb: "link",
|
|
2426
|
+
examples: [
|
|
2427
|
+
`himring files link ${KB2} ${FILE} --version 2`,
|
|
2428
|
+
`himring files link ${KB2} ${FILE} --version 1 --rendition pdf --disposition attachment --output json`
|
|
2429
|
+
]
|
|
2430
|
+
},
|
|
2431
|
+
list_questions: {
|
|
2432
|
+
resource: "questions",
|
|
2433
|
+
verb: "list",
|
|
2434
|
+
examples: [
|
|
2435
|
+
`himring questions list ${KB2} --search refund`,
|
|
2436
|
+
`himring questions list ${KB2} --end-user customer-42 --output json`
|
|
2437
|
+
]
|
|
2438
|
+
},
|
|
2439
|
+
erase_end_user: {
|
|
2440
|
+
resource: "end-users",
|
|
2441
|
+
verb: "erase",
|
|
2442
|
+
confirm: true,
|
|
2443
|
+
examples: [
|
|
2444
|
+
"himring end-users erase --end-user customer-42 --yes",
|
|
2445
|
+
"himring end-users erase --end-user customer-42 --dry-run"
|
|
2446
|
+
]
|
|
2447
|
+
}
|
|
2448
|
+
};
|
|
2449
|
+
|
|
2450
|
+
// src/memory-review-specs.ts
|
|
2451
|
+
var MEMORY_REVIEW_RESOURCE_DESCRIPTIONS = {
|
|
2452
|
+
"memory-decisions": "List the decisions that Himring applied to memories, settle a memory over any of them, forget or recover a memory, and send feedback on a recalled memory.",
|
|
2453
|
+
recall: "Recall memories for an agent with their labels, or read the context of one end user or team.",
|
|
2454
|
+
"memory-webhooks": "Set the endpoint that receives each applied decision as a signed event, read or remove it, and list its deliveries.",
|
|
2455
|
+
"memory-learning": "List what Himring learned from labeled decisions, undo a learned change, run tuning now, and read the scores of the Memory.",
|
|
2456
|
+
"memory-questions": "Save the questions that the recall score checks, list them, and delete them."
|
|
2457
|
+
};
|
|
2458
|
+
var MEMORY = "--memory mem_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f";
|
|
2459
|
+
var STORED = "--stored-memory mm_9b1d3f5a7c9e1b3d5f7a9c1e3b5d7f9a";
|
|
2460
|
+
var CHANGE = "--change lrn_5e7a9c1e3a5c7e9a1c3e5a7c9e1a3c5e";
|
|
2461
|
+
var SAVED = "--saved-question msq_8a0c2e4a6c8e0a2c4e6a8c0e2a4c6e8a";
|
|
2462
|
+
var RECALL = "--recall rcl_1b3d5f7a9c1e3b5d7f9a1c3e5b7d9f1a";
|
|
2463
|
+
var MEMORY_REVIEW_COMMANDS = {
|
|
2464
|
+
list_memory_decisions: {
|
|
2465
|
+
resource: "memory-decisions",
|
|
2466
|
+
verb: "list",
|
|
2467
|
+
examples: [
|
|
2468
|
+
`himring memory-decisions list ${MEMORY} --kind disputed,file_conflict`,
|
|
2469
|
+
`himring memory-decisions list ${MEMORY} --subject-owner billing-team --by-person true --output json`
|
|
2470
|
+
]
|
|
2471
|
+
},
|
|
2472
|
+
settle_memory: {
|
|
2473
|
+
resource: "memory-decisions",
|
|
2474
|
+
verb: "settle",
|
|
2475
|
+
confirm: true,
|
|
2476
|
+
examples: [
|
|
2477
|
+
`himring memory-decisions settle ${MEMORY} ${STORED} --trust-level confirmed --yes`,
|
|
2478
|
+
`himring memory-decisions settle ${MEMORY} ${STORED} --trust-level confirmed --over-file true --dry-run`
|
|
2479
|
+
]
|
|
2480
|
+
},
|
|
2481
|
+
forget_memory: {
|
|
2482
|
+
resource: "memory-decisions",
|
|
2483
|
+
verb: "forget",
|
|
2484
|
+
confirm: true,
|
|
2485
|
+
examples: [
|
|
2486
|
+
`himring memory-decisions forget ${MEMORY} ${STORED} --yes`,
|
|
2487
|
+
`himring memory-decisions forget ${MEMORY} ${STORED} --dry-run`
|
|
2488
|
+
]
|
|
2489
|
+
},
|
|
2490
|
+
recover_memory: {
|
|
2491
|
+
resource: "memory-decisions",
|
|
2492
|
+
verb: "recover",
|
|
2493
|
+
examples: [
|
|
2494
|
+
`himring memory-decisions recover ${MEMORY} ${STORED}`,
|
|
2495
|
+
`himring memory-decisions recover ${MEMORY} ${STORED} --output json`
|
|
2496
|
+
]
|
|
2497
|
+
},
|
|
2498
|
+
list_forgetting_suggestions: {
|
|
2499
|
+
resource: "memory-decisions",
|
|
2500
|
+
verb: "suggestions",
|
|
2501
|
+
examples: [
|
|
2502
|
+
`himring memory-decisions suggestions ${MEMORY}`,
|
|
2503
|
+
`himring memory-decisions suggestions ${MEMORY} --limit 50 --output json`
|
|
2504
|
+
]
|
|
2505
|
+
},
|
|
2506
|
+
send_memory_feedback: {
|
|
2507
|
+
resource: "memory-decisions",
|
|
2508
|
+
verb: "feedback",
|
|
2509
|
+
examples: [
|
|
2510
|
+
`himring memory-decisions feedback ${MEMORY} ${STORED} --verdict wrong ${RECALL}`,
|
|
2511
|
+
`himring memory-decisions feedback ${MEMORY} ${STORED} --verdict right --output json`
|
|
2512
|
+
]
|
|
2513
|
+
},
|
|
2514
|
+
recall_memories: {
|
|
2515
|
+
resource: "recall",
|
|
2516
|
+
verb: "search",
|
|
2517
|
+
examples: [
|
|
2518
|
+
`himring recall search ${MEMORY} --query "delivery address" --end-user customer-1042`,
|
|
2519
|
+
`himring recall search ${MEMORY} --query "returns window" --as-of 2026-10-01T09:00:00Z --output json`
|
|
2520
|
+
]
|
|
2521
|
+
},
|
|
2522
|
+
get_memory_context: {
|
|
2523
|
+
resource: "recall",
|
|
2524
|
+
verb: "context",
|
|
2525
|
+
examples: [
|
|
2526
|
+
`himring recall context ${MEMORY} --end-user customer-1042`,
|
|
2527
|
+
`himring recall context ${MEMORY} --team support-emea --agent billing-bot --output json`
|
|
2528
|
+
]
|
|
2529
|
+
},
|
|
2530
|
+
set_memory_webhook: {
|
|
2531
|
+
resource: "memory-webhooks",
|
|
2532
|
+
verb: "set",
|
|
2533
|
+
confirm: true,
|
|
2534
|
+
examples: [
|
|
2535
|
+
`himring memory-webhooks set ${MEMORY} --url https://example.com/himring/events --yes`,
|
|
2536
|
+
`himring memory-webhooks set ${MEMORY} --url https://example.com/himring/events --dry-run`
|
|
2537
|
+
]
|
|
2538
|
+
},
|
|
2539
|
+
get_memory_webhook: {
|
|
2540
|
+
resource: "memory-webhooks",
|
|
2541
|
+
verb: "get",
|
|
2542
|
+
examples: [`himring memory-webhooks get ${MEMORY}`, `himring memory-webhooks get ${MEMORY} --output json`]
|
|
2543
|
+
},
|
|
2544
|
+
remove_memory_webhook: {
|
|
2545
|
+
resource: "memory-webhooks",
|
|
2546
|
+
verb: "remove",
|
|
2547
|
+
confirm: true,
|
|
2548
|
+
examples: [`himring memory-webhooks remove ${MEMORY} --yes`, `himring memory-webhooks remove ${MEMORY} --dry-run`]
|
|
2549
|
+
},
|
|
2550
|
+
list_memory_webhook_deliveries: {
|
|
2551
|
+
resource: "memory-webhooks",
|
|
2552
|
+
verb: "deliveries",
|
|
2553
|
+
examples: [
|
|
2554
|
+
`himring memory-webhooks deliveries ${MEMORY} --state waiting,failed`,
|
|
2555
|
+
`himring memory-webhooks deliveries ${MEMORY} --output json`
|
|
2556
|
+
]
|
|
2557
|
+
},
|
|
2558
|
+
list_learned_changes: {
|
|
2559
|
+
resource: "memory-learning",
|
|
2560
|
+
verb: "list",
|
|
2561
|
+
examples: [`himring memory-learning list ${MEMORY}`, `himring memory-learning list ${MEMORY} --output json`]
|
|
2562
|
+
},
|
|
2563
|
+
undo_learned_change: {
|
|
2564
|
+
resource: "memory-learning",
|
|
2565
|
+
verb: "undo",
|
|
2566
|
+
confirm: true,
|
|
2567
|
+
examples: [
|
|
2568
|
+
`himring memory-learning undo ${MEMORY} ${CHANGE} --yes`,
|
|
2569
|
+
`himring memory-learning undo ${MEMORY} ${CHANGE} --dry-run`
|
|
2570
|
+
]
|
|
2571
|
+
},
|
|
2572
|
+
tune_memory: {
|
|
2573
|
+
resource: "memory-learning",
|
|
2574
|
+
verb: "tune",
|
|
2575
|
+
examples: [`himring memory-learning tune ${MEMORY}`, `himring memory-learning tune ${MEMORY} --output json`]
|
|
2576
|
+
},
|
|
2577
|
+
get_memory_scores: {
|
|
2578
|
+
resource: "memory-learning",
|
|
2579
|
+
verb: "scores",
|
|
2580
|
+
examples: [`himring memory-learning scores ${MEMORY}`, `himring memory-learning scores ${MEMORY} --output json`]
|
|
2581
|
+
},
|
|
2582
|
+
save_memory_question: {
|
|
2583
|
+
resource: "memory-questions",
|
|
2584
|
+
verb: "save",
|
|
2585
|
+
examples: [
|
|
2586
|
+
`himring memory-questions save ${MEMORY} ${STORED} --question "Where do I send returns?"`,
|
|
2587
|
+
`himring memory-questions save ${MEMORY} ${STORED} --question "What is my delivery address?" --end-user customer-1042 --output json`
|
|
2588
|
+
]
|
|
2589
|
+
},
|
|
2590
|
+
list_memory_saved_questions: {
|
|
2591
|
+
resource: "memory-questions",
|
|
2592
|
+
verb: "list",
|
|
2593
|
+
examples: [
|
|
2594
|
+
`himring memory-questions list ${MEMORY}`,
|
|
2595
|
+
`himring memory-questions list ${MEMORY} --flagged true --output json`
|
|
2596
|
+
]
|
|
2597
|
+
},
|
|
2598
|
+
delete_memory_saved_question: {
|
|
2599
|
+
resource: "memory-questions",
|
|
2600
|
+
verb: "delete",
|
|
2601
|
+
confirm: true,
|
|
2602
|
+
examples: [
|
|
2603
|
+
`himring memory-questions delete ${MEMORY} ${SAVED} --yes`,
|
|
2604
|
+
`himring memory-questions delete ${MEMORY} ${SAVED} --dry-run`
|
|
2605
|
+
]
|
|
2606
|
+
}
|
|
2607
|
+
};
|
|
2608
|
+
|
|
2609
|
+
// src/memory-specs.ts
|
|
2610
|
+
var MEMORY_RESOURCE_DESCRIPTIONS = {
|
|
2611
|
+
memory: "Turn on the Memory of a project, read how far it has sorted, change its thresholds, and delete or restore it.",
|
|
2612
|
+
memories: "List the memories that an agent may receive, inspect one with its sources and decisions, share a personal memory, sort a message without storing it, and export the memories as JSON.",
|
|
2613
|
+
"memory-reviews": "List the memories that wait for a person, and settle them.",
|
|
2614
|
+
"memory-owners": "List the end users and teams that the Memory holds memories for.",
|
|
2615
|
+
"memory-sources": "Connect your agents' conversations, your code, a database table, or a connected tool to the Memory, and sync, change, or disconnect them.",
|
|
2616
|
+
messages: "Send messages to an agent or push source of the Memory, list their receipts, and read one with the memories that it wrote."
|
|
2617
|
+
};
|
|
2618
|
+
var MEMORY2 = "--memory mem_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f";
|
|
2619
|
+
var STORED2 = "--stored-memory mm_9b1d3f5a7c9e1b3d5f7a9c1e3b5d7f9a";
|
|
2620
|
+
var REVIEW = "--review rev_2c4e6a8c0e2a4c6e8a0c2e4a6c8e0a2c";
|
|
2621
|
+
var SOURCE = "--source src_6d8f0a2c4e1b3d5f7a9c0e2b4d6f8a1c";
|
|
2622
|
+
var MEMORY_COMMANDS = {
|
|
2623
|
+
enable_memory: {
|
|
2624
|
+
resource: "memory",
|
|
2625
|
+
verb: "enable",
|
|
2626
|
+
examples: ["himring memory enable", "himring memory enable --language french --confidence-threshold 0.9"]
|
|
2627
|
+
},
|
|
2628
|
+
get_memory: {
|
|
2629
|
+
resource: "memory",
|
|
2630
|
+
verb: "get",
|
|
2631
|
+
examples: ["himring memory get", "himring memory get --state deleted --output json"]
|
|
2632
|
+
},
|
|
2633
|
+
update_memory: {
|
|
2634
|
+
resource: "memory",
|
|
2635
|
+
verb: "update",
|
|
2636
|
+
confirm: true,
|
|
2637
|
+
examples: [
|
|
2638
|
+
`himring memory update ${MEMORY2} --duplicate-threshold 0.85 --yes`,
|
|
2639
|
+
`himring memory update ${MEMORY2} --knowledge-base-choice listed --checked-knowledge-base-ids kb_4a6c8e0a2c4e6a8c0e2a4c6e8a0c2e4a,kb_7e9a1c3e5a7c9e1a3c5e7a9c1e3a5c7e --dry-run`
|
|
2640
|
+
]
|
|
2641
|
+
},
|
|
2642
|
+
delete_memory: {
|
|
2643
|
+
resource: "memory",
|
|
2644
|
+
verb: "delete",
|
|
2645
|
+
confirm: true,
|
|
2646
|
+
examples: [`himring memory delete ${MEMORY2} --yes`, `himring memory delete ${MEMORY2} --dry-run`]
|
|
2647
|
+
},
|
|
2648
|
+
restore_memory: {
|
|
2649
|
+
resource: "memory",
|
|
2650
|
+
verb: "restore",
|
|
2651
|
+
examples: [`himring memory restore ${MEMORY2}`, `himring memory restore ${MEMORY2} --output json`]
|
|
2652
|
+
},
|
|
2653
|
+
list_memories: {
|
|
2654
|
+
resource: "memories",
|
|
2655
|
+
verb: "list",
|
|
2656
|
+
examples: [
|
|
2657
|
+
`himring memories list ${MEMORY2} --end-user customer-1042 --query "delivery address"`,
|
|
2658
|
+
`himring memories list ${MEMORY2} --type plan --plan-state open,overdue --output json`
|
|
2659
|
+
]
|
|
2660
|
+
},
|
|
2661
|
+
inspect_memory: {
|
|
2662
|
+
resource: "memories",
|
|
2663
|
+
verb: "inspect",
|
|
2664
|
+
examples: [
|
|
2665
|
+
`himring memories inspect ${MEMORY2} ${STORED2}`,
|
|
2666
|
+
`himring memories inspect ${MEMORY2} ${STORED2} --output json`
|
|
2667
|
+
]
|
|
2668
|
+
},
|
|
2669
|
+
promote_memory: {
|
|
2670
|
+
resource: "memories",
|
|
2671
|
+
verb: "promote",
|
|
2672
|
+
confirm: true,
|
|
2673
|
+
examples: [
|
|
2674
|
+
`himring memories promote ${MEMORY2} ${STORED2} --scope company --yes`,
|
|
2675
|
+
`himring memories promote ${MEMORY2} ${STORED2} --scope team --team support-emea --dry-run`
|
|
2676
|
+
]
|
|
2677
|
+
},
|
|
2678
|
+
sort_message: {
|
|
2679
|
+
resource: "memories",
|
|
2680
|
+
verb: "sort",
|
|
2681
|
+
examples: [
|
|
2682
|
+
`himring memories sort ${MEMORY2} --text "Refunds now take 5 working days." --author "Head of support" --author-kind staff`,
|
|
2683
|
+
`himring memories sort ${MEMORY2} --text "I moved to Leeds." --author customer-1042 --author-kind end_user --end-user customer-1042 --output json`
|
|
2684
|
+
]
|
|
2685
|
+
},
|
|
2686
|
+
list_memory_reviews: {
|
|
2687
|
+
resource: "memory-reviews",
|
|
2688
|
+
verb: "list",
|
|
2689
|
+
examples: [
|
|
2690
|
+
`himring memory-reviews list ${MEMORY2}`,
|
|
2691
|
+
`himring memory-reviews list ${MEMORY2} --reason instruction_like,disputed --output json`
|
|
2692
|
+
]
|
|
2693
|
+
},
|
|
2694
|
+
settle_memory_review: {
|
|
2695
|
+
resource: "memory-reviews",
|
|
2696
|
+
verb: "settle",
|
|
2697
|
+
confirm: true,
|
|
2698
|
+
examples: [
|
|
2699
|
+
`himring memory-reviews settle ${MEMORY2} ${REVIEW} --trust-level confirmed --yes`,
|
|
2700
|
+
`himring memory-reviews settle ${MEMORY2} ${REVIEW} --trust-level not_kept --dry-run`
|
|
2701
|
+
]
|
|
2702
|
+
},
|
|
2703
|
+
create_memory_source: {
|
|
2704
|
+
resource: "memory-sources",
|
|
2705
|
+
verb: "create",
|
|
2706
|
+
examples: [
|
|
2707
|
+
`himring memory-sources create ${MEMORY2} --name "Support agent" --kind agent`,
|
|
2708
|
+
`himring memory-sources create ${MEMORY2} --name "Customers table" --kind database --settings-file table.json --output json`
|
|
2709
|
+
]
|
|
2710
|
+
},
|
|
2711
|
+
list_memory_sources: {
|
|
2712
|
+
resource: "memory-sources",
|
|
2713
|
+
verb: "list",
|
|
2714
|
+
examples: [
|
|
2715
|
+
`himring memory-sources list ${MEMORY2}`,
|
|
2716
|
+
`himring memory-sources list ${MEMORY2} --kind slack --output json`
|
|
2717
|
+
]
|
|
2718
|
+
},
|
|
2719
|
+
get_memory_source: {
|
|
2720
|
+
resource: "memory-sources",
|
|
2721
|
+
verb: "get",
|
|
2722
|
+
examples: [
|
|
2723
|
+
`himring memory-sources get ${MEMORY2} ${SOURCE}`,
|
|
2724
|
+
`himring memory-sources get ${MEMORY2} ${SOURCE} --output json`
|
|
2725
|
+
]
|
|
2726
|
+
},
|
|
2727
|
+
update_memory_source: {
|
|
2728
|
+
resource: "memory-sources",
|
|
2729
|
+
verb: "update",
|
|
2730
|
+
confirm: true,
|
|
2731
|
+
examples: [
|
|
2732
|
+
`himring memory-sources update ${MEMORY2} ${SOURCE} --sorting rules_only --yes`,
|
|
2733
|
+
`himring memory-sources update ${MEMORY2} ${SOURCE} --name "Support agent, Europe" --dry-run`
|
|
2734
|
+
]
|
|
2735
|
+
},
|
|
2736
|
+
delete_memory_source: {
|
|
2737
|
+
resource: "memory-sources",
|
|
2738
|
+
verb: "delete",
|
|
2739
|
+
confirm: true,
|
|
2740
|
+
examples: [
|
|
2741
|
+
`himring memory-sources delete ${MEMORY2} ${SOURCE} --yes`,
|
|
2742
|
+
`himring memory-sources delete ${MEMORY2} ${SOURCE} --dry-run`
|
|
2743
|
+
]
|
|
2744
|
+
},
|
|
2745
|
+
sync_memory_source: {
|
|
2746
|
+
resource: "memory-sources",
|
|
2747
|
+
verb: "sync",
|
|
2748
|
+
examples: [
|
|
2749
|
+
`himring memory-sources sync ${MEMORY2} ${SOURCE}`,
|
|
2750
|
+
`himring memory-sources sync ${MEMORY2} ${SOURCE} --output json`
|
|
2751
|
+
]
|
|
2752
|
+
},
|
|
2753
|
+
start_memory_source_sign_in: {
|
|
2754
|
+
resource: "memory-sources",
|
|
2755
|
+
verb: "sign-in",
|
|
2756
|
+
examples: [
|
|
2757
|
+
`himring memory-sources sign-in ${MEMORY2} ${SOURCE}`,
|
|
2758
|
+
`himring memory-sources sign-in ${MEMORY2} ${SOURCE} --output json`
|
|
2759
|
+
]
|
|
2760
|
+
},
|
|
2761
|
+
add_messages: {
|
|
2762
|
+
resource: "messages",
|
|
2763
|
+
verb: "add",
|
|
2764
|
+
examples: [
|
|
2765
|
+
`himring messages add ${MEMORY2} ${SOURCE} --items-file messages.json`,
|
|
2766
|
+
`cat messages.json | himring messages add ${MEMORY2} ${SOURCE} --items-file - --output json`
|
|
2767
|
+
]
|
|
2768
|
+
},
|
|
2769
|
+
list_messages: {
|
|
2770
|
+
resource: "messages",
|
|
2771
|
+
verb: "list",
|
|
2772
|
+
examples: [
|
|
2773
|
+
`himring messages list ${MEMORY2} --state waiting,failed`,
|
|
2774
|
+
`himring messages list ${MEMORY2} ${SOURCE} --conversation-id ticket-88 --output json`
|
|
2775
|
+
]
|
|
2776
|
+
},
|
|
2777
|
+
get_message: {
|
|
2778
|
+
resource: "messages",
|
|
2779
|
+
verb: "get",
|
|
2780
|
+
examples: [
|
|
2781
|
+
`himring messages get ${MEMORY2} ${SOURCE} --external-id ticket-88-reply-3`,
|
|
2782
|
+
`himring messages get ${MEMORY2} ${SOURCE} --external-id ticket-88-reply-3 --version 2 --output json`
|
|
2783
|
+
]
|
|
2784
|
+
},
|
|
2785
|
+
export_memories: {
|
|
2786
|
+
resource: "memories",
|
|
2787
|
+
verb: "export",
|
|
2788
|
+
examples: [
|
|
2789
|
+
`himring memories export ${MEMORY2} --end-user customer-1042 --out customer-1042-memories.json`,
|
|
2790
|
+
`himring memories export ${MEMORY2} --after mm_9b1d3f5a7c9e1b3d5f7a9c1e3b5d7f9a --out memories-part-2.json --force`
|
|
2791
|
+
]
|
|
2792
|
+
},
|
|
2793
|
+
list_memory_owners: {
|
|
2794
|
+
resource: "memory-owners",
|
|
2795
|
+
verb: "list",
|
|
2796
|
+
examples: [
|
|
2797
|
+
`himring memory-owners list ${MEMORY2} --query support`,
|
|
2798
|
+
`himring memory-owners list ${MEMORY2} --scope team --output json`
|
|
2799
|
+
]
|
|
2800
|
+
}
|
|
2801
|
+
};
|
|
2802
|
+
|
|
2803
|
+
// src/question-set-specs.ts
|
|
2804
|
+
var QUESTION_SET_RESOURCE_DESCRIPTIONS = {
|
|
2805
|
+
"question-set": "Read the saved questions of a knowledge base in summary, with the settings that search uses.",
|
|
2806
|
+
"saved-questions": "Save, import, list, read, update, and delete the questions that a knowledge base answers.",
|
|
2807
|
+
scorecards: "Score the saved questions and read the result of each one.",
|
|
2808
|
+
corrections: "Propose, try, promote, and discard corrections to the search settings of a knowledge base.",
|
|
2809
|
+
"correction-passes": "List and read the passes that propose and try corrections."
|
|
2810
|
+
};
|
|
2811
|
+
var KB3 = "--knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f";
|
|
2812
|
+
var SAVED_QUESTION = "--saved-question svq_7c1e3a5b9d2f4e6a8c0b1d3f5a7c9e2b";
|
|
2813
|
+
var SCORECARD = "--scorecard scr_4a6c8e0b2d1f3a5c7e9b0d2f4a6c8e1b";
|
|
2814
|
+
var CORRECTION = "--correction cor_9e1c3a5b7d0f2e4a6c8b1d3f5e7a9c2b";
|
|
2815
|
+
var PASS = "--pass pas_5b7d9f1a3c0e2b4d6f8a0c2e4b6d8f1a";
|
|
2816
|
+
var QUESTION_SET_COMMANDS = {
|
|
2817
|
+
get_question_set: {
|
|
2818
|
+
resource: "question-set",
|
|
2819
|
+
verb: "get",
|
|
2820
|
+
examples: [`himring question-set get ${KB3}`, `himring question-set get ${KB3} --output json`]
|
|
2821
|
+
},
|
|
2822
|
+
save_question: {
|
|
2823
|
+
resource: "saved-questions",
|
|
2824
|
+
verb: "save",
|
|
2825
|
+
examples: [
|
|
2826
|
+
`himring saved-questions save ${KB3} --question "How long do refunds take?" --chunk chk_2b4d6f8a0c1e3a5c7e9b8d6f4a2c0e1b`,
|
|
2827
|
+
`himring saved-questions save ${KB3} --question "Where do I sign for repairs?" --file fil_0a1b2c3d4e5f60718293a4b5c6d7e8f9 --first-position 12 --last-position 14`
|
|
2828
|
+
]
|
|
2829
|
+
},
|
|
2830
|
+
list_saved_questions: {
|
|
2831
|
+
resource: "saved-questions",
|
|
2832
|
+
verb: "list",
|
|
2833
|
+
examples: [
|
|
2834
|
+
`himring saved-questions list ${KB3} --state broken`,
|
|
2835
|
+
`himring saved-questions list ${KB3} --split held_back --search refund --output json`
|
|
2836
|
+
]
|
|
2837
|
+
},
|
|
2838
|
+
get_saved_question: {
|
|
2839
|
+
resource: "saved-questions",
|
|
2840
|
+
verb: "get",
|
|
2841
|
+
examples: [
|
|
2842
|
+
`himring saved-questions get ${KB3} ${SAVED_QUESTION}`,
|
|
2843
|
+
`himring saved-questions get ${KB3} ${SAVED_QUESTION} --output json`
|
|
2844
|
+
]
|
|
2845
|
+
},
|
|
2846
|
+
update_saved_question: {
|
|
2847
|
+
resource: "saved-questions",
|
|
2848
|
+
verb: "update",
|
|
2849
|
+
examples: [
|
|
2850
|
+
`himring saved-questions update ${KB3} ${SAVED_QUESTION} --confirm true`,
|
|
2851
|
+
`himring saved-questions update ${KB3} ${SAVED_QUESTION} --file fil_0a1b2c3d4e5f60718293a4b5c6d7e8f9 --first-position 20 --last-position 22`
|
|
2852
|
+
]
|
|
2853
|
+
},
|
|
2854
|
+
delete_saved_question: {
|
|
2855
|
+
resource: "saved-questions",
|
|
2856
|
+
verb: "delete",
|
|
2857
|
+
confirm: true,
|
|
2858
|
+
examples: [
|
|
2859
|
+
`himring saved-questions delete ${KB3} ${SAVED_QUESTION} --yes`,
|
|
2860
|
+
`himring saved-questions delete ${KB3} ${SAVED_QUESTION} --dry-run`
|
|
2861
|
+
]
|
|
2862
|
+
},
|
|
2863
|
+
score_question_set: {
|
|
2864
|
+
resource: "scorecards",
|
|
2865
|
+
verb: "score",
|
|
2866
|
+
examples: [`himring scorecards score ${KB3}`, `himring scorecards score ${KB3} --output json`]
|
|
2867
|
+
},
|
|
2868
|
+
list_scorecards: {
|
|
2869
|
+
resource: "scorecards",
|
|
2870
|
+
verb: "list",
|
|
2871
|
+
examples: [`himring scorecards list ${KB3}`, `himring scorecards list ${KB3} --limit 5 --output json`]
|
|
2872
|
+
},
|
|
2873
|
+
get_scorecard: {
|
|
2874
|
+
resource: "scorecards",
|
|
2875
|
+
verb: "get",
|
|
2876
|
+
examples: [`himring scorecards get ${KB3} ${SCORECARD}`, `himring scorecards get ${KB3} ${SCORECARD} --output json`]
|
|
2877
|
+
},
|
|
2878
|
+
list_scorecard_results: {
|
|
2879
|
+
resource: "scorecards",
|
|
2880
|
+
verb: "results",
|
|
2881
|
+
examples: [
|
|
2882
|
+
`himring scorecards results ${KB3} ${SCORECARD} --outcome failed --cause ranked_lower`,
|
|
2883
|
+
`himring scorecards results ${KB3} ${SCORECARD} --compare-to scr_1b3d5f7a9c0e2b4d6f8a1c3e5b7d9f0a --output json`,
|
|
2884
|
+
`himring scorecards results ${KB3} ${SCORECARD} --compare-to scr_1b3d5f7a9c0e2b4d6f8a1c3e5b7d9f0a --change now_passes,now_fails`
|
|
2885
|
+
]
|
|
2886
|
+
},
|
|
2887
|
+
propose_corrections: {
|
|
2888
|
+
resource: "corrections",
|
|
2889
|
+
verb: "propose",
|
|
2890
|
+
examples: [`himring corrections propose ${KB3}`, `himring corrections propose ${KB3} --output json`]
|
|
2891
|
+
},
|
|
2892
|
+
create_correction: {
|
|
2893
|
+
resource: "corrections",
|
|
2894
|
+
verb: "create",
|
|
2895
|
+
examples: [
|
|
2896
|
+
`himring corrections create ${KB3} --setting-file setting.json`,
|
|
2897
|
+
`echo '{"kind":"chunking","chunk_tokens":300}' | himring corrections create ${KB3} --setting-file - --target-ids svq_7c1e3a5b9d2f4e6a8c0b1d3f5a7c9e2b`
|
|
2898
|
+
]
|
|
2899
|
+
},
|
|
2900
|
+
list_corrections: {
|
|
2901
|
+
resource: "corrections",
|
|
2902
|
+
verb: "list",
|
|
2903
|
+
examples: [
|
|
2904
|
+
`himring corrections list ${KB3} ${PASS}`,
|
|
2905
|
+
`himring corrections list ${KB3} --status proposed,tried`,
|
|
2906
|
+
`himring corrections list ${KB3} --kind chunking --output json`
|
|
2907
|
+
]
|
|
2908
|
+
},
|
|
2909
|
+
get_correction: {
|
|
2910
|
+
resource: "corrections",
|
|
2911
|
+
verb: "get",
|
|
2912
|
+
examples: [
|
|
2913
|
+
`himring corrections get ${KB3} ${CORRECTION}`,
|
|
2914
|
+
`himring corrections get ${KB3} ${CORRECTION} --output json`
|
|
2915
|
+
]
|
|
2916
|
+
},
|
|
2917
|
+
try_corrections: {
|
|
2918
|
+
resource: "corrections",
|
|
2919
|
+
verb: "try",
|
|
2920
|
+
examples: [
|
|
2921
|
+
`himring corrections try ${KB3} --correction-ids cor_9e1c3a5b7d0f2e4a6c8b1d3f5e7a9c2b`,
|
|
2922
|
+
`himring corrections try ${KB3} --correction-ids cor_9e1c3a5b7d0f2e4a6c8b1d3f5e7a9c2b --complete-index true`
|
|
2923
|
+
]
|
|
2924
|
+
},
|
|
2925
|
+
promote_correction: {
|
|
2926
|
+
resource: "corrections",
|
|
2927
|
+
verb: "promote",
|
|
2928
|
+
confirm: true,
|
|
2929
|
+
examples: [
|
|
2930
|
+
`himring corrections promote ${KB3} ${CORRECTION} --yes`,
|
|
2931
|
+
`himring corrections promote ${KB3} ${CORRECTION} --note "Held-back score held at 41 of 50" --yes`
|
|
2932
|
+
]
|
|
2933
|
+
},
|
|
2934
|
+
discard_correction: {
|
|
2935
|
+
resource: "corrections",
|
|
2936
|
+
verb: "discard",
|
|
2937
|
+
confirm: true,
|
|
2938
|
+
examples: [
|
|
2939
|
+
`himring corrections discard ${KB3} ${CORRECTION} --yes`,
|
|
2940
|
+
`himring corrections discard ${KB3} ${CORRECTION} --note "Too slow to build" --dry-run`
|
|
2941
|
+
]
|
|
2942
|
+
},
|
|
2943
|
+
list_correction_passes: {
|
|
2944
|
+
resource: "correction-passes",
|
|
2945
|
+
verb: "list",
|
|
2946
|
+
examples: [`himring correction-passes list ${KB3}`, `himring correction-passes list ${KB3} --limit 5 --output json`]
|
|
2947
|
+
},
|
|
2948
|
+
get_correction_pass: {
|
|
2949
|
+
resource: "correction-passes",
|
|
2950
|
+
verb: "get",
|
|
2951
|
+
examples: [
|
|
2952
|
+
`himring correction-passes get ${KB3} ${PASS}`,
|
|
2953
|
+
`himring correction-passes get ${KB3} ${PASS} --output json`
|
|
2954
|
+
]
|
|
2955
|
+
}
|
|
2956
|
+
};
|
|
2957
|
+
|
|
2958
|
+
// src/source-specs.ts
|
|
2959
|
+
var SOURCE_RESOURCE_DESCRIPTIONS = {
|
|
2960
|
+
sources: "Connect the systems that feed a knowledge base, such as call platforms, Zendesk, S3 buckets, Slack, Notion, Confluence, and Google Drive, and sign in to them, sync, change, or disconnect them.",
|
|
2961
|
+
"source-sign-ins": "Finish the sign-in of a source with the state and the code that the platform returned.",
|
|
2962
|
+
"source-items": "Send conversations, messages, and records from any system to a push source, and list their receipts."
|
|
2963
|
+
};
|
|
2964
|
+
var KB4 = "--knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f";
|
|
2965
|
+
var SOURCE2 = "--source src_6d8f0a2c4e1b3d5f7a9c0e2b4d6f8a1c";
|
|
2966
|
+
var SOURCE_COMMANDS = {
|
|
2967
|
+
create_source: {
|
|
2968
|
+
resource: "sources",
|
|
2969
|
+
verb: "create",
|
|
2970
|
+
examples: [
|
|
2971
|
+
`himring sources create ${KB4} --name "Order system" --kind push`,
|
|
2972
|
+
`himring sources create ${KB4} --name "Support calls" --kind retell --credentials-file retell.json`,
|
|
2973
|
+
`himring sources create ${KB4} --name "Contracts bucket" --kind s3 --settings-file bucket.json --credentials-file bucket-key.json --output json`
|
|
2974
|
+
]
|
|
2975
|
+
},
|
|
2976
|
+
list_sources: {
|
|
2977
|
+
resource: "sources",
|
|
2978
|
+
verb: "list",
|
|
2979
|
+
examples: [`himring sources list ${KB4}`, `himring sources list ${KB4} --kind vapi,retell --output json`]
|
|
2980
|
+
},
|
|
2981
|
+
get_source: {
|
|
2982
|
+
resource: "sources",
|
|
2983
|
+
verb: "get",
|
|
2984
|
+
examples: [`himring sources get ${KB4} ${SOURCE2}`, `himring sources get ${KB4} ${SOURCE2} --output json`]
|
|
2985
|
+
},
|
|
2986
|
+
list_source_syncs: {
|
|
2987
|
+
resource: "sources",
|
|
2988
|
+
verb: "syncs",
|
|
2989
|
+
examples: [
|
|
2990
|
+
`himring sources syncs ${KB4} ${SOURCE2}`,
|
|
2991
|
+
`himring sources syncs ${KB4} ${SOURCE2} --limit 5 --output json`
|
|
2992
|
+
]
|
|
2993
|
+
},
|
|
2994
|
+
update_source: {
|
|
2995
|
+
resource: "sources",
|
|
2996
|
+
verb: "update",
|
|
2997
|
+
confirm: true,
|
|
2998
|
+
examples: [
|
|
2999
|
+
`himring sources update ${KB4} ${SOURCE2} --credentials-file new-key.json --yes`,
|
|
3000
|
+
`himring sources update ${KB4} ${SOURCE2} --rotate-webhook-secret true --yes --output json`,
|
|
3001
|
+
`himring sources update ${KB4} ${SOURCE2} --name "Support calls, Europe" --dry-run`
|
|
3002
|
+
]
|
|
3003
|
+
},
|
|
3004
|
+
delete_source: {
|
|
3005
|
+
resource: "sources",
|
|
3006
|
+
verb: "delete",
|
|
3007
|
+
confirm: true,
|
|
3008
|
+
examples: [`himring sources delete ${KB4} ${SOURCE2} --yes`, `himring sources delete ${KB4} ${SOURCE2} --dry-run`]
|
|
3009
|
+
},
|
|
3010
|
+
sync_source: {
|
|
3011
|
+
resource: "sources",
|
|
3012
|
+
verb: "sync",
|
|
3013
|
+
examples: [`himring sources sync ${KB4} ${SOURCE2}`, `himring sources sync ${KB4} ${SOURCE2} --output json`]
|
|
3014
|
+
},
|
|
3015
|
+
start_source_sign_in: {
|
|
3016
|
+
resource: "sources",
|
|
3017
|
+
verb: "sign-in",
|
|
3018
|
+
examples: [`himring sources sign-in ${KB4} ${SOURCE2}`, `himring sources sign-in ${KB4} ${SOURCE2} --output json`]
|
|
3019
|
+
},
|
|
3020
|
+
finish_source_sign_in: {
|
|
3021
|
+
resource: "source-sign-ins",
|
|
3022
|
+
verb: "finish",
|
|
3023
|
+
examples: ["himring source-sign-ins finish --state 4kQ9xT2mW7pL0vB3nR8sY1dF6hJ5gK2cZ9aE4uI7oP0 --code 7a1f0c9e2b"]
|
|
3024
|
+
},
|
|
3025
|
+
ingest_items: {
|
|
3026
|
+
resource: "source-items",
|
|
3027
|
+
verb: "ingest",
|
|
3028
|
+
examples: [
|
|
3029
|
+
`himring source-items ingest ${KB4} ${SOURCE2} --items-file items.json`,
|
|
3030
|
+
`cat items.json | himring source-items ingest ${KB4} ${SOURCE2} --items-file - --output json`
|
|
3031
|
+
]
|
|
3032
|
+
},
|
|
3033
|
+
list_source_items: {
|
|
3034
|
+
resource: "source-items",
|
|
3035
|
+
verb: "list",
|
|
3036
|
+
examples: [
|
|
3037
|
+
`himring source-items list ${KB4} ${SOURCE2} --state waiting`,
|
|
3038
|
+
`himring source-items list ${KB4} ${SOURCE2} --external-id order-1042 --output json`
|
|
3039
|
+
]
|
|
3040
|
+
}
|
|
3041
|
+
};
|
|
3042
|
+
|
|
3043
|
+
// src/operation-specs.ts
|
|
3044
|
+
var RESOURCE_DESCRIPTIONS = {
|
|
3045
|
+
operations: "List the operations of the Himring API.",
|
|
3046
|
+
auth: "Sign up, sign in, set up your second factor, and sign out.",
|
|
3047
|
+
projects: "Create, read, delete, and restore projects.",
|
|
3048
|
+
members: "List and remove the members of a project.",
|
|
3049
|
+
invitations: "Invite people to a project, and accept invitations.",
|
|
3050
|
+
"api-keys": "Create, list, and revoke the API keys of a project.",
|
|
3051
|
+
databases: "Create, read, change, delete, restore, and compact the SQLite databases of a project.",
|
|
3052
|
+
migrations: "List and add the migrations of a database.",
|
|
3053
|
+
indexes: "Create, read, change, delete, restore, download, and preview searches of the search indexes of a project.",
|
|
3054
|
+
...DATABASE_WORKSPACE_RESOURCE_DESCRIPTIONS,
|
|
3055
|
+
...INDEX_RECORD_RESOURCE_DESCRIPTIONS,
|
|
3056
|
+
...KNOWLEDGE_BASE_RESOURCE_DESCRIPTIONS,
|
|
3057
|
+
...QUESTION_SET_RESOURCE_DESCRIPTIONS,
|
|
3058
|
+
...FLAGGED_QUESTION_RESOURCE_DESCRIPTIONS,
|
|
3059
|
+
...SOURCE_RESOURCE_DESCRIPTIONS,
|
|
3060
|
+
...MEMORY_RESOURCE_DESCRIPTIONS,
|
|
3061
|
+
...MEMORY_REVIEW_RESOURCE_DESCRIPTIONS
|
|
3062
|
+
};
|
|
3063
|
+
var PROJECT = "--project prj_6d2f0c1e9a8b4c7d5e3f2a1b0c9d8e7f";
|
|
3064
|
+
var ACCOUNT = "--account 0b6e8f6a-3c1d-4f5e-9a7b-2c4d6e8f0a1b";
|
|
3065
|
+
var INVITATION = "--invitation inv_5e7d9c1b3a2f4e6d8c0b1a9f7e5d3c2b";
|
|
3066
|
+
var KEY = "--key key_2b4d6f8a0c1e3a5c7e9b8d6f4a2c0e1b";
|
|
3067
|
+
var DATABASE = "--database db_3a9e5c7b1d2f4e6a8c0b9d7f5e3a1c2b";
|
|
3068
|
+
var INDEX2 = "--index ix_8c4b2a0f1e3d5c7b9a8f6e4d2c0b1a3f";
|
|
3069
|
+
var OPERATION_COMMANDS = {
|
|
3070
|
+
list_operations: {
|
|
3071
|
+
resource: "operations",
|
|
3072
|
+
verb: "list",
|
|
3073
|
+
examples: ["himring operations list", "himring operations list --output json"]
|
|
3074
|
+
},
|
|
3075
|
+
get_session: {
|
|
3076
|
+
resource: "auth",
|
|
3077
|
+
verb: "session",
|
|
3078
|
+
examples: ["himring auth session", "himring auth session --output json"]
|
|
3079
|
+
},
|
|
3080
|
+
create_project: {
|
|
3081
|
+
resource: "projects",
|
|
3082
|
+
verb: "create",
|
|
3083
|
+
examples: ['himring projects create --name "Support answers"', "himring projects create --name Docs --output json"]
|
|
3084
|
+
},
|
|
3085
|
+
list_projects: {
|
|
3086
|
+
resource: "projects",
|
|
3087
|
+
verb: "list",
|
|
3088
|
+
examples: [
|
|
3089
|
+
"himring projects list --search support --role owner",
|
|
3090
|
+
"himring projects list --state deleted --sort purge_after --direction asc --output json"
|
|
3091
|
+
]
|
|
3092
|
+
},
|
|
3093
|
+
get_project: {
|
|
3094
|
+
resource: "projects",
|
|
3095
|
+
verb: "get",
|
|
3096
|
+
examples: [
|
|
3097
|
+
`himring projects get ${PROJECT}`,
|
|
3098
|
+
"HIMRING_PROJECT=prj_6d2f0c1e9a8b4c7d5e3f2a1b0c9d8e7f himring projects get"
|
|
3099
|
+
]
|
|
3100
|
+
},
|
|
3101
|
+
delete_project: {
|
|
3102
|
+
resource: "projects",
|
|
3103
|
+
verb: "delete",
|
|
3104
|
+
confirm: true,
|
|
3105
|
+
examples: [`himring projects delete ${PROJECT} --yes`, `himring projects delete ${PROJECT} --dry-run`]
|
|
3106
|
+
},
|
|
3107
|
+
restore_project: {
|
|
3108
|
+
resource: "projects",
|
|
3109
|
+
verb: "restore",
|
|
3110
|
+
examples: [`himring projects restore ${PROJECT}`, `himring projects restore ${PROJECT} --output json`]
|
|
3111
|
+
},
|
|
3112
|
+
list_members: {
|
|
3113
|
+
resource: "members",
|
|
3114
|
+
verb: "list",
|
|
3115
|
+
examples: [
|
|
3116
|
+
`himring members list ${PROJECT} --role owner`,
|
|
3117
|
+
"himring members list --search example.com --sort added_at --direction desc --limit 20 --output json"
|
|
3118
|
+
]
|
|
3119
|
+
},
|
|
3120
|
+
remove_member: {
|
|
3121
|
+
resource: "members",
|
|
3122
|
+
verb: "remove",
|
|
3123
|
+
confirm: true,
|
|
3124
|
+
examples: [`himring members remove ${PROJECT} ${ACCOUNT} --yes`, `himring members remove ${ACCOUNT} --dry-run`]
|
|
3125
|
+
},
|
|
3126
|
+
invite_member: {
|
|
3127
|
+
resource: "invitations",
|
|
3128
|
+
verb: "create",
|
|
3129
|
+
examples: [
|
|
3130
|
+
"himring invitations create --email teammate@example.com",
|
|
3131
|
+
"himring invitations create --email second-owner@example.com --role owner"
|
|
3132
|
+
]
|
|
3133
|
+
},
|
|
3134
|
+
list_invitations: {
|
|
3135
|
+
resource: "invitations",
|
|
3136
|
+
verb: "list",
|
|
3137
|
+
examples: [
|
|
3138
|
+
`himring invitations list ${PROJECT} --status expired`,
|
|
3139
|
+
"himring invitations list --role member --sort expires_at --direction asc --output json"
|
|
3140
|
+
]
|
|
3141
|
+
},
|
|
3142
|
+
revoke_invitation: {
|
|
3143
|
+
resource: "invitations",
|
|
3144
|
+
verb: "revoke",
|
|
3145
|
+
confirm: true,
|
|
3146
|
+
examples: [`himring invitations revoke ${INVITATION} --yes`, `himring invitations revoke ${INVITATION} --dry-run`]
|
|
3147
|
+
},
|
|
3148
|
+
accept_invitation: {
|
|
3149
|
+
resource: "invitations",
|
|
3150
|
+
verb: "accept",
|
|
3151
|
+
examples: [
|
|
3152
|
+
"himring invitations accept --token-file invitation.txt",
|
|
3153
|
+
'printf "%s" "$INVITATION_TOKEN" | himring invitations accept --token-file - --output json'
|
|
3154
|
+
]
|
|
3155
|
+
},
|
|
3156
|
+
create_api_key: {
|
|
3157
|
+
resource: "api-keys",
|
|
3158
|
+
verb: "create",
|
|
3159
|
+
examples: [
|
|
3160
|
+
`printf '%s' '{"access":"full"}' | himring api-keys create --name CI --permissions-file -`,
|
|
3161
|
+
'himring api-keys create --name "Support agent" --permissions-file support-agent-permissions.json --output json'
|
|
3162
|
+
]
|
|
3163
|
+
},
|
|
3164
|
+
update_api_key: {
|
|
3165
|
+
resource: "api-keys",
|
|
3166
|
+
verb: "update",
|
|
3167
|
+
examples: [
|
|
3168
|
+
`printf '%s' '{"access":"restricted","indexes":{"level":"read"}}' | himring api-keys update ${KEY} --permissions-file -`,
|
|
3169
|
+
`himring api-keys update ${KEY} --permissions-file read-only.json --output json`
|
|
3170
|
+
]
|
|
3171
|
+
},
|
|
3172
|
+
list_api_key_permission_changes: {
|
|
3173
|
+
resource: "api-keys",
|
|
3174
|
+
verb: "permission-changes",
|
|
3175
|
+
examples: [
|
|
3176
|
+
`himring api-keys permission-changes ${KEY}`,
|
|
3177
|
+
`himring api-keys permission-changes ${KEY} --limit 10 --output json`
|
|
3178
|
+
]
|
|
3179
|
+
},
|
|
3180
|
+
list_api_keys: {
|
|
3181
|
+
resource: "api-keys",
|
|
3182
|
+
verb: "list",
|
|
3183
|
+
examples: [
|
|
3184
|
+
`himring api-keys list ${PROJECT} --status active`,
|
|
3185
|
+
"himring api-keys list --search hmr_3f9a --created-from 2026-10-01 --output json"
|
|
3186
|
+
]
|
|
3187
|
+
},
|
|
3188
|
+
revoke_api_key: {
|
|
3189
|
+
resource: "api-keys",
|
|
3190
|
+
verb: "revoke",
|
|
3191
|
+
confirm: true,
|
|
3192
|
+
examples: [`himring api-keys revoke ${KEY} --yes`, `himring api-keys revoke ${KEY} --dry-run`]
|
|
3193
|
+
},
|
|
3194
|
+
create_database: {
|
|
3195
|
+
resource: "databases",
|
|
3196
|
+
verb: "create",
|
|
3197
|
+
examples: [
|
|
3198
|
+
"himring databases create --name orders",
|
|
3199
|
+
"himring databases create --name orders --migrations-file migrations.json"
|
|
3200
|
+
]
|
|
3201
|
+
},
|
|
3202
|
+
list_databases: {
|
|
3203
|
+
resource: "databases",
|
|
3204
|
+
verb: "list",
|
|
3205
|
+
examples: [
|
|
3206
|
+
"himring databases list --search orders --creator key --sort name --direction asc",
|
|
3207
|
+
"himring databases list --state deleted --sort purge_after --direction asc --limit 20 --offset 20 --output json"
|
|
3208
|
+
]
|
|
3209
|
+
},
|
|
3210
|
+
get_database: {
|
|
3211
|
+
resource: "databases",
|
|
3212
|
+
verb: "get",
|
|
3213
|
+
examples: [`himring databases get ${DATABASE}`, `himring databases get ${DATABASE} --output json`]
|
|
3214
|
+
},
|
|
3215
|
+
update_database: {
|
|
3216
|
+
resource: "databases",
|
|
3217
|
+
verb: "update",
|
|
3218
|
+
confirm: true,
|
|
3219
|
+
examples: [
|
|
3220
|
+
`himring databases update ${DATABASE} --sql-write-preview true --yes`,
|
|
3221
|
+
`himring databases update ${DATABASE} --sql-write-preview false --dry-run`
|
|
3222
|
+
]
|
|
3223
|
+
},
|
|
3224
|
+
delete_database: {
|
|
3225
|
+
resource: "databases",
|
|
3226
|
+
verb: "delete",
|
|
3227
|
+
confirm: true,
|
|
3228
|
+
examples: [`himring databases delete ${DATABASE} --yes`, `himring databases delete ${DATABASE} --dry-run`]
|
|
3229
|
+
},
|
|
3230
|
+
restore_database: {
|
|
3231
|
+
resource: "databases",
|
|
3232
|
+
verb: "restore",
|
|
3233
|
+
examples: [`himring databases restore ${DATABASE}`, `himring databases restore ${DATABASE} --output json`]
|
|
3234
|
+
},
|
|
3235
|
+
compact_database: {
|
|
3236
|
+
resource: "databases",
|
|
3237
|
+
verb: "compact",
|
|
3238
|
+
examples: [`himring databases compact ${DATABASE}`, `himring databases compact ${DATABASE} --output json`]
|
|
3239
|
+
},
|
|
3240
|
+
list_database_migrations: {
|
|
3241
|
+
resource: "migrations",
|
|
3242
|
+
verb: "list",
|
|
3243
|
+
examples: [`himring migrations list ${DATABASE}`, `himring migrations list ${DATABASE} --output json`]
|
|
3244
|
+
},
|
|
3245
|
+
add_database_migration: {
|
|
3246
|
+
resource: "migrations",
|
|
3247
|
+
verb: "add",
|
|
3248
|
+
examples: [
|
|
3249
|
+
`himring migrations add ${DATABASE} --name add_orders --sql-file 002_add_orders.sql`,
|
|
3250
|
+
`echo 'CREATE INDEX orders_by_day ON orders (day);' | himring migrations add ${DATABASE} --name orders_by_day --sql-file -`
|
|
3251
|
+
]
|
|
3252
|
+
},
|
|
3253
|
+
create_index: {
|
|
3254
|
+
resource: "indexes",
|
|
3255
|
+
verb: "create",
|
|
3256
|
+
examples: [
|
|
3257
|
+
"himring indexes create --name articles --config-file articles.json",
|
|
3258
|
+
"cat articles.json | himring indexes create --name articles --config-file -"
|
|
3259
|
+
]
|
|
3260
|
+
},
|
|
3261
|
+
list_indexes: {
|
|
3262
|
+
resource: "indexes",
|
|
3263
|
+
verb: "list",
|
|
3264
|
+
examples: [
|
|
3265
|
+
"himring indexes list --search articles --created-from 2026-10-01 --created-to 2026-10-31",
|
|
3266
|
+
"himring indexes list --state deleted --sort purge_after --direction asc --output json"
|
|
3267
|
+
]
|
|
3268
|
+
},
|
|
3269
|
+
get_index: {
|
|
3270
|
+
resource: "indexes",
|
|
3271
|
+
verb: "get",
|
|
3272
|
+
examples: [`himring indexes get ${INDEX2}`, `himring indexes get ${INDEX2} --output json`]
|
|
3273
|
+
},
|
|
3274
|
+
delete_index: {
|
|
3275
|
+
resource: "indexes",
|
|
3276
|
+
verb: "delete",
|
|
3277
|
+
confirm: true,
|
|
3278
|
+
examples: [`himring indexes delete ${INDEX2} --yes`, `himring indexes delete ${INDEX2} --dry-run`]
|
|
3279
|
+
},
|
|
3280
|
+
restore_index: {
|
|
3281
|
+
resource: "indexes",
|
|
3282
|
+
verb: "restore",
|
|
3283
|
+
examples: [`himring indexes restore ${INDEX2}`, `himring indexes restore ${INDEX2} --output json`]
|
|
3284
|
+
},
|
|
3285
|
+
download_index: {
|
|
3286
|
+
resource: "indexes",
|
|
3287
|
+
verb: "download",
|
|
3288
|
+
examples: [`himring indexes download ${INDEX2}`, `himring indexes download ${INDEX2} --out backup.nrsl --force`]
|
|
3289
|
+
},
|
|
3290
|
+
...DATABASE_WORKSPACE_COMMANDS,
|
|
3291
|
+
...INDEX_RECORD_COMMANDS,
|
|
3292
|
+
...KNOWLEDGE_BASE_COMMANDS,
|
|
3293
|
+
...QUESTION_SET_COMMANDS,
|
|
3294
|
+
...FLAGGED_QUESTION_COMMANDS,
|
|
3295
|
+
...SOURCE_COMMANDS,
|
|
3296
|
+
...MEMORY_COMMANDS,
|
|
3297
|
+
...MEMORY_REVIEW_COMMANDS
|
|
3298
|
+
};
|
|
3299
|
+
|
|
3300
|
+
// src/operation-commands.ts
|
|
3301
|
+
var INPUT_SUGGESTION2 = "Correct the options and try again.";
|
|
3302
|
+
function isCommandOperation(id) {
|
|
3303
|
+
return Object.hasOwn(OPERATION_COMMANDS, id) && Object.hasOwn(HIMRING_OPERATIONS3, id);
|
|
3304
|
+
}
|
|
3305
|
+
async function runOperation(context, id, spec, fields, options) {
|
|
3306
|
+
return runCommand(context, async () => {
|
|
3307
|
+
const input = await inputFrom(context, fields, options);
|
|
3308
|
+
checkInput(id, input, INPUT_SUGGESTION2);
|
|
3309
|
+
if (options.dryRun === true) return dryRunOf(id, input, withoutPathFields(id, input));
|
|
3310
|
+
if (spec.confirm === true && options.yes !== true) {
|
|
3311
|
+
throw new UsageError(
|
|
3312
|
+
`${HIMRING_OPERATION_CATALOGUE5[id].summary} The command needs your confirmation.`,
|
|
3313
|
+
"Pass --yes to go ahead."
|
|
3314
|
+
);
|
|
3315
|
+
}
|
|
3316
|
+
const result = await (await signedInClient(context)).invoke(id, input);
|
|
3317
|
+
if (HIMRING_OPERATIONS3[id].response.kind === "download") {
|
|
3318
|
+
return saveDownloadTo(result, {
|
|
3319
|
+
out: typeof options.out === "string" ? options.out : void 0,
|
|
3320
|
+
force: options.force === true,
|
|
3321
|
+
idleTimeoutMs: context.options.timeoutMs
|
|
3322
|
+
});
|
|
3323
|
+
}
|
|
3324
|
+
checkOutput(id, result);
|
|
3325
|
+
return result;
|
|
3326
|
+
});
|
|
3327
|
+
}
|
|
3328
|
+
function examplesText(spec) {
|
|
3329
|
+
return `
|
|
3330
|
+
Examples:
|
|
3331
|
+
${spec.examples.map((example) => ` $ ${example}`).join("\n")}`;
|
|
3332
|
+
}
|
|
3333
|
+
function groupFor(program, groups, resource) {
|
|
3334
|
+
const known = groups.get(resource) ?? program.commands.find((command) => command.name() === resource);
|
|
3335
|
+
const group = known ?? program.command(resource).description(RESOURCE_DESCRIPTIONS[resource] ?? resource);
|
|
3336
|
+
groups.set(resource, group);
|
|
3337
|
+
return group;
|
|
3338
|
+
}
|
|
3339
|
+
function addOperationCommand(group, id, spec, contextFor, recordExitCode) {
|
|
3340
|
+
const entry = HIMRING_OPERATION_CATALOGUE5[id];
|
|
3341
|
+
const fields = fieldOptionsOf(id);
|
|
3342
|
+
const command = group.command(spec.verb).description(entry.summary).addHelpText("after", examplesText(spec));
|
|
3343
|
+
addFieldOptions(command, fields);
|
|
3344
|
+
command.option("--input-file <path>", "read the whole input as one JSON object from a file, or - for stdin");
|
|
3345
|
+
if (entry.changesState) command.option("--dry-run", "check the input and show the request, without sending it");
|
|
3346
|
+
if (spec.confirm === true) command.option("--yes", "confirm the change that the command makes");
|
|
3347
|
+
if (HIMRING_OPERATIONS3[id].response.kind === "download") {
|
|
3348
|
+
command.option(
|
|
3349
|
+
"--out <path>",
|
|
3350
|
+
"write the file to this path; without it, the CLI writes the file under its own name in this folder"
|
|
3351
|
+
);
|
|
3352
|
+
command.option("--force", "replace a file that already exists");
|
|
3353
|
+
}
|
|
3354
|
+
command.action(async (_options, invoked) => {
|
|
3355
|
+
const context = contextFor(invoked);
|
|
3356
|
+
if (context === void 0) return;
|
|
3357
|
+
const options = invoked.opts();
|
|
3358
|
+
recordExitCode(await runOperation(context, id, spec, fields, isRecord(options) ? options : {}));
|
|
3359
|
+
});
|
|
3360
|
+
}
|
|
3361
|
+
function addOperationCommands(program, contextFor, recordExitCode) {
|
|
3362
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3363
|
+
for (const id of Object.keys(OPERATION_COMMANDS).filter(isCommandOperation)) {
|
|
3364
|
+
const spec = OPERATION_COMMANDS[id];
|
|
3365
|
+
addOperationCommand(groupFor(program, groups, spec.resource), id, spec, contextFor, recordExitCode);
|
|
3366
|
+
}
|
|
3367
|
+
}
|
|
3368
|
+
|
|
3369
|
+
// src/question-file-commands.ts
|
|
3370
|
+
import { extname as extname2 } from "node:path";
|
|
3371
|
+
import { HIMRING_OPERATION_CATALOGUE as HIMRING_OPERATION_CATALOGUE6 } from "@himring/sdk/catalogue";
|
|
3372
|
+
import { Option as Option9 } from "commander";
|
|
3373
|
+
import * as v8 from "valibot";
|
|
3374
|
+
var OPERATION5 = "import_saved_questions";
|
|
3375
|
+
var CSV_FORMAT = "csv";
|
|
3376
|
+
var LINES_FORMAT = "jsonl";
|
|
3377
|
+
var CSV_EXTENSION = ".csv";
|
|
3378
|
+
var commandOptionsSchema5 = v8.object({
|
|
3379
|
+
project: v8.optional(v8.string()),
|
|
3380
|
+
knowledgeBase: v8.optional(v8.string()),
|
|
3381
|
+
from: v8.optional(v8.string()),
|
|
3382
|
+
format: v8.optional(v8.string()),
|
|
3383
|
+
dryRun: v8.optional(v8.boolean())
|
|
3384
|
+
});
|
|
3385
|
+
var IMPORT_EXAMPLES3 = `
|
|
3386
|
+
Examples:
|
|
3387
|
+
$ himring saved-questions import --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --from questions.jsonl
|
|
3388
|
+
$ himring saved-questions import --knowledge-base kb_3f9a0c1e2d4b6a8c0e2f4a6b8c0d2e4f --from questions.csv --output json
|
|
3389
|
+
|
|
3390
|
+
Each JSON line holds {"question": "...", "file": "policies/refunds.pdf", "quote": "..."}, and a CSV file starts with the header row question,file,quote.`;
|
|
3391
|
+
function formatOf2(options) {
|
|
3392
|
+
if (options.format !== void 0) return options.format;
|
|
3393
|
+
return options.from !== void 0 && extname2(options.from).toLowerCase() === CSV_EXTENSION ? CSV_FORMAT : LINES_FORMAT;
|
|
3394
|
+
}
|
|
3395
|
+
function addQuestionFileCommands(program, contextFor, recordExitCode) {
|
|
3396
|
+
const group = program.commands.find((command) => command.name() === "saved-questions");
|
|
3397
|
+
if (group === void 0) throw new Error("The import command needs the saved-questions group.");
|
|
3398
|
+
addProjectOption(group.command("import").description(HIMRING_OPERATION_CATALOGUE6[OPERATION5].summary)).addOption(new Option9("--knowledge-base <value>", "knowledge_base_id (required)")).requiredOption("--from <path>", "the local file of questions, in JSON Lines or CSV").addOption(
|
|
3399
|
+
new Option9(
|
|
3400
|
+
"--format <value>",
|
|
3401
|
+
"the format of the file, by default csv for a .csv file and jsonl otherwise"
|
|
3402
|
+
).choices(choicesOf(OPERATION5, "format"))
|
|
3403
|
+
).option("--dry-run", "check the input and show the request, without sending it").addHelpText("after", IMPORT_EXAMPLES3).action(async (_options, invoked) => {
|
|
3404
|
+
const context = contextFor(invoked);
|
|
3405
|
+
if (context === void 0) return;
|
|
3406
|
+
const options = v8.parse(commandOptionsSchema5, invoked.opts());
|
|
3407
|
+
recordExitCode(
|
|
3408
|
+
await runCommand(
|
|
3409
|
+
context,
|
|
3410
|
+
() => sendFileBody(context, {
|
|
3411
|
+
id: OPERATION5,
|
|
3412
|
+
input: { project_id: options.project, knowledge_base_id: options.knowledgeBase, format: formatOf2(options) },
|
|
3413
|
+
from: options.from,
|
|
3414
|
+
dryRun: options.dryRun === true,
|
|
3415
|
+
suggestion: "Pass --project and --knowledge-base.",
|
|
3416
|
+
splitHint: "Split the questions into several files and import each one."
|
|
3417
|
+
})
|
|
3418
|
+
)
|
|
3419
|
+
);
|
|
3420
|
+
});
|
|
3421
|
+
}
|
|
3422
|
+
|
|
3423
|
+
// src/secret-output.ts
|
|
3424
|
+
function secretOutput(io) {
|
|
3425
|
+
const secrets = /* @__PURE__ */ new Set();
|
|
3426
|
+
function protectSecret(value) {
|
|
3427
|
+
if (value === void 0 || value.length === 0) return;
|
|
3428
|
+
secrets.add(value);
|
|
3429
|
+
secrets.add(JSON.stringify(value).slice(1, -1));
|
|
3430
|
+
secrets.add(printable(value, false));
|
|
3431
|
+
secrets.add(printable(value, true));
|
|
3432
|
+
}
|
|
3433
|
+
function redact(text) {
|
|
3434
|
+
let result = text;
|
|
3435
|
+
for (const secret of [...secrets].sort((left, right) => right.length - left.length)) {
|
|
3436
|
+
result = result.replaceAll(secret, "[redacted credential]");
|
|
3437
|
+
}
|
|
3438
|
+
return result;
|
|
3439
|
+
}
|
|
3440
|
+
function redactValue(value) {
|
|
3441
|
+
if (typeof value === "string") return redact(value);
|
|
3442
|
+
if (Array.isArray(value)) return value.map(redactValue);
|
|
3443
|
+
if (typeof value !== "object" || value === null) return value;
|
|
3444
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [redact(key), redactValue(entry)]));
|
|
3445
|
+
}
|
|
3446
|
+
function redactOutput(text) {
|
|
3447
|
+
try {
|
|
3448
|
+
const value = JSON.parse(text);
|
|
3449
|
+
return `${JSON.stringify(redactValue(value))}${text.endsWith("\n") ? "\n" : ""}`;
|
|
3450
|
+
} catch {
|
|
3451
|
+
return redact(text);
|
|
3452
|
+
}
|
|
3453
|
+
}
|
|
3454
|
+
return {
|
|
3455
|
+
protectSecret,
|
|
3456
|
+
io: {
|
|
3457
|
+
writeStdout: (text) => io.writeStdout(redactOutput(text)),
|
|
3458
|
+
writeStderr: (text) => io.writeStderr(redactOutput(text)),
|
|
3459
|
+
readStdin: () => io.readStdin(),
|
|
3460
|
+
stdinIsTerminal: io.stdinIsTerminal
|
|
3461
|
+
}
|
|
3462
|
+
};
|
|
3463
|
+
}
|
|
3464
|
+
|
|
3465
|
+
// src/status-command.ts
|
|
3466
|
+
import { createHimringClient as createHimringClient2, describeError as describeError3, isHimringApiError as isHimringApiError3 } from "@himring/sdk";
|
|
3467
|
+
var READY_STATUS = "ready";
|
|
3468
|
+
var REPORT_FIELDS = /* @__PURE__ */ new Set(["api", "api_url"]);
|
|
3469
|
+
var START_API_SUGGESTION = "Check that the API runs, and pass its address with --api-url or HIMRING_API_URL.";
|
|
3470
|
+
var NOT_READY_FAILURE = {
|
|
3471
|
+
code: "not_ready",
|
|
3472
|
+
message: "A service behind the API is not ready.",
|
|
3473
|
+
suggestion: "Find the dependency that reports down, then try again once it is up."
|
|
3474
|
+
};
|
|
3475
|
+
function failureFor2(error, apiUrl) {
|
|
3476
|
+
if (isHimringApiError3(error) && (error.kind === "network" || error.kind === "timeout")) {
|
|
3477
|
+
return {
|
|
3478
|
+
failure: {
|
|
3479
|
+
code: error.kind === "network" ? "api_unreachable" : "api_timeout",
|
|
3480
|
+
message: error.message,
|
|
3481
|
+
suggestion: START_API_SUGGESTION
|
|
3482
|
+
},
|
|
3483
|
+
exitCode: EXIT_CODES.network
|
|
3484
|
+
};
|
|
3485
|
+
}
|
|
3486
|
+
return {
|
|
3487
|
+
failure: {
|
|
3488
|
+
code: "unexpected_response",
|
|
3489
|
+
message: describeError3(error),
|
|
3490
|
+
suggestion: `Check that ${apiUrl} serves the Himring API.`
|
|
3491
|
+
},
|
|
3492
|
+
exitCode: EXIT_CODES.unexpected
|
|
3493
|
+
};
|
|
3494
|
+
}
|
|
3495
|
+
function writeReportText(io, report, apiUrl) {
|
|
3496
|
+
const dependencies = Object.entries(report.dependencies).filter(([name]) => !REPORT_FIELDS.has(name));
|
|
3497
|
+
io.writeStdout(formatText(Object.fromEntries([["api", report.status], ...dependencies, ["api_url", apiUrl]])));
|
|
3498
|
+
}
|
|
3499
|
+
function writeReport(io, report, options, metadata) {
|
|
3500
|
+
const ready = report.status === READY_STATUS;
|
|
3501
|
+
if (options.output === "text") {
|
|
3502
|
+
writeReportText(io, report, options.apiUrl);
|
|
3503
|
+
if (!ready) writeFailureText(io, NOT_READY_FAILURE);
|
|
3504
|
+
return;
|
|
3505
|
+
}
|
|
3506
|
+
writeEnvelope(
|
|
3507
|
+
io,
|
|
3508
|
+
ready ? { status: "success", data: report, error: null, metadata } : { status: "error", data: report, error: NOT_READY_FAILURE, metadata }
|
|
3509
|
+
);
|
|
3510
|
+
}
|
|
3511
|
+
async function runStatusCommand(options, io) {
|
|
3512
|
+
const startedAt = performance.now();
|
|
3513
|
+
const client = createHimringClient2({ baseUrl: options.apiUrl, timeoutMs: options.timeoutMs });
|
|
3514
|
+
const metadata = () => ({
|
|
3515
|
+
api_url: options.apiUrl,
|
|
3516
|
+
duration_ms: Math.round(performance.now() - startedAt)
|
|
3517
|
+
});
|
|
3518
|
+
let report;
|
|
3519
|
+
try {
|
|
3520
|
+
report = await client.getReadiness();
|
|
3521
|
+
} catch (error) {
|
|
3522
|
+
const { failure, exitCode } = failureFor2(error, options.apiUrl);
|
|
3523
|
+
if (options.output === "json") {
|
|
3524
|
+
writeEnvelope(io, { status: "error", data: null, error: failure, metadata: metadata() });
|
|
3525
|
+
} else {
|
|
3526
|
+
writeFailureText(io, failure);
|
|
3527
|
+
}
|
|
3528
|
+
return exitCode;
|
|
3529
|
+
}
|
|
3530
|
+
writeReport(io, report, options, metadata());
|
|
3531
|
+
return report.status === READY_STATUS ? EXIT_CODES.success : EXIT_CODES.notReady;
|
|
3532
|
+
}
|
|
3533
|
+
|
|
3534
|
+
// src/table-import-commands.ts
|
|
3535
|
+
import { HIMRING_OPERATION_CATALOGUE as HIMRING_OPERATION_CATALOGUE7 } from "@himring/sdk/catalogue";
|
|
3536
|
+
import { Option as Option10 } from "commander";
|
|
3537
|
+
import * as v9 from "valibot";
|
|
3538
|
+
var OPERATION6 = "upload_table_import";
|
|
3539
|
+
var commandOptionsSchema6 = v9.object({
|
|
3540
|
+
project: v9.optional(v9.string()),
|
|
3541
|
+
database: v9.optional(v9.string()),
|
|
3542
|
+
tableName: v9.optional(v9.string()),
|
|
3543
|
+
from: v9.optional(v9.string()),
|
|
3544
|
+
dryRun: v9.optional(v9.boolean())
|
|
3545
|
+
});
|
|
3546
|
+
var UPLOAD_EXAMPLES2 = `
|
|
3547
|
+
Examples:
|
|
3548
|
+
$ himring imports upload --database db_3a9e5c7b1d2f4e6a8c0b9d7f5e3a1c2b --table-name orders --from orders.csv
|
|
3549
|
+
$ himring imports upload --database db_3a9e5c7b1d2f4e6a8c0b9d7f5e3a1c2b --table-name suppliers --from suppliers.xlsx --output json
|
|
3550
|
+
|
|
3551
|
+
The first row of the file holds the column names. Then map them with himring imports check, and insert the rows with himring imports apply.`;
|
|
3552
|
+
function addTableImportCommands(program, contextFor, recordExitCode) {
|
|
3553
|
+
const group = program.commands.find((command) => command.name() === "imports");
|
|
3554
|
+
if (group === void 0) throw new Error("The upload command needs the imports group.");
|
|
3555
|
+
addProjectOption(group.command("upload").description(HIMRING_OPERATION_CATALOGUE7[OPERATION6].summary)).addOption(new Option10("--database <value>", "database_id (required)")).addOption(new Option10("--table-name <value>", "table_name, of a table that exists or a new one (required)")).requiredOption("--from <path>", "the local CSV or XLSX file").option("--dry-run", "check the input and show the request, without sending it").addHelpText("after", UPLOAD_EXAMPLES2).action(async (_options, invoked) => {
|
|
3556
|
+
const context = contextFor(invoked);
|
|
3557
|
+
if (context === void 0) return;
|
|
3558
|
+
const options = v9.parse(commandOptionsSchema6, invoked.opts());
|
|
3559
|
+
recordExitCode(
|
|
3560
|
+
await runCommand(
|
|
3561
|
+
context,
|
|
3562
|
+
() => sendFileBody(context, {
|
|
3563
|
+
id: OPERATION6,
|
|
3564
|
+
input: { project_id: options.project, database_id: options.database, table_name: options.tableName },
|
|
3565
|
+
from: options.from,
|
|
3566
|
+
dryRun: options.dryRun === true,
|
|
3567
|
+
suggestion: "Pass --project, --database, and --table-name.",
|
|
3568
|
+
splitHint: "Split the rows into several files and import each one."
|
|
3569
|
+
})
|
|
3570
|
+
)
|
|
3571
|
+
);
|
|
3572
|
+
});
|
|
3573
|
+
}
|
|
3574
|
+
|
|
3575
|
+
// src/program.ts
|
|
3576
|
+
var packageManifestSchema = v10.object({ version: v10.pipe(v10.string(), v10.nonEmpty()) });
|
|
3577
|
+
var CLI_VERSION = v10.parse(packageManifestSchema, createRequire(import.meta.url)("../package.json")).version;
|
|
3578
|
+
var CLI_VERSION_FLAGS = /* @__PURE__ */ new Set(["-V", "--version"]);
|
|
3579
|
+
var USER_ARGUMENTS_START = 2;
|
|
3580
|
+
var LONGEST_TIMER_DELAY_MS = 2147483647;
|
|
3581
|
+
var REFUSED_API_URL = "";
|
|
3582
|
+
var REFUSED_API_URL_FAILURE = {
|
|
3583
|
+
code: "usage",
|
|
3584
|
+
message: "The API address from --api-url or HIMRING_API_URL is not an http or https URL with no user name, password, query, or fragment.",
|
|
3585
|
+
suggestion: "Pass an address such as http://127.0.0.1:4000."
|
|
3586
|
+
};
|
|
3587
|
+
var VERSION_HELP = `
|
|
3588
|
+
Version:
|
|
3589
|
+
himring --version print the version of this CLI; after a command, --version picks a file version`;
|
|
3590
|
+
var globalOptionsSchema = v10.object({
|
|
3591
|
+
apiUrl: v10.string(),
|
|
3592
|
+
output: v10.picklist(OUTPUT_FORMATS),
|
|
3593
|
+
timeoutMs: v10.number()
|
|
3594
|
+
});
|
|
3595
|
+
var ENVIRONMENT_HELP = `
|
|
3596
|
+
Environment:
|
|
3597
|
+
HIMRING_API_URL base URL of the Himring API, in place of --api-url
|
|
3598
|
+
HIMRING_API_TIMEOUT_MS time limit of each request, in place of --timeout-ms
|
|
3599
|
+
HIMRING_API_KEY API key of a project, used in place of a signed-in session
|
|
3600
|
+
HIMRING_SESSION_TOKEN session token, used in place of the credentials file
|
|
3601
|
+
HIMRING_PROJECT project ID, in place of --project
|
|
3602
|
+
HIMRING_PASSWORD password, in place of --password-stdin
|
|
3603
|
+
HIMRING_CONFIG_DIR folder of credentials.json, by default $XDG_CONFIG_HOME/himring or ~/.config/himring`;
|
|
3604
|
+
function parseApiUrl(value) {
|
|
3605
|
+
return httpUrlOf(value) ?? REFUSED_API_URL;
|
|
3606
|
+
}
|
|
3607
|
+
function parseTimeoutMs(value) {
|
|
3608
|
+
const timeoutMs = wholeNumberInRangeOf(value, 1, LONGEST_TIMER_DELAY_MS);
|
|
3609
|
+
if (timeoutMs !== void 0) return timeoutMs;
|
|
3610
|
+
throw new InvalidArgumentError3(
|
|
3611
|
+
`Pass a whole number of milliseconds from 1 to ${LONGEST_TIMER_DELAY_MS}, such as 5000.`
|
|
3612
|
+
);
|
|
3613
|
+
}
|
|
3614
|
+
function buildProgram(io, environment, recordExitCode, protectSecret) {
|
|
3615
|
+
const program = new Command("himring").description("Work with Himring, the backend that lets AI agents answer from what your business knows.").addOption(
|
|
3616
|
+
new Option11("--api-url <url>", "base URL of the Himring API").env("HIMRING_API_URL").default(DEFAULT_HIMRING_API_URL).argParser(parseApiUrl)
|
|
3617
|
+
).addOption(new Option11("--output <format>", "output format").choices(OUTPUT_FORMATS).default("text")).addOption(
|
|
3618
|
+
new Option11("--timeout-ms <milliseconds>", "how long to wait for the API to respond").env("HIMRING_API_TIMEOUT_MS").default(DEFAULT_HIMRING_API_TIMEOUT_MS).argParser(parseTimeoutMs)
|
|
3619
|
+
).configureOutput({ writeOut: io.writeStdout, writeErr: io.writeStderr }).showHelpAfterError().exitOverride().addHelpText("after", `${VERSION_HELP}
|
|
3620
|
+
${ENVIRONMENT_HELP}
|
|
3621
|
+
${EXIT_CODE_HELP}`);
|
|
3622
|
+
const credentials = createCredentialsStore(environment);
|
|
3623
|
+
const contextFor = (command) => {
|
|
3624
|
+
const parsed = v10.safeParse(globalOptionsSchema, command.optsWithGlobals());
|
|
3625
|
+
if (parsed.success && parsed.output.apiUrl === REFUSED_API_URL) {
|
|
3626
|
+
writeFailure(io, parsed.output.output, REFUSED_API_URL_FAILURE, {});
|
|
3627
|
+
recordExitCode(EXIT_CODES.usage);
|
|
3628
|
+
return void 0;
|
|
3629
|
+
}
|
|
3630
|
+
if (parsed.success) return { io, protectSecret, environment, credentials, options: parsed.output };
|
|
3631
|
+
writeFailure(
|
|
3632
|
+
io,
|
|
3633
|
+
"text",
|
|
3634
|
+
{
|
|
3635
|
+
code: "usage",
|
|
3636
|
+
message: `The global options are invalid: ${v10.summarize(parsed.issues)}`,
|
|
3637
|
+
suggestion: "Read himring --help for the valid options."
|
|
3638
|
+
},
|
|
3639
|
+
{}
|
|
3640
|
+
);
|
|
3641
|
+
recordExitCode(EXIT_CODES.usage);
|
|
3642
|
+
return void 0;
|
|
3643
|
+
};
|
|
3644
|
+
program.command("status").description("Report whether the API and the services behind it are ready.").addHelpText(
|
|
3645
|
+
"after",
|
|
3646
|
+
`
|
|
3647
|
+
Examples:
|
|
3648
|
+
$ himring status
|
|
3649
|
+
$ himring status --output json
|
|
3650
|
+
$ HIMRING_API_URL=http://127.0.0.1:4000 himring status --timeout-ms 2000`
|
|
3651
|
+
).action(async (_options, command) => {
|
|
3652
|
+
const context = contextFor(command);
|
|
3653
|
+
if (context === void 0) return;
|
|
3654
|
+
recordExitCode(await runStatusCommand(context.options, io));
|
|
3655
|
+
});
|
|
3656
|
+
addAuthCommands(program, contextFor, recordExitCode);
|
|
3657
|
+
addOperationCommands(program, contextFor, recordExitCode);
|
|
3658
|
+
addFileCommands(program, contextFor, recordExitCode);
|
|
3659
|
+
addQuestionFileCommands(program, contextFor, recordExitCode);
|
|
3660
|
+
addIndexRecordFileCommands(program, contextFor, recordExitCode);
|
|
3661
|
+
addAnswerLogCommands(program, contextFor, recordExitCode);
|
|
3662
|
+
addTableImportCommands(program, contextFor, recordExitCode);
|
|
3663
|
+
return program;
|
|
3664
|
+
}
|
|
3665
|
+
async function runCli(argv, io, environment) {
|
|
3666
|
+
const output = secretOutput(io);
|
|
3667
|
+
output.protectSecret(environment.HIMRING_API_KEY);
|
|
3668
|
+
output.protectSecret(environment.HIMRING_SESSION_TOKEN);
|
|
3669
|
+
output.protectSecret(environment.HIMRING_PASSWORD);
|
|
3670
|
+
io = output.io;
|
|
3671
|
+
const [firstArgument, ...otherArguments] = argv.slice(USER_ARGUMENTS_START);
|
|
3672
|
+
if (firstArgument !== void 0 && otherArguments.length === 0 && CLI_VERSION_FLAGS.has(firstArgument)) {
|
|
3673
|
+
io.writeStdout(`${CLI_VERSION}
|
|
3674
|
+
`);
|
|
3675
|
+
return EXIT_CODES.success;
|
|
3676
|
+
}
|
|
3677
|
+
let exitCode = EXIT_CODES.success;
|
|
3678
|
+
const program = buildProgram(
|
|
3679
|
+
io,
|
|
3680
|
+
environment,
|
|
3681
|
+
(recordedExitCode) => {
|
|
3682
|
+
exitCode = recordedExitCode;
|
|
3683
|
+
},
|
|
3684
|
+
output.protectSecret
|
|
3685
|
+
);
|
|
3686
|
+
try {
|
|
3687
|
+
await program.parseAsync([...argv]);
|
|
3688
|
+
} catch (error) {
|
|
3689
|
+
if (error instanceof CommanderError) {
|
|
3690
|
+
return error.exitCode === 0 ? EXIT_CODES.success : EXIT_CODES.usage;
|
|
3691
|
+
}
|
|
3692
|
+
io.writeStderr(`Error: ${describeError4(error)}
|
|
3693
|
+
`);
|
|
3694
|
+
return EXIT_CODES.unexpected;
|
|
3695
|
+
}
|
|
3696
|
+
return exitCode;
|
|
3697
|
+
}
|
|
3698
|
+
|
|
3699
|
+
// src/standard-input.ts
|
|
3700
|
+
async function readCapped(stream) {
|
|
3701
|
+
const chunks = [];
|
|
3702
|
+
let total = 0;
|
|
3703
|
+
for await (const chunk of stream) {
|
|
3704
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
3705
|
+
total += bytes.byteLength;
|
|
3706
|
+
if (total > MAXIMUM_LOCAL_INPUT_BYTES) {
|
|
3707
|
+
stream.destroy();
|
|
3708
|
+
throw new UsageError("stdin holds more than 8 MiB.", "Split the input into smaller requests.");
|
|
3709
|
+
}
|
|
3710
|
+
chunks.push(bytes);
|
|
3711
|
+
}
|
|
3712
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
3713
|
+
}
|
|
3714
|
+
function readStandardInputOnce(stream) {
|
|
3715
|
+
let alreadyRead = false;
|
|
3716
|
+
return async () => {
|
|
3717
|
+
if (alreadyRead) {
|
|
3718
|
+
throw new UsageError(
|
|
3719
|
+
"Two options asked to read stdin.",
|
|
3720
|
+
"Read at most one input from stdin, and pass the others as files."
|
|
3721
|
+
);
|
|
3722
|
+
}
|
|
3723
|
+
alreadyRead = true;
|
|
3724
|
+
return readCapped(stream);
|
|
3725
|
+
};
|
|
3726
|
+
}
|
|
3727
|
+
|
|
3728
|
+
// src/main.ts
|
|
3729
|
+
function writeStdout(text) {
|
|
3730
|
+
process.stdout.write(text);
|
|
3731
|
+
}
|
|
3732
|
+
function writeStderr(text) {
|
|
3733
|
+
process.stderr.write(text);
|
|
3734
|
+
}
|
|
3735
|
+
process.exitCode = await runCli(
|
|
3736
|
+
process.argv,
|
|
3737
|
+
{
|
|
3738
|
+
writeStdout,
|
|
3739
|
+
writeStderr,
|
|
3740
|
+
readStdin: readStandardInputOnce(process.stdin),
|
|
3741
|
+
stdinIsTerminal: process.stdin.isTTY === true
|
|
3742
|
+
},
|
|
3743
|
+
process.env
|
|
3744
|
+
);
|