@sol-merrai/cli 0.1.3 → 0.2.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/README.md +122 -81
- package/dist/bin.mjs +834 -0
- package/dist/bin.mjs.map +1 -0
- package/dist/index.d.mts +590 -25
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +135 -2
- package/dist/index.mjs.map +1 -0
- package/package.json +8 -6
- package/.env.example +0 -3
- package/.env.prod.example +0 -3
- package/dist/cli.d.mts +0 -1
- package/dist/cli.mjs +0 -234
- package/dist/cli.mjs.map +0 -1
- package/dist/client-BirYnOM4.mjs +0 -27
- package/dist/client-BirYnOM4.mjs.map +0 -1
package/dist/bin.mjs
ADDED
|
@@ -0,0 +1,834 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { ORPCError, createORPCClient } from "@orpc/client";
|
|
3
|
+
import { RPCLink } from "@orpc/client/fetch";
|
|
4
|
+
import { Command, CommanderError, InvalidArgumentError } from "commander";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import fs$1 from "node:fs/promises";
|
|
9
|
+
import { createInterface } from "node:readline/promises";
|
|
10
|
+
|
|
11
|
+
//#region src/client.ts
|
|
12
|
+
const resolveBaseURL = (baseURL) => {
|
|
13
|
+
const resolved = baseURL?.trim();
|
|
14
|
+
if (!resolved) throw new Error("baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials");
|
|
15
|
+
return resolved.endsWith("/") ? resolved.slice(0, -1) : resolved;
|
|
16
|
+
};
|
|
17
|
+
const resolveHeaders = (headers, apiKey, cookie) => {
|
|
18
|
+
const resolvedHeaders = new Headers(headers);
|
|
19
|
+
if (apiKey) resolvedHeaders.set("x-api-key", apiKey);
|
|
20
|
+
if (cookie) resolvedHeaders.set("Cookie", cookie);
|
|
21
|
+
return Object.fromEntries(resolvedHeaders.entries());
|
|
22
|
+
};
|
|
23
|
+
const createRawMerraiClient = (options = {}) => {
|
|
24
|
+
return createORPCClient(new RPCLink({
|
|
25
|
+
fetch: options.fetch,
|
|
26
|
+
headers: () => resolveHeaders(options.headers, options.apiKey, options.cookie),
|
|
27
|
+
url: `${resolveBaseURL(options.baseURL)}/rpc`
|
|
28
|
+
}));
|
|
29
|
+
};
|
|
30
|
+
const createMerraiThrowingClient = (options = {}) => createRawMerraiClient(options);
|
|
31
|
+
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region package.json
|
|
34
|
+
var version = "0.2.0";
|
|
35
|
+
|
|
36
|
+
//#endregion
|
|
37
|
+
//#region src/config.ts
|
|
38
|
+
const DEFAULT_MERRAI_BASE_URL = "https://api.merrai.app";
|
|
39
|
+
const CREDENTIALS_VERSION = 1;
|
|
40
|
+
const trimmed = (value) => {
|
|
41
|
+
const result = value?.trim();
|
|
42
|
+
return result === void 0 || result.length === 0 ? void 0 : result;
|
|
43
|
+
};
|
|
44
|
+
const isUnknownRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
45
|
+
const resolveHomeDirectory = (env) => trimmed(env.HOME) ?? trimmed(env.USERPROFILE) ?? os.homedir();
|
|
46
|
+
const resolveMerraiConfigPaths = (env) => {
|
|
47
|
+
const home = resolveHomeDirectory(env);
|
|
48
|
+
const xdgConfigHome = trimmed(env.XDG_CONFIG_HOME);
|
|
49
|
+
const windowsAppData = trimmed(env.APPDATA);
|
|
50
|
+
const directory = xdgConfigHome ? path.join(xdgConfigHome, "merrai") : process.platform === "win32" && windowsAppData ? path.join(windowsAppData, "Merrai") : path.join(home, ".config", "merrai");
|
|
51
|
+
return {
|
|
52
|
+
credentials: path.join(directory, "credentials.json"),
|
|
53
|
+
directory,
|
|
54
|
+
legacyClaudeCredentials: path.join(home, ".merrai-claude-code", "credentials.json")
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
const parseCredentials = (raw, options) => {
|
|
58
|
+
try {
|
|
59
|
+
const value = JSON.parse(raw);
|
|
60
|
+
if (!isUnknownRecord(value)) return null;
|
|
61
|
+
if (options.requireVersion && value.version !== CREDENTIALS_VERSION) return null;
|
|
62
|
+
const apiKey = typeof value.apiKey === "string" ? trimmed(value.apiKey) : void 0;
|
|
63
|
+
const baseURL = typeof value.baseURL === "string" ? trimmed(value.baseURL) : void 0;
|
|
64
|
+
if (apiKey === void 0) return null;
|
|
65
|
+
return {
|
|
66
|
+
apiKey,
|
|
67
|
+
...baseURL === void 0 ? {} : { baseURL },
|
|
68
|
+
savedAt: typeof value.savedAt === "string" ? value.savedAt : (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
69
|
+
version: CREDENTIALS_VERSION
|
|
70
|
+
};
|
|
71
|
+
} catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const readCredentialsFile = (file, options) => {
|
|
76
|
+
if (!fs.existsSync(file)) return null;
|
|
77
|
+
try {
|
|
78
|
+
const credentials = parseCredentials(fs.readFileSync(file, "utf8"), { requireVersion: options.requireVersion });
|
|
79
|
+
if (credentials === null && options.strict) throw new Error(`Invalid Merrai credentials file at ${file}. Run 'merrai auth set-key' to replace it.`);
|
|
80
|
+
return credentials;
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (options.strict) throw error;
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const loadMerraiCredentials = (env, options = {}) => {
|
|
87
|
+
const paths = resolveMerraiConfigPaths(env);
|
|
88
|
+
return readCredentialsFile(paths.credentials, {
|
|
89
|
+
requireVersion: true,
|
|
90
|
+
strict: options.strict === true
|
|
91
|
+
}) ?? readCredentialsFile(paths.legacyClaudeCredentials, {
|
|
92
|
+
requireVersion: false,
|
|
93
|
+
strict: options.strict === true
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
const saveMerraiCredentials = (env, input) => {
|
|
97
|
+
const apiKey = trimmed(input.apiKey);
|
|
98
|
+
if (apiKey === void 0) throw new Error("API key cannot be empty");
|
|
99
|
+
const paths = resolveMerraiConfigPaths(env);
|
|
100
|
+
fs.mkdirSync(paths.directory, {
|
|
101
|
+
mode: 448,
|
|
102
|
+
recursive: true
|
|
103
|
+
});
|
|
104
|
+
fs.chmodSync(paths.directory, 448);
|
|
105
|
+
const credentials = {
|
|
106
|
+
apiKey,
|
|
107
|
+
baseURL: trimmed(input.baseURL) ?? DEFAULT_MERRAI_BASE_URL,
|
|
108
|
+
savedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
109
|
+
version: CREDENTIALS_VERSION
|
|
110
|
+
};
|
|
111
|
+
fs.writeFileSync(paths.credentials, JSON.stringify(credentials, null, 2), { mode: 384 });
|
|
112
|
+
fs.chmodSync(paths.credentials, 384);
|
|
113
|
+
return credentials;
|
|
114
|
+
};
|
|
115
|
+
const removeFileIfPresent = (file) => {
|
|
116
|
+
try {
|
|
117
|
+
fs.unlinkSync(file);
|
|
118
|
+
return true;
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
const clearMerraiCredentials = (env, options = {}) => {
|
|
125
|
+
const paths = resolveMerraiConfigPaths(env);
|
|
126
|
+
const removedShared = removeFileIfPresent(paths.credentials);
|
|
127
|
+
const removedLegacy = options.includeLegacy === true ? removeFileIfPresent(paths.legacyClaudeCredentials) : false;
|
|
128
|
+
return removedShared || removedLegacy;
|
|
129
|
+
};
|
|
130
|
+
const resolveMerraiClientOptions = (env, overrides, options = {}) => {
|
|
131
|
+
const apiKeyOverride = trimmed(overrides.apiKey) ?? trimmed(env.MERRAI_API_KEY);
|
|
132
|
+
const baseURLOverride = trimmed(overrides.baseURL) ?? trimmed(env.MERRAI_BASE_URL);
|
|
133
|
+
const credentials = apiKeyOverride !== void 0 && baseURLOverride !== void 0 ? null : loadMerraiCredentials(env, { strict: options.strictCredentials !== false });
|
|
134
|
+
return {
|
|
135
|
+
apiKey: apiKeyOverride ?? credentials?.apiKey,
|
|
136
|
+
baseURL: baseURLOverride ?? credentials?.baseURL ?? DEFAULT_MERRAI_BASE_URL,
|
|
137
|
+
cookie: trimmed(overrides.cookie) ?? trimmed(env.MERRAI_COOKIE)
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region src/errors.ts
|
|
143
|
+
const MERRAI_CLI_EXIT_CODES = {
|
|
144
|
+
auth: 3,
|
|
145
|
+
network: 10,
|
|
146
|
+
notFound: 4,
|
|
147
|
+
rateLimit: 5,
|
|
148
|
+
success: 0,
|
|
149
|
+
usage: 2
|
|
150
|
+
};
|
|
151
|
+
var MerraiCliUsageError = class extends Error {
|
|
152
|
+
constructor(message, options) {
|
|
153
|
+
super(message, options);
|
|
154
|
+
this.name = "MerraiCliUsageError";
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
const renderJsonError = (message, metadata = {}) => JSON.stringify({ error: {
|
|
158
|
+
...metadata,
|
|
159
|
+
message
|
|
160
|
+
} }, null, 2);
|
|
161
|
+
const renderOrpcError = (error) => renderJsonError(error.message, {
|
|
162
|
+
code: error.code,
|
|
163
|
+
...error.data === void 0 ? {} : { data: error.data },
|
|
164
|
+
status: error.status
|
|
165
|
+
});
|
|
166
|
+
const classifyMerraiCliError = (error) => {
|
|
167
|
+
if (error instanceof CommanderError) return {
|
|
168
|
+
exitCode: error.code === "commander.helpDisplayed" || error.code === "commander.version" ? MERRAI_CLI_EXIT_CODES.success : MERRAI_CLI_EXIT_CODES.usage,
|
|
169
|
+
message: error.message,
|
|
170
|
+
shouldRender: false
|
|
171
|
+
};
|
|
172
|
+
if (error instanceof MerraiCliUsageError) return {
|
|
173
|
+
exitCode: MERRAI_CLI_EXIT_CODES.usage,
|
|
174
|
+
message: renderJsonError(error.message, { code: "USAGE_ERROR" }),
|
|
175
|
+
shouldRender: true
|
|
176
|
+
};
|
|
177
|
+
if (error instanceof ORPCError) {
|
|
178
|
+
const code = error.code;
|
|
179
|
+
if (code === "BAD_REQUEST" || code === "UNPROCESSABLE_CONTENT") return {
|
|
180
|
+
exitCode: MERRAI_CLI_EXIT_CODES.usage,
|
|
181
|
+
message: renderOrpcError(error),
|
|
182
|
+
shouldRender: true
|
|
183
|
+
};
|
|
184
|
+
if (code === "UNAUTHORIZED" || code === "FORBIDDEN") return {
|
|
185
|
+
exitCode: MERRAI_CLI_EXIT_CODES.auth,
|
|
186
|
+
message: renderOrpcError(error),
|
|
187
|
+
shouldRender: true
|
|
188
|
+
};
|
|
189
|
+
if (code === "NOT_FOUND" || code === "CONFLICT") return {
|
|
190
|
+
exitCode: MERRAI_CLI_EXIT_CODES.notFound,
|
|
191
|
+
message: renderOrpcError(error),
|
|
192
|
+
shouldRender: true
|
|
193
|
+
};
|
|
194
|
+
if (code === "RATE_LIMITED" || code === "TOO_MANY_REQUESTS" || code === "PAYLOAD_TOO_LARGE" || code === "RESOURCE_EXHAUSTED" || error.status === 429) return {
|
|
195
|
+
exitCode: MERRAI_CLI_EXIT_CODES.rateLimit,
|
|
196
|
+
message: renderOrpcError(error),
|
|
197
|
+
shouldRender: true
|
|
198
|
+
};
|
|
199
|
+
return {
|
|
200
|
+
exitCode: MERRAI_CLI_EXIT_CODES.network,
|
|
201
|
+
message: renderOrpcError(error),
|
|
202
|
+
shouldRender: true
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
exitCode: MERRAI_CLI_EXIT_CODES.network,
|
|
207
|
+
message: renderJsonError(error instanceof Error ? error.message : String(error), { code: "NETWORK_ERROR" }),
|
|
208
|
+
shouldRender: true
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
//#endregion
|
|
213
|
+
//#region src/input.ts
|
|
214
|
+
const readStream = async (stream) => {
|
|
215
|
+
const chunks = [];
|
|
216
|
+
for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
|
|
217
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
218
|
+
};
|
|
219
|
+
const readFileOrStdin = async (options) => {
|
|
220
|
+
if (options.file === "-") return readStream(options.stdin);
|
|
221
|
+
const resolvedPath = path.resolve(options.cwd, options.file);
|
|
222
|
+
try {
|
|
223
|
+
return await fs$1.readFile(resolvedPath, "utf8");
|
|
224
|
+
} catch (error) {
|
|
225
|
+
throw new MerraiCliUsageError(`Unable to read ${resolvedPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
const readStructuredInput = async (options) => {
|
|
229
|
+
if (options.file !== void 0 && options.input !== void 0) throw new MerraiCliUsageError("Use only one of --input or --file");
|
|
230
|
+
if (options.file === void 0 && options.input === void 0) throw new MerraiCliUsageError("Provide --input <json> or --file <path|->");
|
|
231
|
+
const source = options.input ?? await readFileOrStdin({
|
|
232
|
+
cwd: options.cwd,
|
|
233
|
+
file: options.file,
|
|
234
|
+
stdin: options.stdin
|
|
235
|
+
});
|
|
236
|
+
try {
|
|
237
|
+
return JSON.parse(source);
|
|
238
|
+
} catch (error) {
|
|
239
|
+
throw new MerraiCliUsageError(`Invalid JSON from ${options.file === void 0 ? "--input" : options.file}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
const readTextInput = async (options) => {
|
|
243
|
+
const directValues = [options.positional, options.option].filter((value) => value !== void 0);
|
|
244
|
+
if (directValues.length > 1 || options.file !== void 0 && directValues.length > 0) throw new MerraiCliUsageError("Provide memory text using only one positional value, --memory, or --file");
|
|
245
|
+
const value = directValues[0] ?? (options.file === void 0 ? void 0 : await readFileOrStdin({
|
|
246
|
+
cwd: options.cwd,
|
|
247
|
+
file: options.file,
|
|
248
|
+
stdin: options.stdin
|
|
249
|
+
}));
|
|
250
|
+
if (value === void 0 || value.trim().length === 0) throw new MerraiCliUsageError("Memory text cannot be empty");
|
|
251
|
+
return value;
|
|
252
|
+
};
|
|
253
|
+
const confirmAction = async (options) => {
|
|
254
|
+
if (!("isTTY" in options.input && options.input.isTTY === true)) return false;
|
|
255
|
+
const prompt = createInterface({
|
|
256
|
+
input: options.input,
|
|
257
|
+
output: options.output
|
|
258
|
+
});
|
|
259
|
+
try {
|
|
260
|
+
const answer = await prompt.question(`${options.message} [y/N] `);
|
|
261
|
+
return answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes";
|
|
262
|
+
} finally {
|
|
263
|
+
prompt.close();
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
const readSecretInput = async (options) => {
|
|
267
|
+
const input = options.input;
|
|
268
|
+
if (input.isTTY !== true || input.setRawMode === void 0) throw new MerraiCliUsageError("Provide the API key as an argument or through MERRAI_API_KEY in noninteractive use");
|
|
269
|
+
options.output.write(options.message);
|
|
270
|
+
const wasRaw = input.isRaw === true;
|
|
271
|
+
input.setRawMode(true);
|
|
272
|
+
return new Promise((resolve, reject) => {
|
|
273
|
+
let value = "";
|
|
274
|
+
const cleanup = () => {
|
|
275
|
+
input.off("data", onData);
|
|
276
|
+
input.off("end", onEnd);
|
|
277
|
+
input.off("error", onError);
|
|
278
|
+
input.setRawMode?.(wasRaw);
|
|
279
|
+
input.pause();
|
|
280
|
+
};
|
|
281
|
+
const rejectInput = (error) => {
|
|
282
|
+
cleanup();
|
|
283
|
+
reject(error);
|
|
284
|
+
};
|
|
285
|
+
const onEnd = () => {
|
|
286
|
+
rejectInput(new MerraiCliUsageError("API key entry ended unexpectedly"));
|
|
287
|
+
};
|
|
288
|
+
const onError = (error) => {
|
|
289
|
+
rejectInput(new MerraiCliUsageError(`Unable to read API key: ${error.message}`, { cause: error }));
|
|
290
|
+
};
|
|
291
|
+
const onData = (chunk) => {
|
|
292
|
+
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk;
|
|
293
|
+
for (const character of text) {
|
|
294
|
+
if (character === "\r" || character === "\n") {
|
|
295
|
+
options.output.write("\n");
|
|
296
|
+
cleanup();
|
|
297
|
+
resolve(value);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
if (character === "" || character === "") {
|
|
301
|
+
options.output.write("\n");
|
|
302
|
+
rejectInput(new MerraiCliUsageError("API key entry cancelled"));
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (character === "" || character === "\b") {
|
|
306
|
+
if (value.length > 0) {
|
|
307
|
+
value = value.slice(0, -1);
|
|
308
|
+
options.output.write("\b \b");
|
|
309
|
+
}
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
value += character;
|
|
313
|
+
options.output.write("*");
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
input.on("data", onData);
|
|
317
|
+
input.once("end", onEnd);
|
|
318
|
+
input.once("error", onError);
|
|
319
|
+
input.resume();
|
|
320
|
+
});
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
//#endregion
|
|
324
|
+
//#region src/commands/auth.ts
|
|
325
|
+
const registerAuthCommands = (program, context) => {
|
|
326
|
+
const auth = program.command("auth").description("Manage CLI credentials");
|
|
327
|
+
auth.command("set-key").argument("[apiKey]", "Merrai API key").description("Validate and save an API key").action(async (positional, _options, actionCommand) => {
|
|
328
|
+
const globals = actionCommand.optsWithGlobals();
|
|
329
|
+
const apiKey = positional?.trim() || globals.apiKey?.trim() || context.runtime.env.MERRAI_API_KEY?.trim() || await readSecretInput({
|
|
330
|
+
input: context.runtime.stdin,
|
|
331
|
+
message: "Merrai API key: ",
|
|
332
|
+
output: context.runtime.stderr
|
|
333
|
+
});
|
|
334
|
+
if (apiKey.length === 0) throw new MerraiCliUsageError("API key cannot be empty");
|
|
335
|
+
const connection = resolveMerraiClientOptions(context.runtime.env, {
|
|
336
|
+
apiKey,
|
|
337
|
+
baseURL: globals.baseUrl
|
|
338
|
+
}, { strictCredentials: false });
|
|
339
|
+
await context.runtime.createClient(connection).memoryStatus({});
|
|
340
|
+
const credentials = saveMerraiCredentials(context.runtime.env, {
|
|
341
|
+
apiKey,
|
|
342
|
+
baseURL: connection.baseURL
|
|
343
|
+
});
|
|
344
|
+
context.output(actionCommand).data({
|
|
345
|
+
authenticated: true,
|
|
346
|
+
baseURL: credentials.baseURL
|
|
347
|
+
}, () => `Saved API key for ${credentials.baseURL}.`);
|
|
348
|
+
});
|
|
349
|
+
auth.command("status").description("Show credential status without revealing the key").action(async (_options, actionCommand) => {
|
|
350
|
+
const credentials = loadMerraiCredentials(context.runtime.env, { strict: true });
|
|
351
|
+
const paths = resolveMerraiConfigPaths(context.runtime.env);
|
|
352
|
+
const result = {
|
|
353
|
+
authenticated: credentials !== null || (context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0,
|
|
354
|
+
baseURL: credentials?.baseURL ?? null,
|
|
355
|
+
configured: credentials !== null,
|
|
356
|
+
credentialsPath: paths.credentials,
|
|
357
|
+
environmentKeySet: (context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0
|
|
358
|
+
};
|
|
359
|
+
context.output(actionCommand).data(result, () => result.configured ? `Authenticated for ${result.baseURL}.` : result.environmentKeySet ? "Authenticated through MERRAI_API_KEY." : "No saved CLI credentials.");
|
|
360
|
+
});
|
|
361
|
+
auth.command("logout").description("Remove saved CLI credentials").option("--yes", "Skip confirmation").action(async (options, actionCommand) => {
|
|
362
|
+
if (options.yes !== true) {
|
|
363
|
+
if (!await confirmAction({
|
|
364
|
+
input: context.runtime.stdin,
|
|
365
|
+
message: "Remove saved Merrai CLI credentials?",
|
|
366
|
+
output: context.runtime.stderr
|
|
367
|
+
})) throw new MerraiCliUsageError("Logout cancelled. Use --yes for noninteractive confirmation.");
|
|
368
|
+
}
|
|
369
|
+
const removed = clearMerraiCredentials(context.runtime.env, { includeLegacy: true });
|
|
370
|
+
const output = context.output(actionCommand);
|
|
371
|
+
output.data({ removed }, () => removed ? "Removed saved credentials." : "No saved credentials found.");
|
|
372
|
+
if ((context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0) output.diagnostic("MERRAI_API_KEY is still set; commands will continue using it.");
|
|
373
|
+
});
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
//#endregion
|
|
377
|
+
//#region src/commands/debug.ts
|
|
378
|
+
const configureRpcCommand = (command, context) => {
|
|
379
|
+
command.argument("<procedure>", "Top-level oRPC procedure").option("--input <json>", "Inline JSON input").option("--file <path>", "Read JSON input from a file, or - for stdin").action(async (procedureName, options, actionCommand) => {
|
|
380
|
+
const client = context.client(actionCommand);
|
|
381
|
+
const procedure = Reflect.get(client, procedureName);
|
|
382
|
+
if (typeof procedure !== "function") throw new MerraiCliUsageError(`Unknown procedure: ${procedureName}`);
|
|
383
|
+
const result = await procedure(options.input !== void 0 || options.file !== void 0 ? await readStructuredInput({
|
|
384
|
+
cwd: context.runtime.cwd,
|
|
385
|
+
file: options.file,
|
|
386
|
+
input: options.input,
|
|
387
|
+
stdin: context.runtime.stdin
|
|
388
|
+
}) : void 0);
|
|
389
|
+
context.output(actionCommand).data(result);
|
|
390
|
+
});
|
|
391
|
+
};
|
|
392
|
+
const registerDebugCommands = (program, context) => {
|
|
393
|
+
configureRpcCommand(program.command("debug").description("Unstable debugging commands").command("rpc").description("Call a top-level oRPC procedure"), context);
|
|
394
|
+
configureRpcCommand(program.command("rpc", { hidden: true }).description("Legacy raw oRPC command"), context);
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
//#endregion
|
|
398
|
+
//#region src/commands/shared.ts
|
|
399
|
+
const ISO_8601_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
|
|
400
|
+
const resolveLobeKey = (options) => options.lobe ?? options.lobeKey;
|
|
401
|
+
const parseIntegerOption = (value, name, range) => {
|
|
402
|
+
if (value === void 0) return;
|
|
403
|
+
const parsed = Number(value);
|
|
404
|
+
if (!Number.isInteger(parsed) || parsed < range.minimum || parsed > range.maximum) throw new MerraiCliUsageError(`${name} must be an integer from ${range.minimum} to ${range.maximum}`);
|
|
405
|
+
return parsed;
|
|
406
|
+
};
|
|
407
|
+
const parseNumberOption = (value, name, range) => {
|
|
408
|
+
if (value === void 0) return;
|
|
409
|
+
const parsed = Number(value);
|
|
410
|
+
if (!Number.isFinite(parsed) || parsed < range.minimum || parsed > range.maximum) throw new MerraiCliUsageError(`${name} must be a number from ${range.minimum} to ${range.maximum}`);
|
|
411
|
+
return parsed;
|
|
412
|
+
};
|
|
413
|
+
const parseDateOption = (value, name) => {
|
|
414
|
+
if (value === void 0) return;
|
|
415
|
+
if (!ISO_8601_DATETIME_PATTERN.test(value) || Number.isNaN(new Date(value).getTime())) throw new MerraiCliUsageError(`${name} must be a valid ISO 8601 datetime`);
|
|
416
|
+
return value;
|
|
417
|
+
};
|
|
418
|
+
const parseEntityType = (value) => {
|
|
419
|
+
if (value === void 0) return;
|
|
420
|
+
switch (value) {
|
|
421
|
+
case "action":
|
|
422
|
+
case "document":
|
|
423
|
+
case "event":
|
|
424
|
+
case "knowledge":
|
|
425
|
+
case "person": return value;
|
|
426
|
+
default: throw new MerraiCliUsageError("--type must be one of: person, event, action, knowledge, document");
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
|
|
430
|
+
//#endregion
|
|
431
|
+
//#region src/commands/entity.ts
|
|
432
|
+
const renderEntities = (result) => {
|
|
433
|
+
if (result.entities.length === 0) return "No matching entities found.";
|
|
434
|
+
return result.entities.map((entity) => `- ${entity.displayName} (${entity.type}, ${entity.memoryCount} memories) — ${entity.id}`).join("\n");
|
|
435
|
+
};
|
|
436
|
+
const renderEntityMemories = (result) => {
|
|
437
|
+
const heading = `# ${result.entity.displayName} (${result.entity.type})`;
|
|
438
|
+
if (result.memories.length === 0) return `${heading}\nNo linked memories.`;
|
|
439
|
+
return `${heading}\n${result.memories.map((memory) => `- ${memory.recordedAt.slice(0, 10)} — ${memory.content}`).join("\n")}`;
|
|
440
|
+
};
|
|
441
|
+
const configureFindCommand = (command, context) => {
|
|
442
|
+
command.argument("[name]", "Entity name").option("--name <name>", "Entity name").option("--type <type>", "person, event, action, knowledge, or document").option("--limit <number>", "Maximum results").action(async (positional, options, actionCommand) => {
|
|
443
|
+
const name = options.name ?? positional;
|
|
444
|
+
if (name === void 0 || name.trim().length === 0) throw new MerraiCliUsageError("Provide an entity name");
|
|
445
|
+
const input = {
|
|
446
|
+
limit: parseIntegerOption(options.limit, "--limit", {
|
|
447
|
+
maximum: 25,
|
|
448
|
+
minimum: 1
|
|
449
|
+
}),
|
|
450
|
+
name,
|
|
451
|
+
type: parseEntityType(options.type)
|
|
452
|
+
};
|
|
453
|
+
const result = await context.client(actionCommand).findMemoryEntities(input);
|
|
454
|
+
context.output(actionCommand).data(result, renderEntities);
|
|
455
|
+
});
|
|
456
|
+
};
|
|
457
|
+
const configureMemoriesCommand = (command, context) => {
|
|
458
|
+
command.argument("[entityId]", "Entity id").option("--entity-id <id>", "Entity id").option("--limit <number>", "Maximum results").action(async (positional, options, actionCommand) => {
|
|
459
|
+
const entityId = options.entityId ?? positional;
|
|
460
|
+
if (entityId === void 0 || entityId.trim().length === 0) throw new MerraiCliUsageError("Provide an entity id");
|
|
461
|
+
const input = {
|
|
462
|
+
entityId,
|
|
463
|
+
limit: parseIntegerOption(options.limit, "--limit", {
|
|
464
|
+
maximum: 50,
|
|
465
|
+
minimum: 1
|
|
466
|
+
})
|
|
467
|
+
};
|
|
468
|
+
const result = await context.client(actionCommand).memoriesByEntity(input);
|
|
469
|
+
context.output(actionCommand).data(result, renderEntityMemories);
|
|
470
|
+
});
|
|
471
|
+
};
|
|
472
|
+
const registerEntityCommands = (program, context) => {
|
|
473
|
+
const entity = program.command("entity").description("Find memory entities");
|
|
474
|
+
configureFindCommand(entity.command("find").description("Find entities by name"), context);
|
|
475
|
+
configureFindCommand(program.command("find-entity", { hidden: true }).description("Legacy entity find"), context);
|
|
476
|
+
configureMemoriesCommand(entity.command("memories").description("Recall memories linked to an entity"), context);
|
|
477
|
+
configureMemoriesCommand(program.command("search-memories-by-entity", { hidden: true }).description("Legacy entity recall"), context);
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
//#endregion
|
|
481
|
+
//#region src/commands/ingest.ts
|
|
482
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
483
|
+
const parseMemoriesInput = (value) => {
|
|
484
|
+
if (!Array.isArray(value)) throw new MerraiCliUsageError("Memory ingest input must be a JSON array");
|
|
485
|
+
return { memories: value };
|
|
486
|
+
};
|
|
487
|
+
const parseChatInput = (value) => {
|
|
488
|
+
if (!isRecord(value) || !Array.isArray(value.memories)) throw new MerraiCliUsageError("Chat ingest input must be an object containing a memories array");
|
|
489
|
+
return value;
|
|
490
|
+
};
|
|
491
|
+
const parseChatsInput = (value) => {
|
|
492
|
+
if (!isRecord(value) || !Array.isArray(value.sessions)) throw new MerraiCliUsageError("Multi-chat ingest input must be an object containing a sessions array");
|
|
493
|
+
return value;
|
|
494
|
+
};
|
|
495
|
+
const configureStructuredCommand = (command, context, parse, submit) => {
|
|
496
|
+
command.option("--input <json>", "Inline JSON input").option("--file <path>", "Read JSON from a file, or - for stdin").action(async (options, actionCommand) => {
|
|
497
|
+
const result = await submit(actionCommand, parse(await readStructuredInput({
|
|
498
|
+
cwd: context.runtime.cwd,
|
|
499
|
+
file: options.file,
|
|
500
|
+
input: options.input,
|
|
501
|
+
stdin: context.runtime.stdin
|
|
502
|
+
})));
|
|
503
|
+
context.output(actionCommand).data(result, () => "Ingest queued.");
|
|
504
|
+
});
|
|
505
|
+
};
|
|
506
|
+
const registerIngestCommands = (program, context) => {
|
|
507
|
+
const ingest = program.command("ingest").description("Bulk memory ingestion");
|
|
508
|
+
const registerMemories = (command) => configureStructuredCommand(command, context, parseMemoriesInput, async (actionCommand, input) => context.client(actionCommand).addMemories(input));
|
|
509
|
+
registerMemories(ingest.command("memories").description("Ingest memories"));
|
|
510
|
+
registerMemories(program.command("add-memories", { hidden: true }).description("Legacy memory ingest"));
|
|
511
|
+
const registerChat = (command) => configureStructuredCommand(command, context, parseChatInput, async (actionCommand, input) => context.client(actionCommand).addChatSession(input));
|
|
512
|
+
registerChat(ingest.command("chat").description("Ingest one chat session"));
|
|
513
|
+
registerChat(program.command("add-chat-session", { hidden: true }).description("Legacy chat ingest"));
|
|
514
|
+
const registerChats = (command) => configureStructuredCommand(command, context, parseChatsInput, async (actionCommand, input) => context.client(actionCommand).addChatSessions(input));
|
|
515
|
+
registerChats(ingest.command("chats").description("Ingest multiple chat sessions"));
|
|
516
|
+
registerChats(program.command("add-chat-sessions", { hidden: true }).description("Legacy multi-chat ingest"));
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
//#endregion
|
|
520
|
+
//#region src/commands/living-document.ts
|
|
521
|
+
const renderDocumentList = (value) => {
|
|
522
|
+
if (value.documents.length === 0) return "No living documents found.";
|
|
523
|
+
return value.documents.map((document) => `- ${document.title} — ${document.id}`).join("\n");
|
|
524
|
+
};
|
|
525
|
+
const configureGetCommand = (command, context) => {
|
|
526
|
+
command.argument("[documentId]", "Living document id").option("--document-id <id>", "Living document id").action(async (positional, options, actionCommand) => {
|
|
527
|
+
const documentId = options.documentId ?? positional;
|
|
528
|
+
if (documentId === void 0 || documentId.trim().length === 0) throw new MerraiCliUsageError("Provide a living document id");
|
|
529
|
+
const result = await context.client(actionCommand).recall.readLivingDocument({ documentId });
|
|
530
|
+
context.output(actionCommand).data(result, (value) => JSON.stringify(value, null, 2));
|
|
531
|
+
});
|
|
532
|
+
};
|
|
533
|
+
const registerLivingDocumentCommands = (program, context) => {
|
|
534
|
+
const document = program.command("document").description("Read living documents");
|
|
535
|
+
const listAction = async (command) => {
|
|
536
|
+
const result = await context.client(command).recall.listLivingDocuments();
|
|
537
|
+
context.output(command).data(result, renderDocumentList);
|
|
538
|
+
};
|
|
539
|
+
document.command("list").description("List living documents").action(async (_options, command) => listAction(command));
|
|
540
|
+
program.command("list-living-documents", { hidden: true }).description("Legacy living document list").action(async (_options, command) => listAction(command));
|
|
541
|
+
configureGetCommand(document.command("get").description("Read a living document and its shares"), context);
|
|
542
|
+
configureGetCommand(program.command("read-living-document", { hidden: true }).description("Legacy living document read"), context);
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
//#endregion
|
|
546
|
+
//#region src/commands/memory.ts
|
|
547
|
+
const renderSearchHits = (hits) => {
|
|
548
|
+
if (hits.length === 0) return "No memories found.";
|
|
549
|
+
return hits.map((hit) => {
|
|
550
|
+
return `- ${hit.category === null ? "" : `[${hit.category}] `}${hit.memoryDate.slice(0, 10)} — ${hit.content}`;
|
|
551
|
+
}).join("\n");
|
|
552
|
+
};
|
|
553
|
+
const renderProfile = (overview) => {
|
|
554
|
+
const lines = [`# ${overview.account.name}`];
|
|
555
|
+
if (overview.account.primaryRole !== null) lines.push(`Role: ${overview.account.primaryRole}`);
|
|
556
|
+
if (overview.account.workplace !== null) lines.push(`Workplace: ${overview.account.workplace}`);
|
|
557
|
+
if (overview.profile !== null) {
|
|
558
|
+
lines.push(`Scope: ${overview.profile.scope}`);
|
|
559
|
+
for (const fact of overview.profile.facts) lines.push(`- ${fact.content}`);
|
|
560
|
+
}
|
|
561
|
+
return lines.join("\n");
|
|
562
|
+
};
|
|
563
|
+
const renderDateResults = (result) => {
|
|
564
|
+
if (result.memories.length === 0) return "No memories found in the requested date range.";
|
|
565
|
+
return result.memories.map((memory) => `- ${memory.recordedAt.slice(0, 10)} — ${memory.content}`).join("\n");
|
|
566
|
+
};
|
|
567
|
+
const configureAddCommand = (command, context, contract) => {
|
|
568
|
+
command.argument("[text]", "Memory text").option("--memory <text>", "Memory text").option("--file <path>", "Read memory text from a file, or - for stdin").option("--observation-date <datetime>", "ISO 8601 observation time");
|
|
569
|
+
if (contract === "legacy") command.option("--source <source>", "Source identifier").option("--lobe <key>", "Memory lobe").option("--lobe-key <key>", "Legacy alias for --lobe");
|
|
570
|
+
command.action(async (positional, options, actionCommand) => {
|
|
571
|
+
const recallInput = {
|
|
572
|
+
memory: await readTextInput({
|
|
573
|
+
cwd: context.runtime.cwd,
|
|
574
|
+
file: options.file,
|
|
575
|
+
option: options.memory,
|
|
576
|
+
positional,
|
|
577
|
+
stdin: context.runtime.stdin
|
|
578
|
+
}),
|
|
579
|
+
observationDate: parseDateOption(options.observationDate, "--observation-date")
|
|
580
|
+
};
|
|
581
|
+
const client = context.client(actionCommand);
|
|
582
|
+
const result = contract === "recall" ? await client.recall.addMemory(recallInput) : await client.addMemory({
|
|
583
|
+
...recallInput,
|
|
584
|
+
lobeKey: resolveLobeKey(options),
|
|
585
|
+
source: options.source
|
|
586
|
+
});
|
|
587
|
+
context.output(actionCommand).data(result, () => "Memory queued.");
|
|
588
|
+
});
|
|
589
|
+
};
|
|
590
|
+
const configureSearchCommand = (command, context, contract) => {
|
|
591
|
+
command.argument("[query]", "Search query").option("--query <text>", "Search query").option("--limit <number>", "Maximum results");
|
|
592
|
+
if (contract === "legacy") command.option("--lobe <key>", "Restrict to a lobe").option("--lobe-key <key>", "Legacy alias for --lobe").option("--threshold <number>", "Minimum vector similarity").option("--mode <mode>", "fast, adaptive, or reflective", "fast").option("--no-graph", "Disable graph expansion").option("--graph-per-seed <number>", "Maximum neighbors per seed").option("--graph-max <number>", "Maximum graph neighbors");
|
|
593
|
+
command.action(async (positional, options, actionCommand) => {
|
|
594
|
+
const query = options.query ?? positional;
|
|
595
|
+
if (query === void 0 || query.trim().length === 0) throw new MerraiCliUsageError("Provide a search query");
|
|
596
|
+
const mode = options.mode;
|
|
597
|
+
if (contract === "legacy" && mode !== "fast" && mode !== "adaptive" && mode !== "reflective") throw new MerraiCliUsageError("--mode must be one of: fast, adaptive, reflective");
|
|
598
|
+
const limit = parseIntegerOption(options.limit, "--limit", {
|
|
599
|
+
maximum: contract === "recall" ? 25 : 50,
|
|
600
|
+
minimum: 1
|
|
601
|
+
});
|
|
602
|
+
if (contract === "recall") {
|
|
603
|
+
const result = await context.client(actionCommand).recall.searchMemory({
|
|
604
|
+
limit,
|
|
605
|
+
query
|
|
606
|
+
});
|
|
607
|
+
context.output(actionCommand).data(result, (value) => renderSearchHits(value.memories.map((memory) => ({
|
|
608
|
+
...memory,
|
|
609
|
+
memoryDate: memory.recordedAt,
|
|
610
|
+
score: 0,
|
|
611
|
+
summary: null
|
|
612
|
+
}))));
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
const graphPerSeed = parseIntegerOption(options.graphPerSeed, "--graph-per-seed", {
|
|
616
|
+
maximum: 10,
|
|
617
|
+
minimum: 0
|
|
618
|
+
});
|
|
619
|
+
const graphMax = parseIntegerOption(options.graphMax, "--graph-max", {
|
|
620
|
+
maximum: 25,
|
|
621
|
+
minimum: 0
|
|
622
|
+
});
|
|
623
|
+
const input = {
|
|
624
|
+
graph: options.graph === false || graphPerSeed !== void 0 || graphMax !== void 0 ? {
|
|
625
|
+
enabled: options.graph !== false,
|
|
626
|
+
maxNeighborsPerSeed: graphPerSeed,
|
|
627
|
+
maxTotalNeighbors: graphMax
|
|
628
|
+
} : void 0,
|
|
629
|
+
limit,
|
|
630
|
+
lobeKey: resolveLobeKey(options),
|
|
631
|
+
mode: mode === "fast" || mode === "adaptive" || mode === "reflective" ? mode : void 0,
|
|
632
|
+
query,
|
|
633
|
+
threshold: parseNumberOption(options.threshold, "--threshold", {
|
|
634
|
+
maximum: 1,
|
|
635
|
+
minimum: 0
|
|
636
|
+
})
|
|
637
|
+
};
|
|
638
|
+
const result = await context.client(actionCommand).searchMemories(input);
|
|
639
|
+
context.output(actionCommand).data(result, renderSearchHits);
|
|
640
|
+
});
|
|
641
|
+
};
|
|
642
|
+
const configureDateCommand = (command, context) => {
|
|
643
|
+
command.option("--start <datetime>", "Inclusive ISO 8601 lower bound").option("--end <datetime>", "Inclusive ISO 8601 upper bound").option("--limit <number>", "Maximum results").action(async (options, actionCommand) => {
|
|
644
|
+
const start = parseDateOption(options.start, "--start");
|
|
645
|
+
const end = parseDateOption(options.end, "--end");
|
|
646
|
+
if (start === void 0 && end === void 0) throw new MerraiCliUsageError("Provide at least one of --start or --end");
|
|
647
|
+
const input = {
|
|
648
|
+
end,
|
|
649
|
+
limit: parseIntegerOption(options.limit, "--limit", {
|
|
650
|
+
maximum: 50,
|
|
651
|
+
minimum: 1
|
|
652
|
+
}),
|
|
653
|
+
start
|
|
654
|
+
};
|
|
655
|
+
const result = await context.client(actionCommand).memoriesByDate(input);
|
|
656
|
+
context.output(actionCommand).data(result, renderDateResults);
|
|
657
|
+
});
|
|
658
|
+
};
|
|
659
|
+
const configureStatusCommand = (command, context) => {
|
|
660
|
+
command.option("--lobe <key>", "Restrict to a lobe").option("--lobe-key <key>", "Legacy alias for --lobe").action(async (options, actionCommand) => {
|
|
661
|
+
const lobeKey = resolveLobeKey(options);
|
|
662
|
+
const result = await context.client(actionCommand).memoryStatus({ lobeKey });
|
|
663
|
+
context.output(actionCommand).data(result, () => lobeKey === void 0 ? `${result.count} memories.` : `${result.count} memories in ${lobeKey}.`);
|
|
664
|
+
});
|
|
665
|
+
};
|
|
666
|
+
const configureClearCommand = (command, context, requireConfirmation) => {
|
|
667
|
+
command.argument("[lobe]", "Lobe to clear").option("--lobe <key>", "Lobe to clear").option("--lobe-key <key>", "Legacy alias for --lobe").option("--yes", "Skip confirmation").action(async (positional, options, actionCommand) => {
|
|
668
|
+
const lobeKey = resolveLobeKey(options) ?? positional;
|
|
669
|
+
if (lobeKey === void 0 || lobeKey.trim().length === 0) throw new MerraiCliUsageError("Provide the lobe to clear");
|
|
670
|
+
if (requireConfirmation && options.yes !== true) {
|
|
671
|
+
if (!await confirmAction({
|
|
672
|
+
input: context.runtime.stdin,
|
|
673
|
+
message: `Clear all memories in lobe '${lobeKey}'?`,
|
|
674
|
+
output: context.runtime.stderr
|
|
675
|
+
})) throw new MerraiCliUsageError("Clear cancelled. Use --yes for noninteractive confirmation.");
|
|
676
|
+
}
|
|
677
|
+
const result = await context.client(actionCommand).clearLobe({ lobeKey });
|
|
678
|
+
context.output(actionCommand).data(result, () => `Cleared lobe ${lobeKey}.`);
|
|
679
|
+
});
|
|
680
|
+
};
|
|
681
|
+
const registerMemoryCommands = (program, context) => {
|
|
682
|
+
const memory = program.command("memory").description("Manage and recall memories");
|
|
683
|
+
configureAddCommand(memory.command("add").description("Queue a memory"), context, "recall");
|
|
684
|
+
configureAddCommand(program.command("add-memory", { hidden: true }).description("Legacy memory add"), context, "legacy");
|
|
685
|
+
configureSearchCommand(memory.command("search").description("Search memories"), context, "recall");
|
|
686
|
+
configureSearchCommand(program.command("search", { hidden: true }).description("Legacy memory search"), context, "legacy");
|
|
687
|
+
const listAction = async (command) => {
|
|
688
|
+
const result = await context.client(command).memories();
|
|
689
|
+
context.output(command).data(result);
|
|
690
|
+
};
|
|
691
|
+
memory.command("list").description("List memories").action(async (_options, command) => listAction(command));
|
|
692
|
+
program.command("memories", { hidden: true }).description("Legacy memory list").action(async (_options, command) => listAction(command));
|
|
693
|
+
const profileAction = async (command) => {
|
|
694
|
+
const result = await context.client(command).memoryOverview();
|
|
695
|
+
context.output(command).data(result, renderProfile);
|
|
696
|
+
};
|
|
697
|
+
memory.command("profile").description("Show the account and memory profile").action(async (_options, command) => profileAction(command));
|
|
698
|
+
program.command("who-am-i", { hidden: true }).aliases(["whoami"]).description("Legacy memory profile").action(async (_options, command) => profileAction(command));
|
|
699
|
+
configureDateCommand(memory.command("by-date").description("Recall memories by date"), context);
|
|
700
|
+
configureDateCommand(program.command("search-memories-by-date", { hidden: true }).description("Legacy date recall"), context);
|
|
701
|
+
configureStatusCommand(memory.command("status").description("Count processed memories"), context);
|
|
702
|
+
configureStatusCommand(program.command("memory-status", { hidden: true }).description("Legacy status"), context);
|
|
703
|
+
configureClearCommand(memory.command("clear").description("Clear a memory lobe"), context, true);
|
|
704
|
+
configureClearCommand(program.command("clear-lobe", { hidden: true }).description("Legacy lobe clear"), context, false);
|
|
705
|
+
};
|
|
706
|
+
|
|
707
|
+
//#endregion
|
|
708
|
+
//#region src/commands/system.ts
|
|
709
|
+
const renderLabelledJson = (label) => (value) => `${label}\n${JSON.stringify(value, null, 2)}`;
|
|
710
|
+
const redactAuthSessionToken = (result) => ({
|
|
711
|
+
session: {
|
|
712
|
+
createdAt: result.session.createdAt,
|
|
713
|
+
expiresAt: result.session.expiresAt,
|
|
714
|
+
id: result.session.id,
|
|
715
|
+
ipAddress: result.session.ipAddress,
|
|
716
|
+
updatedAt: result.session.updatedAt,
|
|
717
|
+
userAgent: result.session.userAgent,
|
|
718
|
+
userId: result.session.userId
|
|
719
|
+
},
|
|
720
|
+
user: result.user
|
|
721
|
+
});
|
|
722
|
+
const registerSystemCommands = (program, context) => {
|
|
723
|
+
program.command("health").description("Check API connectivity").action(async (_options, command) => {
|
|
724
|
+
const result = await context.client(command).healthCheck();
|
|
725
|
+
context.output(command).data(result, renderLabelledJson("Merrai is reachable."));
|
|
726
|
+
});
|
|
727
|
+
program.command("session").description("Fetch the current session").action(async (_options, command) => {
|
|
728
|
+
const result = await context.client(command).session();
|
|
729
|
+
const safeResult = result === null ? null : redactAuthSessionToken(result);
|
|
730
|
+
context.output(command).data(safeResult, renderLabelledJson("Current session:"));
|
|
731
|
+
});
|
|
732
|
+
const account = program.command("account").description("Account information");
|
|
733
|
+
const usageAction = async (command) => {
|
|
734
|
+
const result = await context.client(command).usageSummary();
|
|
735
|
+
context.output(command).data(result, renderLabelledJson("Usage:"));
|
|
736
|
+
};
|
|
737
|
+
account.command("usage").description("Fetch the current usage summary").action(async (_options, command) => usageAction(command));
|
|
738
|
+
program.command("usage-summary", { hidden: true }).description("Legacy alias for account usage").action(async (_options, command) => usageAction(command));
|
|
739
|
+
};
|
|
740
|
+
|
|
741
|
+
//#endregion
|
|
742
|
+
//#region src/output.ts
|
|
743
|
+
const ensureTrailingNewline = (value) => value.endsWith("\n") ? value : `${value}\n`;
|
|
744
|
+
const createMerraiCliOutput = (options) => ({
|
|
745
|
+
data: (value, renderText) => {
|
|
746
|
+
const rendered = options.format === "text" && renderText !== void 0 ? renderText(value) : typeof value === "string" && options.format === "text" ? value : JSON.stringify(value, null, 2);
|
|
747
|
+
options.stdout.write(ensureTrailingNewline(rendered ?? "null"));
|
|
748
|
+
},
|
|
749
|
+
diagnostic: (message) => {
|
|
750
|
+
options.stderr.write(ensureTrailingNewline(message));
|
|
751
|
+
},
|
|
752
|
+
error: (message) => {
|
|
753
|
+
options.stderr.write(ensureTrailingNewline(message));
|
|
754
|
+
}
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
//#endregion
|
|
758
|
+
//#region src/runtime.ts
|
|
759
|
+
const globalOptions = (command) => command.optsWithGlobals();
|
|
760
|
+
const createMerraiCommandContext = (runtime) => ({
|
|
761
|
+
client: (command) => {
|
|
762
|
+
const options = globalOptions(command);
|
|
763
|
+
return runtime.createClient(resolveMerraiClientOptions(runtime.env, {
|
|
764
|
+
apiKey: options.apiKey,
|
|
765
|
+
baseURL: options.baseUrl,
|
|
766
|
+
cookie: options.cookie
|
|
767
|
+
}));
|
|
768
|
+
},
|
|
769
|
+
output: (command) => {
|
|
770
|
+
const options = globalOptions(command);
|
|
771
|
+
return createMerraiCliOutput({
|
|
772
|
+
format: options.json === true ? "json" : options.format ?? "json",
|
|
773
|
+
stderr: runtime.stderr,
|
|
774
|
+
stdout: runtime.stdout
|
|
775
|
+
});
|
|
776
|
+
},
|
|
777
|
+
runtime
|
|
778
|
+
});
|
|
779
|
+
|
|
780
|
+
//#endregion
|
|
781
|
+
//#region src/program.ts
|
|
782
|
+
const CLI_VERSION = version;
|
|
783
|
+
const parseFormat = (value) => {
|
|
784
|
+
if (value !== "json" && value !== "text") throw new InvalidArgumentError("format must be json or text");
|
|
785
|
+
return value;
|
|
786
|
+
};
|
|
787
|
+
const createMerraiProgram = (runtime) => {
|
|
788
|
+
const program = new Command();
|
|
789
|
+
const context = createMerraiCommandContext(runtime);
|
|
790
|
+
program.name("merrai").description("Store, recall, and ingest Merrai memories").version(CLI_VERSION).option("--base-url <url>", "Merrai server base URL").option("--api-key <key>", "Merrai API key").option("--cookie <cookie>", "Session cookie fallback").option("--format <format>", "Output format: json or text", parseFormat).option("--json", "Alias for --format json").showHelpAfterError().exitOverride().configureOutput({
|
|
791
|
+
writeErr: (value) => runtime.stderr.write(value),
|
|
792
|
+
writeOut: (value) => runtime.stdout.write(value)
|
|
793
|
+
});
|
|
794
|
+
registerSystemCommands(program, context);
|
|
795
|
+
registerMemoryCommands(program, context);
|
|
796
|
+
registerEntityCommands(program, context);
|
|
797
|
+
registerLivingDocumentCommands(program, context);
|
|
798
|
+
registerIngestCommands(program, context);
|
|
799
|
+
registerDebugCommands(program, context);
|
|
800
|
+
registerAuthCommands(program, context);
|
|
801
|
+
return program;
|
|
802
|
+
};
|
|
803
|
+
const runMerraiCli = async (runtime) => {
|
|
804
|
+
const program = createMerraiProgram(runtime);
|
|
805
|
+
if (runtime.argv.length === 0) {
|
|
806
|
+
program.outputHelp();
|
|
807
|
+
return MERRAI_CLI_EXIT_CODES.success;
|
|
808
|
+
}
|
|
809
|
+
try {
|
|
810
|
+
await program.parseAsync([...runtime.argv], { from: "user" });
|
|
811
|
+
return MERRAI_CLI_EXIT_CODES.success;
|
|
812
|
+
} catch (error) {
|
|
813
|
+
const result = classifyMerraiCliError(error);
|
|
814
|
+
if (result.shouldRender) runtime.stderr.write(result.message.endsWith("\n") ? result.message : `${result.message}\n`);
|
|
815
|
+
return result.exitCode;
|
|
816
|
+
}
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
//#endregion
|
|
820
|
+
//#region src/bin.ts
|
|
821
|
+
const exitCode = await runMerraiCli({
|
|
822
|
+
argv: process.argv.slice(2),
|
|
823
|
+
createClient: createMerraiThrowingClient,
|
|
824
|
+
cwd: process.cwd(),
|
|
825
|
+
env: process.env,
|
|
826
|
+
stderr: process.stderr,
|
|
827
|
+
stdin: process.stdin,
|
|
828
|
+
stdout: process.stdout
|
|
829
|
+
});
|
|
830
|
+
process.exitCode = exitCode;
|
|
831
|
+
|
|
832
|
+
//#endregion
|
|
833
|
+
export { };
|
|
834
|
+
//# sourceMappingURL=bin.mjs.map
|