@sol-merrai/cli 0.1.4 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs ADDED
@@ -0,0 +1,1910 @@
1
+ #!/usr/bin/env node
2
+ import { createORPCClient } from "@orpc/client";
3
+ import { RPCLink } from "@orpc/client/fetch";
4
+ import { Command, CommanderError, InvalidArgumentError } from "commander";
5
+ import * as NodeCrypto from "node:crypto";
6
+ import * as NodePath from "node:path";
7
+ import * as NodeFSP from "node:fs/promises";
8
+ import { z } from "zod";
9
+ import * as NodeReadlinePromises from "node:readline/promises";
10
+ import * as NodeFS from "node:fs";
11
+ import * as NodeOS from "node:os";
12
+ // src/client.ts
13
+ const resolveBaseURL = (baseURL) => {
14
+ const resolved = baseURL?.trim();
15
+ if (resolved === void 0 || resolved === "") throw new Error("baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials");
16
+ return resolved.endsWith("/") ? resolved.slice(0, -1) : resolved;
17
+ };
18
+ const resolveHeaders = (headers, apiKey, cookie) => {
19
+ const resolvedHeaders = new Headers(headers);
20
+ resolvedHeaders.set("x-merrai-unknown-fields", "strip");
21
+ if (apiKey !== void 0 && apiKey !== "") resolvedHeaders.set("x-api-key", apiKey);
22
+ if (cookie !== void 0 && cookie !== "") resolvedHeaders.set("Cookie", cookie);
23
+ return Object.fromEntries(resolvedHeaders.entries());
24
+ };
25
+ const createMerraiRpcLink = (options) => new RPCLink({
26
+ fetch: options.fetch,
27
+ headers: () => resolveHeaders(options.headers, options.apiKey, options.cookie),
28
+ url: `${resolveBaseURL(options.baseURL)}/rpc`
29
+ });
30
+ const createRawMerraiClient = (options = {}) => createORPCClient(createMerraiRpcLink(options));
31
+ /** Debug names address the remote router independently of the published client mirror. */
32
+ const createMerraiDebugProcedure = (options, procedureName) => createORPCClient(createMerraiRpcLink(options), { path: [procedureName] });
33
+ const createMerraiThrowingClient = (options = {}) => createRawMerraiClient(options);
34
+ // package.json
35
+ var version = "0.10.0";
36
+ // src/errors.ts
37
+ const MERRAI_CLI_EXIT_CODES = {
38
+ /** An App Artifact handler ran and failed: its own error, not Merrai's. */
39
+ appFailed: 6,
40
+ auth: 3,
41
+ network: 10,
42
+ notFound: 4,
43
+ rateLimit: 5,
44
+ success: 0,
45
+ usage: 2
46
+ };
47
+ /**
48
+ * An App Artifact call that answered with a failure. Handler failures are
49
+ * values on the wire; the CLI still exits non-zero so scripts notice.
50
+ */
51
+ var MerraiCliAppArtifactCallError = class extends Error {
52
+ fault;
53
+ constructor(message, fault) {
54
+ super(message);
55
+ this.fault = fault;
56
+ this.name = "MerraiCliAppArtifactCallError";
57
+ }
58
+ };
59
+ var MerraiCliUsageError = class extends Error {
60
+ constructor(message, options) {
61
+ super(message, options);
62
+ this.name = "MerraiCliUsageError";
63
+ }
64
+ };
65
+ /** Nothing of the caller's matched; exits as the server's not found does. */
66
+ var MerraiCliNotFoundError = class extends Error {
67
+ constructor(message) {
68
+ super(message);
69
+ this.name = "MerraiCliNotFoundError";
70
+ }
71
+ };
72
+ const orpcErrorSchema = z.object({
73
+ code: z.string(),
74
+ data: z.unknown().optional(),
75
+ message: z.string(),
76
+ status: z.number()
77
+ });
78
+ const INVALID_API_KEY_CLI_MESSAGE = "Invalid or revoked API key. Create a new key in Merrai settings, then save it with `merrai auth set-key` or set MERRAI_API_KEY.";
79
+ const invalidApiKeyErrorSchema = z.object({
80
+ code: z.literal("UNAUTHORIZED"),
81
+ data: z.object({ reason: z.literal("INVALID_API_KEY") })
82
+ });
83
+ /**
84
+ * True when the server refused the request's API key as unknown, malformed,
85
+ * revoked or expired. That key will not work again.
86
+ */
87
+ const isInvalidApiKeyError = (error) => invalidApiKeyErrorSchema.safeParse(error).success;
88
+ /** True when Merrai answered that nothing of the caller's has that id. */
89
+ const isMerraiNotFoundError = (error) => orpcErrorSchema.safeParse(error).data?.code === "NOT_FOUND";
90
+ const refusalReasonSchema = z.object({
91
+ code: z.literal("NOT_FOUND"),
92
+ data: z.object({ reason: z.string() })
93
+ });
94
+ /** The server's `data.reason` on a NOT_FOUND refusal, such as `archived`. */
95
+ const merraiNotFoundReason = (error) => refusalReasonSchema.safeParse(error).data?.data.reason;
96
+ const renderJsonError = (message, metadata = {}) => JSON.stringify({ error: {
97
+ ...metadata,
98
+ message
99
+ } }, null, 2);
100
+ const renderOrpcError = (error) => {
101
+ const metadata = {
102
+ code: error.code,
103
+ status: error.status
104
+ };
105
+ const data = z.json().safeParse(error.data);
106
+ if (data.success) metadata.data = data.data;
107
+ return renderJsonError(error.message, metadata);
108
+ };
109
+ const classifyMerraiCliError = (error) => {
110
+ if (error instanceof CommanderError) return {
111
+ exitCode: error.code === "commander.helpDisplayed" || error.code === "commander.version" ? MERRAI_CLI_EXIT_CODES.success : MERRAI_CLI_EXIT_CODES.usage,
112
+ message: error.message,
113
+ shouldRender: false
114
+ };
115
+ if (error instanceof MerraiCliAppArtifactCallError) return {
116
+ exitCode: error.fault === "refused" ? MERRAI_CLI_EXIT_CODES.auth : MERRAI_CLI_EXIT_CODES.appFailed,
117
+ message: renderJsonError(error.message, { code: error.fault === "refused" ? "CALL_REFUSED" : "CALL_FAILED" }),
118
+ shouldRender: true
119
+ };
120
+ if (error instanceof MerraiCliUsageError) return {
121
+ exitCode: MERRAI_CLI_EXIT_CODES.usage,
122
+ message: renderJsonError(error.message, { code: "USAGE_ERROR" }),
123
+ shouldRender: true
124
+ };
125
+ if (error instanceof MerraiCliNotFoundError) return {
126
+ exitCode: MERRAI_CLI_EXIT_CODES.notFound,
127
+ message: renderJsonError(error.message, { code: "NOT_FOUND" }),
128
+ shouldRender: true
129
+ };
130
+ const orpcError = orpcErrorSchema.safeParse(error);
131
+ if (orpcError.success) {
132
+ const code = orpcError.data.code;
133
+ if (code === "BAD_REQUEST" || code === "UNPROCESSABLE_CONTENT") return {
134
+ exitCode: MERRAI_CLI_EXIT_CODES.usage,
135
+ message: renderOrpcError(orpcError.data),
136
+ shouldRender: true
137
+ };
138
+ if (code === "UNAUTHORIZED" || code === "FORBIDDEN") return {
139
+ exitCode: MERRAI_CLI_EXIT_CODES.auth,
140
+ message: renderOrpcError(isInvalidApiKeyError(orpcError.data) ? {
141
+ ...orpcError.data,
142
+ message: INVALID_API_KEY_CLI_MESSAGE
143
+ } : orpcError.data),
144
+ shouldRender: true
145
+ };
146
+ if (code === "NOT_FOUND" || code === "CONFLICT") return {
147
+ exitCode: MERRAI_CLI_EXIT_CODES.notFound,
148
+ message: renderOrpcError(orpcError.data),
149
+ shouldRender: true
150
+ };
151
+ if (code === "RATE_LIMITED" || code === "TOO_MANY_REQUESTS" || code === "PAYLOAD_TOO_LARGE" || code === "RESOURCE_EXHAUSTED" || orpcError.data.status === 429) return {
152
+ exitCode: MERRAI_CLI_EXIT_CODES.rateLimit,
153
+ message: renderOrpcError(orpcError.data),
154
+ shouldRender: true
155
+ };
156
+ return {
157
+ exitCode: MERRAI_CLI_EXIT_CODES.network,
158
+ message: renderOrpcError(orpcError.data),
159
+ shouldRender: true
160
+ };
161
+ }
162
+ const nativeError = z.instanceof(Error).safeParse(error);
163
+ const stringError = z.string().safeParse(error);
164
+ return {
165
+ exitCode: MERRAI_CLI_EXIT_CODES.network,
166
+ message: renderJsonError(nativeError.success ? nativeError.data.message : stringError.success ? stringError.data : "Unexpected CLI failure", { code: "NETWORK_ERROR" }),
167
+ shouldRender: true
168
+ };
169
+ };
170
+ // src/app-source-files.ts
171
+ const MANIFEST = "app-artifact.json";
172
+ /** The Working source revision this folder was last pulled or pushed at; never uploaded. */
173
+ const REVISION_FILE = NodePath.join(".merrai", "revision");
174
+ /** Never source: version control, installed packages and Merrai's own build output. */
175
+ const SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([
176
+ ".git",
177
+ "node_modules",
178
+ ".merrai"
179
+ ]);
180
+ /** The server's own limits, checked here so a mistake fails before upload. */
181
+ const MAX_FILES = 64;
182
+ const MAX_FILE_BYTES = 262144;
183
+ const isSkipped = (name) => name.startsWith(".") || SKIPPED_DIRECTORIES.has(name);
184
+ const listFiles = async (root, directory) => {
185
+ const entries = await NodeFSP.readdir(NodePath.join(root, directory), { withFileTypes: true });
186
+ return (await Promise.all(entries.filter((entry) => !isSkipped(entry.name)).map(async (entry) => {
187
+ const relative = NodePath.posix.join(directory, entry.name);
188
+ if (entry.isDirectory()) return await listFiles(root, relative);
189
+ return entry.isFile() ? [relative] : [];
190
+ }))).flat();
191
+ };
192
+ const readText = async (root, file) => {
193
+ const bytes = await NodeFSP.readFile(NodePath.join(root, file));
194
+ if (bytes.byteLength > MAX_FILE_BYTES) throw new MerraiCliUsageError(`${file} is larger than ${MAX_FILE_BYTES / 1024} KB, the most one source file may be`);
195
+ if (bytes.includes(0)) throw new MerraiCliUsageError(`${file} is not a text file. App Artifact source is text only.`);
196
+ return bytes.toString("utf8");
197
+ };
198
+ /** Every source file under `directory`, keyed by its slash-separated relative path. */
199
+ const readAppSourceFolder = async (directory) => {
200
+ let files;
201
+ try {
202
+ files = (await listFiles(directory, "")).toSorted();
203
+ } catch (error) {
204
+ throw new MerraiCliUsageError(`Unable to read ${directory}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
205
+ }
206
+ if (!files.includes(MANIFEST)) throw new MerraiCliUsageError(`${directory} has no ${MANIFEST}. An App Artifact folder needs one at its root.`);
207
+ if (files.length > MAX_FILES) throw new MerraiCliUsageError(`${directory} has ${files.length} files; an App Artifact may have at most ${MAX_FILES}.`);
208
+ const contents = await Promise.all(files.map(async (file) => [file, await readText(directory, file)]));
209
+ return Object.fromEntries(contents);
210
+ };
211
+ /**
212
+ * Refuses a path whose existing parts include a symlink: the lexical check
213
+ * alone would let `--force` follow one and overwrite files elsewhere.
214
+ */
215
+ const assertNoSymlink = async (root, target) => {
216
+ const parts = NodePath.relative(root, target).split(NodePath.sep);
217
+ const prefixes = parts.map((_, index) => NodePath.join(root, ...parts.slice(0, index + 1)));
218
+ const stats = await Promise.all(prefixes.map((prefix) => NodeFSP.lstat(prefix).catch(() => null)));
219
+ const link = prefixes.find((_, index) => stats[index]?.isSymbolicLink() === true);
220
+ if (link !== void 0) throw new MerraiCliUsageError(`Refusing to write through the symlink ${link}`);
221
+ };
222
+ /**
223
+ * Writes the Working source into `directory`. Without `force` it refuses a
224
+ * folder that already has files, so a pull never overwrites local edits.
225
+ */
226
+ const writeAppSourceFolder = async (directory, files, options) => {
227
+ if ((await NodeFSP.readdir(directory).catch(() => [])).length > 0 && !options.force) throw new MerraiCliUsageError(`${directory} is not empty. Pull into an empty folder, or pass --force to overwrite.`);
228
+ const root = NodePath.resolve(directory);
229
+ await Promise.all(Object.entries(files).map(async ([file, content]) => {
230
+ const target = NodePath.resolve(root, file);
231
+ if (!target.startsWith(root + NodePath.sep)) throw new MerraiCliUsageError(`Refusing to write ${file} outside ${directory}`);
232
+ await assertNoSymlink(root, target);
233
+ await NodeFSP.mkdir(NodePath.dirname(target), { recursive: true });
234
+ await NodeFSP.writeFile(target, content, "utf8");
235
+ }));
236
+ };
237
+ /** The revision recorded in `directory`, or undefined when it has none. */
238
+ const readAppSourceRevision = async (directory) => {
239
+ try {
240
+ const revision = (await NodeFSP.readFile(NodePath.join(directory, REVISION_FILE), "utf8")).trim();
241
+ return revision.length === 0 ? void 0 : revision;
242
+ } catch (error) {
243
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
244
+ throw error;
245
+ }
246
+ };
247
+ /**
248
+ * Records the revision the folder matches, so the next push is refused if
249
+ * someone else changed the app meanwhile.
250
+ */
251
+ const writeAppSourceRevision = async (directory, revision) => {
252
+ const target = NodePath.resolve(directory, REVISION_FILE);
253
+ await assertNoSymlink(NodePath.resolve(directory), target);
254
+ await NodeFSP.mkdir(NodePath.dirname(target), { recursive: true });
255
+ await NodeFSP.writeFile(target, `${revision}\n`, "utf8");
256
+ };
257
+ // src/input.ts
258
+ const structuredInputSchema = z.json();
259
+ const readStream = async (stream) => {
260
+ const chunks = [];
261
+ for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
262
+ return Buffer.concat(chunks).toString("utf8");
263
+ };
264
+ const readFileOrStdin = async (options) => {
265
+ if (options.file === "-") return readStream(options.stdin);
266
+ const resolvedPath = NodePath.resolve(options.cwd, options.file);
267
+ try {
268
+ return await NodeFSP.readFile(resolvedPath, "utf8");
269
+ } catch (error) {
270
+ throw new MerraiCliUsageError(`Unable to read ${resolvedPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
271
+ }
272
+ };
273
+ const readStructuredInput = async (options) => {
274
+ if (options.file !== void 0 && options.input !== void 0) throw new MerraiCliUsageError("Use only one of --input or --file");
275
+ if (options.file === void 0 && options.input === void 0) throw new MerraiCliUsageError("Provide --input <json> or --file <path|->");
276
+ const source = options.input !== void 0 ? options.input : await readFileOrStdin({
277
+ cwd: options.cwd,
278
+ file: options.file ?? "-",
279
+ stdin: options.stdin
280
+ });
281
+ try {
282
+ return structuredInputSchema.parse(JSON.parse(source));
283
+ } catch (error) {
284
+ throw new MerraiCliUsageError(`Invalid JSON from ${options.file === void 0 ? "--input" : options.file}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
285
+ }
286
+ };
287
+ const readTextInput = async (options) => {
288
+ const directValues = [options.positional, options.option].filter((value) => value !== void 0);
289
+ 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");
290
+ const value = directValues[0] ?? (options.file === void 0 ? void 0 : await readFileOrStdin({
291
+ cwd: options.cwd,
292
+ file: options.file,
293
+ stdin: options.stdin
294
+ }));
295
+ if (value === void 0 || value.trim().length === 0) throw new MerraiCliUsageError("Memory text cannot be empty");
296
+ return value;
297
+ };
298
+ const confirmAction = async (options) => {
299
+ if (!("isTTY" in options.input && options.input.isTTY === true)) return false;
300
+ const prompt = NodeReadlinePromises.createInterface({
301
+ input: options.input,
302
+ output: options.output
303
+ });
304
+ try {
305
+ const answer = await prompt.question(`${options.message} [y/N] `);
306
+ return answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes";
307
+ } finally {
308
+ prompt.close();
309
+ }
310
+ };
311
+ /** One typed line from a terminal; undefined when nobody can type one. */
312
+ const readTypedConfirmation = async (options) => {
313
+ if (!("isTTY" in options.input && options.input.isTTY === true)) return void 0;
314
+ const prompt = NodeReadlinePromises.createInterface({
315
+ input: options.input,
316
+ output: options.output
317
+ });
318
+ try {
319
+ return await prompt.question(`${options.message} `);
320
+ } finally {
321
+ prompt.close();
322
+ }
323
+ };
324
+ const readSecretInput = async (options) => {
325
+ const input = options.input;
326
+ 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");
327
+ options.output.write(options.message);
328
+ const wasRaw = input.isRaw === true;
329
+ input.setRawMode(true);
330
+ return new Promise((resolve, reject) => {
331
+ let value = "";
332
+ const cleanup = () => {
333
+ input.off("data", onData);
334
+ input.off("end", onEnd);
335
+ input.off("error", onError);
336
+ input.setRawMode?.(wasRaw);
337
+ input.pause();
338
+ };
339
+ const rejectInput = (error) => {
340
+ cleanup();
341
+ reject(error);
342
+ };
343
+ const onEnd = () => {
344
+ rejectInput(new MerraiCliUsageError("API key entry ended unexpectedly"));
345
+ };
346
+ const onError = (error) => {
347
+ rejectInput(new MerraiCliUsageError(`Unable to read API key: ${error.message}`, { cause: error }));
348
+ };
349
+ const onData = (chunk) => {
350
+ const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk;
351
+ for (const character of text) {
352
+ if (character === "\r" || character === "\n") {
353
+ options.output.write("\n");
354
+ cleanup();
355
+ resolve(value);
356
+ return;
357
+ }
358
+ if (character === "" || character === "") {
359
+ options.output.write("\n");
360
+ rejectInput(new MerraiCliUsageError("API key entry cancelled"));
361
+ return;
362
+ }
363
+ if (character === "" || character === "\b") {
364
+ if (value.length > 0) {
365
+ value = value.slice(0, -1);
366
+ options.output.write("\b \b");
367
+ }
368
+ continue;
369
+ }
370
+ value += character;
371
+ options.output.write("*");
372
+ }
373
+ };
374
+ input.on("data", onData);
375
+ input.once("end", onEnd);
376
+ input.once("error", onError);
377
+ input.resume();
378
+ });
379
+ };
380
+ // src/commands/shared.ts
381
+ const ISO_8601_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
382
+ /**
383
+ * Text output for queued work: names the ingestion and how to follow it,
384
+ * since the save is not processed or searchable yet.
385
+ */
386
+ const describeQueuedIngestion = (what, ingestionId) => `${what} queued as ingestion ${ingestionId}. Follow it with \`merrai ingestion status ${ingestionId}\`.`;
387
+ const resolveLobeKey = (options) => options.lobe ?? options.lobeKey;
388
+ const parseIntegerOption = (value, name, range) => {
389
+ if (value === void 0) return;
390
+ const parsed = Number(value);
391
+ if (!Number.isInteger(parsed) || parsed < range.minimum || parsed > range.maximum) throw new MerraiCliUsageError(`${name} must be an integer from ${range.minimum} to ${range.maximum}`);
392
+ return parsed;
393
+ };
394
+ const parseDateOption = (value, name) => {
395
+ if (value === void 0) return;
396
+ if (!ISO_8601_DATETIME_PATTERN.test(value) || Number.isNaN(new Date(value).getTime())) throw new MerraiCliUsageError(`${name} must be a valid ISO 8601 datetime`);
397
+ return value;
398
+ };
399
+ const parseEntityType = (value) => {
400
+ if (value === void 0) return;
401
+ switch (value) {
402
+ case "action":
403
+ case "document":
404
+ case "event":
405
+ case "knowledge":
406
+ case "person": return value;
407
+ default: throw new MerraiCliUsageError("--type must be one of: person, event, action, knowledge, document");
408
+ }
409
+ };
410
+ /** Commander's collector for an option given more than once. */
411
+ const collectOption = (value, previous) => [...previous, value];
412
+ /** A calendar day (YYYY-MM-DD) that exists. */
413
+ const parseDayOption = (value, name) => {
414
+ if (value === void 0) return void 0;
415
+ const parsed = /* @__PURE__ */ new Date(`${value}T00:00:00.000Z`);
416
+ if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value) throw new MerraiCliUsageError(`${name} must be a day as YYYY-MM-DD`);
417
+ return value;
418
+ };
419
+ /** The day it is where the CLI runs (YYYY-MM-DD). */
420
+ const localDay = (now) => [
421
+ String(now.getFullYear()).padStart(4, "0"),
422
+ String(now.getMonth() + 1).padStart(2, "0"),
423
+ String(now.getDate()).padStart(2, "0")
424
+ ].join("-");
425
+ /** Parses a `nextCursor` JSON a previous page printed. */
426
+ const parseCursorJson$1 = (schema, value, example) => {
427
+ if (value === void 0) return void 0;
428
+ let json;
429
+ try {
430
+ json = JSON.parse(value);
431
+ } catch {
432
+ json = void 0;
433
+ }
434
+ const parsed = schema.safeParse(json);
435
+ if (!parsed.success) throw new MerraiCliUsageError(`cursor must be the nextCursor JSON from a previous page, for example ${example}`);
436
+ return parsed.data;
437
+ };
438
+ /** The line that tells a reader how to fetch the next page, if any. */
439
+ const renderMoreCursor = (cursor) => cursor === null ? [] : [`More: --cursor '${JSON.stringify(cursor)}'`];
440
+ // src/commands/apps.ts
441
+ const GUIDE_TOPICS = ["authoring", "design"];
442
+ const parseGuideTopic = (topic) => {
443
+ const match = GUIDE_TOPICS.find((candidate) => candidate === topic);
444
+ if (match === void 0) throw new MerraiCliUsageError(`Unknown guide topic ${topic}. Use one of: ${GUIDE_TOPICS.join(", ")}`);
445
+ return match;
446
+ };
447
+ const CALL_KINDS = [
448
+ "query",
449
+ "mutation",
450
+ "action"
451
+ ];
452
+ const parseCallKind = (kind) => {
453
+ const match = CALL_KINDS.find((candidate) => candidate === kind);
454
+ if (match === void 0) throw new MerraiCliUsageError(`Unknown handler kind ${kind}. Use one of: ${CALL_KINDS.join(", ")}`);
455
+ return match;
456
+ };
457
+ const requireMessage = (message) => {
458
+ const trimmed = message?.trim() ?? "";
459
+ if (trimmed.length === 0) throw new MerraiCliUsageError("Describe the change with -m <message>; it is kept with the Version.");
460
+ return trimmed;
461
+ };
462
+ const describeVersion = (artifact) => artifact.currentVersion === null ? "no Version yet" : `Version ${artifact.currentVersion.number}`;
463
+ const renderList = (artifacts) => artifacts.length === 0 ? "No apps." : artifacts.map((artifact) => `- ${artifact.name}: ${describeVersion(artifact)}${artifact.pendingTools.length > 0 ? ", needs permission" : ""} (${artifact.id})`).join("\n");
464
+ const SHARE_LEVELS = {
465
+ use: "Can view",
466
+ ask: "Asks before changes",
467
+ act: "Can make changes"
468
+ };
469
+ const renderShared = (artifacts) => artifacts.length === 0 ? "Nothing is shared with you." : artifacts.map((artifact) => `- ${artifact.name}, shared by ${artifact.owner.name} (${SHARE_LEVELS[artifact.level]}) (${artifact.id})`).join("\n");
470
+ const renderRequests = (requests) => requests.length === 0 ? "No requests." : requests.map((request) => `- ${request.action} (${request.tool}): ${request.status}${request.error === null ? "" : `, ${request.error}`} (${request.id})`).join("\n");
471
+ const handlerLines = (api) => {
472
+ if (api === void 0) return [];
473
+ const callable = (kind, handlers) => handlers.filter((handler) => !handler.internal).map((handler) => ` ${kind} ${handler.name}: ${handler.description}`);
474
+ const lines = [
475
+ ...callable("query", api.queries),
476
+ ...callable("mutation", api.mutations),
477
+ ...callable("action", api.actions)
478
+ ];
479
+ return lines.length === 0 ? [] : ["Handlers:", ...lines];
480
+ };
481
+ const renderArtifact = (artifact) => {
482
+ const description = artifact.currentVersion?.manifest.description ?? "";
483
+ return [
484
+ artifact.name,
485
+ `ID: ${artifact.id}`,
486
+ `Status: ${artifact.status}, ${describeVersion(artifact)}`,
487
+ ...description === "" ? [] : [description],
488
+ `Sync: ${artifact.sync.state}${artifact.sync.lastError === null ? "" : ` (${artifact.sync.lastError})`}`,
489
+ ...artifact.pendingTools.length > 0 ? [`Needs permission for: ${artifact.pendingTools.join(", ")} (allow them in Merrai)`] : [],
490
+ ...handlerLines(artifact.currentVersion?.api),
491
+ ...artifact.recentErrors.length > 0 ? ["Recent errors:", ...artifact.recentErrors.map((error) => `- ${error.at} ${error.source}: ${error.message}`)] : []
492
+ ].join("\n");
493
+ };
494
+ const renderSharedArtifact = (artifact) => [
495
+ artifact.name,
496
+ `ID: ${artifact.id}`,
497
+ `Shared by ${artifact.owner.name}: ${SHARE_LEVELS[artifact.level]}`,
498
+ ...artifact.description === "" ? [] : [artifact.description],
499
+ ...handlerLines(artifact.api ?? void 0)
500
+ ].join("\n");
501
+ const renderDeleted = (name) => (deleted) => deleted.dataRemoved ? `Deleted ${name} (${deleted.appArtifactId}).` : `Deleted ${name} (${deleted.appArtifactId}). Its stored data is still being removed.`;
502
+ const renderAlreadyDeleted = (deleted) => deleted.dataRemoved ? `${deleted.appArtifactId} was already deleted. Its stored data is now removed.` : `${deleted.appArtifactId} was already deleted. Its stored data is still being removed.`;
503
+ /**
504
+ * Repeats a delete whose app is already gone: the server only retries
505
+ * removing the owner's own pending data, so there is no name to confirm.
506
+ */
507
+ const finishDeleted = async (client, appArtifactId) => {
508
+ try {
509
+ return await client.appArtifacts.delete({ appArtifactId });
510
+ } catch (error) {
511
+ if (!isMerraiNotFoundError(error)) throw error;
512
+ throw new MerraiCliNotFoundError(`Nothing to delete: ${appArtifactId} is not one of your apps. An app already deleted for good reads the same.`);
513
+ }
514
+ };
515
+ /**
516
+ * Not yours: it may be shared with you. Null for a plain refusal, which reads
517
+ * as the owner lookup's; one with a reason (archived) is the grantee's to see.
518
+ */
519
+ const sharedOrPlainRefusal = async (client, appArtifactId) => {
520
+ try {
521
+ return await client.appArtifacts.getShared({ appArtifactId });
522
+ } catch (sharedError) {
523
+ if (isMerraiNotFoundError(sharedError) && merraiNotFoundReason(sharedError) === void 0) return null;
524
+ throw sharedError;
525
+ }
526
+ };
527
+ const renderPublished = (published) => [
528
+ `Published ${published.artifact.name} Version ${published.version.number} (${published.artifact.id})`,
529
+ published.smokeRender.ok ? "Smoke render: ok" : `Smoke render failed: ${published.smokeRender.detail}`,
530
+ published.sampleData.state === "valid" ? "Sample data: ok" : `Sample data ${published.sampleData.state}: ${published.sampleData.detail}`,
531
+ ...published.pendingTools.length > 0 ? [`Needs permission for: ${published.pendingTools.join(", ")} (allow them in Merrai)`] : []
532
+ ].join("\n");
533
+ const registerAppCommands = (program, context) => {
534
+ const apps = program.command("apps").description("Use your App Artifacts and build them from a local folder");
535
+ apps.command("list").description("List your apps").option("--archived", "List archived apps instead").action(async (options, command) => {
536
+ const result = await context.client(command).appArtifacts.list({ status: options.archived === true ? "archived" : "active" });
537
+ context.output(command).data(result, renderList);
538
+ });
539
+ apps.command("shared").description("List apps other people shared with you").action(async (_options, command) => {
540
+ const result = await context.client(command).appArtifacts.sharedWithMe();
541
+ context.output(command).data(result, renderShared);
542
+ });
543
+ apps.command("show").description("Show one app, its sync state and the handlers you can call").argument("<id>", "App Artifact ID").action(async (id, _options, command) => {
544
+ const client = context.client(command);
545
+ let owned;
546
+ try {
547
+ owned = await client.appArtifacts.get({ appArtifactId: id });
548
+ } catch (ownerError) {
549
+ if (!isMerraiNotFoundError(ownerError)) throw ownerError;
550
+ const shared = await sharedOrPlainRefusal(client, id);
551
+ if (shared === null) throw ownerError;
552
+ context.output(command).data(shared, renderSharedArtifact);
553
+ return;
554
+ }
555
+ context.output(command).data(owned, renderArtifact);
556
+ });
557
+ apps.command("call").description("Run one of an app's queries, mutations or actions").argument("<id>", "App Artifact ID").argument("<kind>", `Handler kind: ${CALL_KINDS.join(", ")}`).argument("<name>", "Handler name, as `merrai apps show` lists it").option("--input <json>", "The handler's input as JSON (default {})").option("--file <path>", "Read the input JSON from a file, or - for stdin").action(async (id, kind, name, options, command) => {
558
+ const callKind = parseCallKind(kind);
559
+ const input = options.input === void 0 && options.file === void 0 ? {} : await readStructuredInput({
560
+ cwd: context.runtime.cwd,
561
+ file: options.file,
562
+ input: options.input,
563
+ stdin: context.runtime.stdin
564
+ });
565
+ const result = await context.client(command).appArtifacts.call({
566
+ appArtifactId: id,
567
+ kind: callKind,
568
+ name,
569
+ input
570
+ });
571
+ if (!result.ok) throw new MerraiCliAppArtifactCallError(result.code === "needs_approval" ? `${result.error} Follow it with \`merrai apps requests ${id}\`.` : result.error, result.fault);
572
+ context.output(command).data(result.value);
573
+ });
574
+ apps.command("requests").description("Your requests waiting for, or decided by, an app's owner").argument("<id>", "App Artifact ID").action(async (id, _options, command) => {
575
+ const result = await context.client(command).appArtifacts.actionRequests({ appArtifactId: id });
576
+ context.output(command).data(result, renderRequests);
577
+ });
578
+ apps.command("cancel-request").description("Take back a request that still waits for the owner").argument("<id>", "App Artifact ID").argument("<request>", "Request ID, as `merrai apps requests` lists it").action(async (id, requestId, _options, command) => {
579
+ const result = await context.client(command).appArtifacts.cancelActionRequest({
580
+ appArtifactId: id,
581
+ requestId
582
+ });
583
+ context.output(command).data(result, (request) => `Request ${request.id}: ${request.status}`);
584
+ });
585
+ apps.command("open").description("Print a link that opens the app in your browser").argument("<id>", "App Artifact ID").action(async (id, _options, command) => {
586
+ const result = await context.client(command).appArtifacts.openUrl({
587
+ appArtifactId: id,
588
+ mode: "window"
589
+ });
590
+ context.output(command).data(result, (value) => value.url);
591
+ });
592
+ apps.command("guide").description("Print how to build an app: read authoring first, then design before any UI").argument("[topic]", GUIDE_TOPICS.join(" or "), "authoring").action(async (topic, _options, command) => {
593
+ const guide = await context.client(command).appArtifacts.buildingGuide({ topic: parseGuideTopic(topic) });
594
+ const { format, json } = command.optsWithGlobals();
595
+ if (json === true || format === "json") {
596
+ context.output(command).data(guide);
597
+ return;
598
+ }
599
+ context.runtime.stdout.write(`${guide.text.trimEnd()}\n`);
600
+ });
601
+ apps.command("create").description("Create an app, optionally from a folder and published").argument("<name>", "The app's name").option("--from <dir>", "Save this folder as the app's Working source").option("--publish", "Publish the folder as Version 1 (needs --from)").option("-m, --message <message>", "Describe the change (with --from)").action(async (name, options, command) => {
602
+ if (options.publish === true && options.from === void 0) throw new MerraiCliUsageError("--publish needs --from <dir>");
603
+ const directory = options.from === void 0 ? void 0 : NodePath.resolve(context.runtime.cwd, options.from);
604
+ const files = directory === void 0 ? void 0 : await readAppSourceFolder(directory);
605
+ const message = files === void 0 ? void 0 : requireMessage(options.message);
606
+ const client = context.client(command);
607
+ const created = await client.appArtifacts.create({
608
+ name,
609
+ creationKey: NodeCrypto.randomUUID()
610
+ });
611
+ if (directory === void 0 || files === void 0 || message === void 0) {
612
+ context.output(command).data(created, renderArtifact);
613
+ return;
614
+ }
615
+ const saved = await client.appArtifacts.saveSource({
616
+ appArtifactId: created.id,
617
+ files,
618
+ message
619
+ });
620
+ await writeAppSourceRevision(directory, saved.revision);
621
+ if (options.publish !== true) {
622
+ context.output(command).data(await client.appArtifacts.get({ appArtifactId: created.id }), renderArtifact);
623
+ return;
624
+ }
625
+ const published = await client.appArtifacts.publish({
626
+ appArtifactId: created.id,
627
+ message,
628
+ publishKey: NodeCrypto.randomUUID(),
629
+ expectedRevision: saved.revision
630
+ });
631
+ context.output(command).data(published, renderPublished);
632
+ });
633
+ apps.command("pull").description("Write an app's Working source into a folder").argument("<id>", "App Artifact ID").argument("<dir>", "An empty folder").option("--force", "Overwrite files already in the folder").action(async (id, dir, options, command) => {
634
+ const { files, revision } = await context.client(command).appArtifacts.source({ appArtifactId: id });
635
+ const directory = NodePath.resolve(context.runtime.cwd, dir);
636
+ await writeAppSourceFolder(directory, files, { force: options.force === true });
637
+ await writeAppSourceRevision(directory, revision);
638
+ context.output(command).data({
639
+ appArtifactId: id,
640
+ directory,
641
+ files: Object.keys(files).toSorted()
642
+ }, (value) => `Wrote ${value.files.length} files to ${value.directory}`);
643
+ });
644
+ apps.command("push").description("Save a folder as an app's Working source without publishing it").argument("<id>", "App Artifact ID").argument("<dir>", "The app's folder").option("-m, --message <message>", "Describe the change").action(async (id, dir, options, command) => {
645
+ const message = requireMessage(options.message);
646
+ const directory = NodePath.resolve(context.runtime.cwd, dir);
647
+ const saved = await context.client(command).appArtifacts.saveSource({
648
+ appArtifactId: id,
649
+ files: await readAppSourceFolder(directory),
650
+ message,
651
+ expectedRevision: await readAppSourceRevision(directory)
652
+ });
653
+ await writeAppSourceRevision(directory, saved.revision);
654
+ context.output(command).data({
655
+ appArtifactId: id,
656
+ revision: saved.revision
657
+ }, (value) => `Saved the Working source at ${value.revision}. Publish it with merrai apps publish ${value.appArtifactId} -m <message>.`);
658
+ });
659
+ apps.command("publish").description("Build the Working source into a new Version").argument("<id>", "App Artifact ID").option("--push <dir>", "First save this folder as the Working source").option("-m, --message <message>", "Describe the change").action(async (id, options, command) => {
660
+ const message = requireMessage(options.message);
661
+ const client = context.client(command);
662
+ let expectedRevision;
663
+ if (options.push !== void 0) {
664
+ const directory = NodePath.resolve(context.runtime.cwd, options.push);
665
+ const files = await readAppSourceFolder(directory);
666
+ const saved = await client.appArtifacts.saveSource({
667
+ appArtifactId: id,
668
+ files,
669
+ message,
670
+ expectedRevision: await readAppSourceRevision(directory)
671
+ });
672
+ await writeAppSourceRevision(directory, saved.revision);
673
+ expectedRevision = saved.revision;
674
+ }
675
+ const published = await client.appArtifacts.publish({
676
+ appArtifactId: id,
677
+ message,
678
+ publishKey: NodeCrypto.randomUUID(),
679
+ expectedRevision
680
+ });
681
+ context.output(command).data(published, renderPublished);
682
+ });
683
+ apps.command("delete").description("Delete an archived app forever: its data, Versions, source and sharing").argument("<id>", "App Artifact ID").option("--confirm <name>", "The app's exact name, to delete without being asked").action(async (id, options, command) => {
684
+ const client = context.client(command);
685
+ let artifact;
686
+ try {
687
+ artifact = await client.appArtifacts.get({ appArtifactId: id });
688
+ } catch (error) {
689
+ if (!isMerraiNotFoundError(error)) throw error;
690
+ context.output(command).data(await finishDeleted(client, id), renderAlreadyDeleted);
691
+ return;
692
+ }
693
+ if (artifact.status !== "archived") throw new MerraiCliUsageError(`Archive this app before you delete it: ${artifact.name} is still active.`);
694
+ const typed = options.confirm ?? await readTypedConfirmation({
695
+ input: context.runtime.stdin,
696
+ message: `This deletes ${artifact.name} forever, with everything it saved, its Versions, its source and who it was shared with. Your connected accounts stay connected. Type ${artifact.name} to confirm:`,
697
+ output: context.runtime.stderr
698
+ });
699
+ if (typed === void 0) throw new MerraiCliUsageError(`Delete cancelled. Use --confirm "${artifact.name}" for noninteractive confirmation.`);
700
+ if (typed !== artifact.name) throw new MerraiCliUsageError(`Delete cancelled: that is not this app's name (${artifact.name}).`);
701
+ const deleted = await client.appArtifacts.delete({ appArtifactId: id });
702
+ context.output(command).data(deleted, renderDeleted(artifact.name));
703
+ });
704
+ };
705
+ const CREDENTIALS_VERSION = 1;
706
+ const trimmed = (value) => {
707
+ const result = value?.trim();
708
+ return result === void 0 || result.length === 0 ? void 0 : result;
709
+ };
710
+ const credentialsValueSchema = z.object({
711
+ apiKey: z.string().trim().min(1),
712
+ baseURL: z.string().trim().min(1).nullish(),
713
+ savedAt: z.string().optional(),
714
+ version: z.literal(CREDENTIALS_VERSION).optional()
715
+ });
716
+ const systemErrorSchema = z.object({ code: z.string() });
717
+ const resolveHomeDirectory = (env) => trimmed(env.HOME) ?? trimmed(env.USERPROFILE) ?? NodeOS.homedir();
718
+ const resolveMerraiConfigPaths = (env) => {
719
+ const home = resolveHomeDirectory(env);
720
+ const xdgConfigHome = trimmed(env.XDG_CONFIG_HOME);
721
+ const windowsAppData = trimmed(env.APPDATA);
722
+ const directory = xdgConfigHome !== void 0 ? NodePath.join(xdgConfigHome, "merrai") : process.platform === "win32" && windowsAppData !== void 0 ? NodePath.join(windowsAppData, "Merrai") : NodePath.join(home, ".config", "merrai");
723
+ return {
724
+ credentials: NodePath.join(directory, "credentials.json"),
725
+ directory,
726
+ legacyClaudeCredentials: NodePath.join(home, ".merrai-claude-code", "credentials.json")
727
+ };
728
+ };
729
+ const parseCredentials = (raw, options) => {
730
+ try {
731
+ const parsed = credentialsValueSchema.safeParse(JSON.parse(raw));
732
+ if (!parsed.success) return null;
733
+ const value = parsed.data;
734
+ if (options.requireVersion && value.version !== CREDENTIALS_VERSION) return null;
735
+ const credentials = {
736
+ apiKey: value.apiKey,
737
+ savedAt: value.savedAt ?? (/* @__PURE__ */ new Date(0)).toISOString(),
738
+ version: CREDENTIALS_VERSION
739
+ };
740
+ if (value.baseURL !== void 0 && value.baseURL !== null) credentials.baseURL = value.baseURL;
741
+ return credentials;
742
+ } catch {
743
+ return null;
744
+ }
745
+ };
746
+ const readCredentialsFile = (file, options) => {
747
+ if (!NodeFS.existsSync(file)) return null;
748
+ try {
749
+ const credentials = parseCredentials(NodeFS.readFileSync(file, "utf8"), { requireVersion: options.requireVersion });
750
+ if (credentials === null && options.strict) throw new Error(`Invalid Merrai credentials file at ${file}. Run 'merrai auth set-key' to replace it.`);
751
+ return credentials;
752
+ } catch (error) {
753
+ if (options.strict) throw error;
754
+ return null;
755
+ }
756
+ };
757
+ const loadMerraiCredentials = (env, options = {}) => {
758
+ const paths = resolveMerraiConfigPaths(env);
759
+ return readCredentialsFile(paths.credentials, {
760
+ requireVersion: true,
761
+ strict: options.strict === true
762
+ }) ?? readCredentialsFile(paths.legacyClaudeCredentials, {
763
+ requireVersion: false,
764
+ strict: options.strict === true
765
+ });
766
+ };
767
+ const saveMerraiCredentials = (env, input) => {
768
+ const apiKey = trimmed(input.apiKey);
769
+ if (apiKey === void 0) throw new Error("API key cannot be empty");
770
+ const paths = resolveMerraiConfigPaths(env);
771
+ NodeFS.mkdirSync(paths.directory, {
772
+ mode: 448,
773
+ recursive: true
774
+ });
775
+ NodeFS.chmodSync(paths.directory, 448);
776
+ const credentials = {
777
+ apiKey,
778
+ baseURL: trimmed(input.baseURL) ?? "https://api.merrai.app",
779
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
780
+ version: CREDENTIALS_VERSION
781
+ };
782
+ NodeFS.writeFileSync(paths.credentials, JSON.stringify(credentials, null, 2), { mode: 384 });
783
+ NodeFS.chmodSync(paths.credentials, 384);
784
+ return credentials;
785
+ };
786
+ const removeFileIfPresent = (file) => {
787
+ try {
788
+ NodeFS.unlinkSync(file);
789
+ return true;
790
+ } catch (error) {
791
+ const systemError = systemErrorSchema.safeParse(error);
792
+ if (systemError.success && systemError.data.code === "ENOENT") return false;
793
+ throw error;
794
+ }
795
+ };
796
+ const clearMerraiCredentials = (env, options = {}) => {
797
+ const paths = resolveMerraiConfigPaths(env);
798
+ const removedShared = removeFileIfPresent(paths.credentials);
799
+ const removedLegacy = options.includeLegacy === true ? removeFileIfPresent(paths.legacyClaudeCredentials) : false;
800
+ return removedShared || removedLegacy;
801
+ };
802
+ const resolveMerraiClientOptions = (env, overrides, options = {}) => {
803
+ const apiKeyOverride = trimmed(overrides.apiKey) ?? trimmed(env.MERRAI_API_KEY);
804
+ const baseURLOverride = trimmed(overrides.baseURL) ?? trimmed(env.MERRAI_BASE_URL);
805
+ const credentials = apiKeyOverride !== void 0 && baseURLOverride !== void 0 ? null : loadMerraiCredentials(env, { strict: options.strictCredentials !== false });
806
+ return {
807
+ apiKey: apiKeyOverride ?? credentials?.apiKey,
808
+ baseURL: baseURLOverride ?? credentials?.baseURL ?? "https://api.merrai.app",
809
+ cookie: trimmed(overrides.cookie) ?? trimmed(env.MERRAI_COOKIE)
810
+ };
811
+ };
812
+ // src/commands/auth.ts
813
+ const registerAuthCommands = (program, context) => {
814
+ const auth = program.command("auth").description("Manage CLI credentials");
815
+ auth.command("set-key").argument("[apiKey]", "Merrai API key").description("Validate and save an API key").action(async (positional, _options, actionCommand) => {
816
+ const globals = actionCommand.optsWithGlobals();
817
+ const apiKey = [
818
+ positional,
819
+ globals.apiKey,
820
+ context.runtime.env.MERRAI_API_KEY
821
+ ].map((value) => value?.trim()).find((value) => value !== void 0 && value.length > 0) ?? await readSecretInput({
822
+ input: context.runtime.stdin,
823
+ message: "Merrai API key: ",
824
+ output: context.runtime.stderr
825
+ });
826
+ if (apiKey.length === 0) throw new MerraiCliUsageError("API key cannot be empty");
827
+ const connection = resolveMerraiClientOptions(context.runtime.env, {
828
+ apiKey,
829
+ baseURL: globals.baseUrl
830
+ }, { strictCredentials: false });
831
+ await context.runtime.createClient(connection).memoryStatus({});
832
+ const credentials = saveMerraiCredentials(context.runtime.env, {
833
+ apiKey,
834
+ baseURL: connection.baseURL
835
+ });
836
+ context.output(actionCommand).data({
837
+ authenticated: true,
838
+ baseURL: credentials.baseURL
839
+ }, () => `Saved API key for ${credentials.baseURL}.`);
840
+ });
841
+ auth.command("status").description("Show credential status without revealing the key").action(async (_options, actionCommand) => {
842
+ const credentials = loadMerraiCredentials(context.runtime.env, { strict: true });
843
+ const paths = resolveMerraiConfigPaths(context.runtime.env);
844
+ const result = {
845
+ authenticated: credentials !== null || (context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0,
846
+ baseURL: credentials?.baseURL ?? null,
847
+ configured: credentials !== null,
848
+ credentialsPath: paths.credentials,
849
+ environmentKeySet: (context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0
850
+ };
851
+ context.output(actionCommand).data(result, () => result.configured ? `Authenticated for ${result.baseURL}.` : result.environmentKeySet ? "Authenticated through MERRAI_API_KEY." : "No saved CLI credentials.");
852
+ });
853
+ auth.command("logout").description("Remove saved CLI credentials").option("--yes", "Skip confirmation").action(async (options, actionCommand) => {
854
+ if (options.yes !== true) {
855
+ if (!await confirmAction({
856
+ input: context.runtime.stdin,
857
+ message: "Remove saved Merrai CLI credentials?",
858
+ output: context.runtime.stderr
859
+ })) throw new MerraiCliUsageError("Logout cancelled. Use --yes for noninteractive confirmation.");
860
+ }
861
+ const removed = clearMerraiCredentials(context.runtime.env, { includeLegacy: true });
862
+ const output = context.output(actionCommand);
863
+ output.data({ removed }, () => removed ? "Removed saved credentials." : "No saved credentials found.");
864
+ if ((context.runtime.env.MERRAI_API_KEY?.trim().length ?? 0) > 0) output.diagnostic("MERRAI_API_KEY is still set; commands will continue using it.");
865
+ });
866
+ };
867
+ // src/commands/debug.ts
868
+ const configureRpcCommand = (command, context) => {
869
+ 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) => {
870
+ const procedure = context.debugProcedure(actionCommand, procedureName);
871
+ const input = options.input !== void 0 || options.file !== void 0 ? await readStructuredInput({
872
+ cwd: context.runtime.cwd,
873
+ file: options.file,
874
+ input: options.input,
875
+ stdin: context.runtime.stdin
876
+ }) : void 0;
877
+ const result = z.json().parse(await procedure(input));
878
+ context.output(actionCommand).data(result);
879
+ });
880
+ };
881
+ const registerDebugCommands = (program, context) => {
882
+ const debug = program.command("debug").description("Unstable debugging commands");
883
+ configureRpcCommand(debug.command("rpc").description("Call a top-level oRPC procedure"), context);
884
+ configureRpcCommand(program.command("rpc", { hidden: true }).description("Legacy raw oRPC command"), context);
885
+ };
886
+ // src/memory-replacement.ts
887
+ /**
888
+ * Exhaustive at compile time; a precision this client does not know reads as
889
+ * unknown rather than failing the output.
890
+ */
891
+ const unsupportedPrecision = (_time) => "unknown";
892
+ /**
893
+ * The calendar reading alone: "2024-04-05", "week of 2024-04-01",
894
+ * "2024-04-20 to 2024-04-21".
895
+ */
896
+ const calendarText = (time) => {
897
+ switch (time.precision) {
898
+ case "week": return `week of ${time.value}`;
899
+ case "day":
900
+ case "month":
901
+ case "year": return time.value;
902
+ case "range": return `${time.start} to ${time.end}`;
903
+ case "unknown": return "unknown";
904
+ default: return unsupportedPrecision(time);
905
+ }
906
+ };
907
+ /** A plan's or deadline's role; null for what happened or an unstated role. */
908
+ const forwardRole = (time) => {
909
+ const role = time.precision === "unknown" ? null : time.role;
910
+ return role === "planned" || role === "due" ? role : null;
911
+ };
912
+ /**
913
+ * An event time as the server words it: a plan or a deadline names its role
914
+ * ("due 2024-04-20"); what happened is the calendar reading alone.
915
+ */
916
+ const describeEventTime = (time) => {
917
+ if (time.precision === "multiple") return time.alternatives.map(describeEventTime).join(" or ");
918
+ const role = forwardRole(time);
919
+ return role === null ? calendarText(time) : `${role} ${calendarText(time)}`;
920
+ };
921
+ /** Whether any reading of the time is a plan or a deadline. */
922
+ const hasForwardRole = (time) => (time.precision === "multiple" ? time.alternatives : [time]).some((reading) => forwardRole(reading) !== null);
923
+ /**
924
+ * "replaces: <earlier text> (due 2024-04-20)": the line Merrai's Search and
925
+ * recall evidence show under a Memory that replaced an earlier value (the
926
+ * latest Memory it supersedes), so a terse update keeps its subject and the
927
+ * old value. Null when it replaced none.
928
+ */
929
+ const renderMemoryReplacement = (replaced) => {
930
+ if (replaced === null || replaced === void 0) return null;
931
+ const time = replaced.eventTime === null || replaced.eventTime.precision === "unknown" ? null : describeEventTime(replaced.eventTime);
932
+ return time === null ? `replaces: ${replaced.content}` : `replaces: ${replaced.content} (${time})`;
933
+ };
934
+ const UPDATE_MARK_LABELS = {
935
+ updated_by: "↳ updated by",
936
+ updates: "replaces"
937
+ };
938
+ /**
939
+ * A linked memory as a mark names it: by its id when the reader is shown it
940
+ * too, otherwise its text with when it happened or is planned or due and the
941
+ * day it was said: "Budget is now $4,000. (said 2024-03-16)".
942
+ */
943
+ const linkedMemoryText = (mark, shownIds) => {
944
+ if (shownIds.has(mark.id)) return mark.id;
945
+ const time = mark.eventTime;
946
+ const notes = [time === null || time.precision === "unknown" ? null : hasForwardRole(time) ? describeEventTime(time) : `happened ${describeEventTime(time)}`, mark.said === null ? null : `said ${mark.said}`].filter((note) => note !== null);
947
+ return notes.length === 0 ? mark.content : `${mark.content} (${notes.join("; ")})`;
948
+ };
949
+ /**
950
+ * "↳ updated by: …" and "replaces: …": the update marks Merrai's Search shows
951
+ * under a memory, newer values first, one line per relation. A later value
952
+ * never retires the earlier one; both stay current. A relation this client
953
+ * does not know is left out rather than failing the output.
954
+ */
955
+ const renderMemoryUpdateMarks = (marks, shownIds) => ["updated_by", "updates"].flatMap((relation) => {
956
+ const members = (marks ?? []).filter((mark) => mark.relation === relation);
957
+ return members.length === 0 ? [] : [`${UPDATE_MARK_LABELS[relation]}: ${members.map((mark) => linkedMemoryText(mark, shownIds)).join("; ")}`];
958
+ });
959
+ /**
960
+ * Each search result's lines as Merrai's Search shows them: its own line
961
+ * (`renderLine`), labelled with its id when another result's mark names it,
962
+ * then what it replaced and its update marks.
963
+ */
964
+ const searchResultLines = (results, renderLine) => {
965
+ const shownIds = new Set(results.map((result) => result.id));
966
+ const named = new Set(results.flatMap((result) => (result.linked ?? []).flatMap((mark) => shownIds.has(mark.id) ? [mark.id] : [])));
967
+ return results.map((result) => {
968
+ const line = renderLine(result);
969
+ const replaced = renderMemoryReplacement(result.replaces);
970
+ return [
971
+ named.has(result.id) ? `${line} [${result.id}]` : line,
972
+ ...replaced === null ? [] : [replaced],
973
+ ...renderMemoryUpdateMarks(result.linked, shownIds)
974
+ ];
975
+ });
976
+ };
977
+ // src/commands/entity.ts
978
+ /** `entity memories` keeps its earlier default of 20 within the shared maximum of 25. */
979
+ const ENTITY_MEMORIES_DEFAULT_LIMIT = 20;
980
+ const renderEntities = (result) => {
981
+ if (result.entities.length === 0) return "No matching entities found.";
982
+ return result.entities.map((entity) => `- ${entity.displayName} (${entity.type}, ${entity.memoryCount} memories, ${entity.id})`).join("\n");
983
+ };
984
+ /**
985
+ * "# Ada (person)", then each linked memory as `memory search` shows it:
986
+ * its line, then what it replaced and its update marks beneath it.
987
+ */
988
+ const renderEntityMemories = (result) => {
989
+ const [entity] = result.matchedEntities;
990
+ const heading = entity === void 0 ? "# Entity" : `# ${entity.displayName} (${entity.type})`;
991
+ if (result.memories.length === 0) return `${heading}\nNo linked memories.`;
992
+ return [heading, ...searchResultLines(result.memories, (memory) => `- ${memory.recordedAt?.slice(0, 10) ?? "undated"}: ${memory.content}`).map((lines) => lines.join("\n "))].join("\n");
993
+ };
994
+ const configureFindCommand = (command, context) => {
995
+ 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) => {
996
+ const name = options.name ?? positional;
997
+ if (name === void 0 || name.trim().length === 0) throw new MerraiCliUsageError("Provide an entity name");
998
+ const input = {
999
+ limit: parseIntegerOption(options.limit, "--limit", {
1000
+ maximum: 25,
1001
+ minimum: 1
1002
+ }),
1003
+ name,
1004
+ type: parseEntityType(options.type)
1005
+ };
1006
+ const result = await context.client(actionCommand).findMemoryEntities(input);
1007
+ context.output(actionCommand).data(result, renderEntities);
1008
+ });
1009
+ };
1010
+ const configureMemoriesCommand = (command, context) => {
1011
+ command.argument("[entityId]", "Entity id").option("--entity-id <id>", "Entity id").option("--limit <number>", "Maximum results, 1-25 (default 20)").action(async (positional, options, actionCommand) => {
1012
+ const entityId = options.entityId ?? positional;
1013
+ if (entityId === void 0 || entityId.trim().length === 0) throw new MerraiCliUsageError("Provide an entity id");
1014
+ const input = {
1015
+ entityId,
1016
+ limit: parseIntegerOption(options.limit, "--limit", {
1017
+ maximum: 25,
1018
+ minimum: 1
1019
+ }) ?? ENTITY_MEMORIES_DEFAULT_LIMIT
1020
+ };
1021
+ const result = await context.client(actionCommand).recall.searchMemories(input);
1022
+ context.output(actionCommand).data(result, renderEntityMemories);
1023
+ });
1024
+ };
1025
+ const registerEntityCommands = (program, context) => {
1026
+ const entity = program.command("entity").description("Find memory entities");
1027
+ configureFindCommand(entity.command("find").description("Find entities by name"), context);
1028
+ configureFindCommand(program.command("find-entity", { hidden: true }).description("Legacy entity find"), context);
1029
+ configureMemoriesCommand(entity.command("memories").description("Recall memories linked to an entity"), context);
1030
+ configureMemoriesCommand(program.command("search-memories-by-entity", { hidden: true }).description("Legacy entity recall"), context);
1031
+ };
1032
+ // src/idempotency.ts
1033
+ /** Accepted by every write API's `idempotencyKey`, including `addChatSessions`. */
1034
+ const IDEMPOTENCY_KEY_HEX_LENGTH = 48;
1035
+ const isKeyMaterialRecord = (value) => value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
1036
+ const canonicalJson = (value) => {
1037
+ if (value === void 0) return "null";
1038
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
1039
+ if (isKeyMaterialRecord(value)) return `{${Object.entries(value).filter(([, entry]) => entry !== void 0).toSorted(([left], [right]) => left < right ? -1 : 1).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
1040
+ return JSON.stringify(value);
1041
+ };
1042
+ /**
1043
+ * A stable idempotency key derived from what one write sends, so a rerun joins
1044
+ * the existing ingestion; any change to content, source, lobe or dates changes
1045
+ * it. `operation` namespaces keys by API shape. Undefined fields are omitted,
1046
+ * so an absent option and an explicit `undefined` produce the same key.
1047
+ */
1048
+ const deriveIdempotencyKey = (operation, payload) => NodeCrypto.createHash("sha256").update(canonicalJson({
1049
+ operation,
1050
+ payload,
1051
+ version: 1
1052
+ })).digest("hex").slice(0, IDEMPOTENCY_KEY_HEX_LENGTH);
1053
+ /**
1054
+ * The key for saving one memory (CLI `memory add`, the plugin's
1055
+ * `/merrai:save`). Without a supplied observation time, the same sentence
1056
+ * saved on a later day is a new occurrence ("went running"), not a retry, so
1057
+ * the UTC day joins the key; same-day reruns still collapse into one save.
1058
+ */
1059
+ const deriveMemorySaveIdempotencyKey = (input) => deriveIdempotencyKey("memory-save", {
1060
+ lobeKey: input.lobeKey,
1061
+ memory: input.memory,
1062
+ observationDate: input.observationDate,
1063
+ occurrenceDay: input.observationDate === void 0 ? input.now.toISOString().slice(0, 10) : void 0,
1064
+ source: input.source
1065
+ });
1066
+ // src/commands/ingest.ts
1067
+ const memoryInputSchema = z.object({
1068
+ lobeKey: z.string().optional(),
1069
+ memory: z.string(),
1070
+ observationDate: z.string().optional(),
1071
+ source: z.string().optional()
1072
+ });
1073
+ const chatMemoryInputSchema = z.object({
1074
+ memory: z.string(),
1075
+ observationDate: z.iso.datetime().optional(),
1076
+ source: z.string().optional()
1077
+ });
1078
+ const addMemoriesInputSchema = z.object({ memories: z.array(memoryInputSchema) });
1079
+ const addChatSessionInputSchema = z.object({
1080
+ idempotencyKey: z.string().optional(),
1081
+ lobeKey: z.string().optional(),
1082
+ memories: z.array(chatMemoryInputSchema),
1083
+ sessionMetadata: z.record(z.string(), z.json()).optional(),
1084
+ source: z.string().optional()
1085
+ });
1086
+ const addChatSessionsInputSchema = z.object({
1087
+ idempotencyKey: z.string().optional(),
1088
+ lobeKey: z.string().optional(),
1089
+ questionMetadata: z.record(z.string(), z.json()).optional(),
1090
+ sessions: z.array(z.object({
1091
+ metadata: z.record(z.string(), z.json()).optional(),
1092
+ sessionId: z.string(),
1093
+ turns: z.array(z.object({
1094
+ content: z.string(),
1095
+ role: z.enum(["user", "assistant"]),
1096
+ sourceTime: z.string().optional(),
1097
+ speaker: z.string().optional(),
1098
+ turnIndex: z.number()
1099
+ }))
1100
+ })),
1101
+ source: z.string().optional()
1102
+ });
1103
+ const parseUsageInput = (schema, value, message) => {
1104
+ const result = schema.safeParse(value);
1105
+ if (!result.success) throw new MerraiCliUsageError(message, { cause: result.error });
1106
+ return result.data;
1107
+ };
1108
+ const parseMemoriesInput = (value) => {
1109
+ if (!Array.isArray(value)) throw new MerraiCliUsageError("Memory ingest input must be a JSON array");
1110
+ const input = parseUsageInput(addMemoriesInputSchema, { memories: value }, "Memory ingest input does not match the expected schema");
1111
+ return {
1112
+ idempotencyKey: deriveIdempotencyKey("ingest-memories", input),
1113
+ ...input
1114
+ };
1115
+ };
1116
+ const parseChatInput = (value) => {
1117
+ const { idempotencyKey, ...input } = parseUsageInput(addChatSessionInputSchema, value, "Chat ingest input does not match the expected schema");
1118
+ return {
1119
+ ...input,
1120
+ idempotencyKey: idempotencyKey ?? deriveIdempotencyKey("ingest-chat", input)
1121
+ };
1122
+ };
1123
+ const parseChatsInput = (value) => {
1124
+ const { idempotencyKey, ...input } = parseUsageInput(addChatSessionsInputSchema, value, "Multi-chat ingest input does not match the expected schema");
1125
+ return {
1126
+ ...input,
1127
+ idempotencyKey: idempotencyKey ?? deriveIdempotencyKey("ingest-chats", input)
1128
+ };
1129
+ };
1130
+ const configureStructuredCommand = (command, context, parse, submit) => {
1131
+ command.option("--input <json>", "Inline JSON input").option("--file <path>", "Read JSON from a file, or - for stdin").action(async (options, actionCommand) => {
1132
+ const result = await submit(actionCommand, parse(await readStructuredInput({
1133
+ cwd: context.runtime.cwd,
1134
+ file: options.file,
1135
+ input: options.input,
1136
+ stdin: context.runtime.stdin
1137
+ })));
1138
+ context.output(actionCommand).data(result, (value) => describeQueuedIngestion("Ingest", value.ingestionId));
1139
+ });
1140
+ };
1141
+ const registerIngestCommands = (program, context) => {
1142
+ const ingest = program.command("ingest").description("Bulk memory ingestion");
1143
+ const registerMemories = (command) => configureStructuredCommand(command, context, parseMemoriesInput, async (actionCommand, input) => context.client(actionCommand).addMemories(input));
1144
+ registerMemories(ingest.command("memories").description("Ingest memories"));
1145
+ registerMemories(program.command("add-memories", { hidden: true }).description("Legacy memory ingest"));
1146
+ const registerChat = (command) => configureStructuredCommand(command, context, parseChatInput, async (actionCommand, input) => context.client(actionCommand).addChatSession(input));
1147
+ registerChat(ingest.command("chat").description("Ingest one chat session"));
1148
+ registerChat(program.command("add-chat-session", { hidden: true }).description("Legacy chat ingest"));
1149
+ const registerChats = (command) => configureStructuredCommand(command, context, parseChatsInput, async (actionCommand, input) => context.client(actionCommand).addChatSessions(input));
1150
+ registerChats(ingest.command("chats").description("Ingest multiple chat sessions"));
1151
+ registerChats(program.command("add-chat-sessions", { hidden: true }).description("Legacy multi-chat ingest"));
1152
+ };
1153
+ // src/commands/ingestion.ts
1154
+ const renderIngestionStatus = (status) => {
1155
+ const lines = [`Ingestion ${status.ingestionId}: ${status.status} (attempt ${status.attempt})`];
1156
+ if (status.pausedReason === "quota_exceeded") lines.push("Waiting for memory quota; it resumes automatically.");
1157
+ if (status.error !== null) lines.push(`Error: ${status.error}`);
1158
+ const result = status.result;
1159
+ if (result !== null) {
1160
+ lines.push(`Sources: ${result.artifacts.length}`);
1161
+ lines.push(`Extraction: ${result.observation.status}`);
1162
+ if ((result.observation.blockedWindows ?? 0) > 0) lines.push(`Blocked windows: ${result.observation.blockedWindows ?? 0} (${result.observation.retryableBlockedWindows ?? 0} retryable with \`merrai ingestion retry\`)`);
1163
+ lines.push(result.memory.status === "completed" || result.memory.status === "deferred" && result.memory.reason === "repair_scheduled" ? `Memories: ${result.memory.created} created, ${result.memory.updated} updated, ${result.memory.reinforced} reinforced` : `Memories: ${result.memory.status} (${result.memory.reason})`);
1164
+ }
1165
+ return lines.join("\n");
1166
+ };
1167
+ const registerIngestionCommands = (program, context) => {
1168
+ const ingestion = program.command("ingestion").description("Follow and retry the processing of saved content");
1169
+ ingestion.command("status").description("Show an ingestion's progress and result").argument("<id>", "Ingestion ID returned by a save or retry").action(async (id, _options, command) => {
1170
+ const result = await context.client(command).ingestionStatus({ ingestionId: id });
1171
+ context.output(command).data(result, renderIngestionStatus);
1172
+ });
1173
+ ingestion.command("retry").description("Extract again the windows a finished ingestion could not extract").argument("<id>", "Ingestion ID of a finished partial ingestion").action(async (id, _options, command) => {
1174
+ const result = await context.client(command).retryIngestionBlockedWindows({ ingestionId: id });
1175
+ context.output(command).data(result, (value) => describeQueuedIngestion("Retry", value.ingestionId));
1176
+ });
1177
+ };
1178
+ // src/commands/living-document.ts
1179
+ const renderLobeScope = (scope) => scope?.kind === "selected" ? ` (lobes: ${scope.lobeKeys.join(", ")})` : "";
1180
+ const renderDocumentList = (value) => {
1181
+ if (value.documents.length === 0) return "No living documents found.";
1182
+ return value.documents.map((document) => `- ${document.title} (${document.id})${renderLobeScope(document.lobeScope)}`).join("\n");
1183
+ };
1184
+ const renderRetriedRebuild = (document) => {
1185
+ if (document.rebuild === null) return `${document.title} is up to date.`;
1186
+ return document.rebuild.reason === "lobe_scope_narrowed" ? `${document.title} is being updated to remove memories from lobes it no longer uses.` : `${document.title} is being updated to remove deleted sources.`;
1187
+ };
1188
+ const renderRetriedBackfill = (document) => {
1189
+ const backfill = document.lobeBackfill;
1190
+ if (backfill === void 0 || backfill === null) return `${document.title} is up to date.`;
1191
+ return `${document.title} is adding the memories already saved in ${backfill.lobeKeys.join(", ")}.`;
1192
+ };
1193
+ const configureGetCommand = (command, context) => {
1194
+ command.argument("[documentId]", "Living document id").option("--document-id <id>", "Living document id").option("--content-offset <number>", "Character offset into document content").option("--max-characters <number>", "Maximum document content characters to return").action(async (positional, options, actionCommand) => {
1195
+ const documentId = options.documentId ?? positional;
1196
+ if (documentId === void 0 || documentId.trim().length === 0) throw new MerraiCliUsageError("Provide a living document id");
1197
+ const result = await context.client(actionCommand).recall.readLivingDocument({
1198
+ contentOffset: parseIntegerOption(options.contentOffset, "--content-offset", {
1199
+ maximum: 1e7,
1200
+ minimum: 0
1201
+ }),
1202
+ documentId,
1203
+ maxCharacters: parseIntegerOption(options.maxCharacters, "--max-characters", {
1204
+ maximum: 2e4,
1205
+ minimum: 1
1206
+ })
1207
+ });
1208
+ context.output(actionCommand).data(result, (value) => JSON.stringify(value, null, 2));
1209
+ });
1210
+ };
1211
+ const registerLivingDocumentCommands = (program, context) => {
1212
+ const document = program.command("document").description("Read living documents");
1213
+ const listAction = async (options, command) => {
1214
+ const result = await context.client(command).recall.listLivingDocuments({
1215
+ limit: parseIntegerOption(options.limit, "--limit", {
1216
+ maximum: 50,
1217
+ minimum: 1
1218
+ }),
1219
+ offset: parseIntegerOption(options.offset, "--offset", {
1220
+ maximum: 1e5,
1221
+ minimum: 0
1222
+ })
1223
+ });
1224
+ context.output(command).data(result, renderDocumentList);
1225
+ };
1226
+ document.command("list").description("List living documents").option("--limit <number>", "Maximum documents to return").option("--offset <number>", "Zero-based document offset").action(async (options, command) => listAction(options, command));
1227
+ program.command("list-living-documents", { hidden: true }).description("Legacy living document list").option("--limit <number>", "Maximum documents to return").option("--offset <number>", "Zero-based document offset").action(async (options, command) => listAction(options, command));
1228
+ configureGetCommand(document.command("get").description("Read a bounded living document content chunk"), context);
1229
+ document.command("retry-rebuild").description("Retry a living document update (removing deleted sources or removed lobes) that failed").argument("<documentId>", "Living document id").action(async (documentId, _options, command) => {
1230
+ const result = await context.client(command).retryLivingDocumentRebuild({ id: documentId });
1231
+ context.output(command).data(result, ({ document: updated }) => renderRetriedRebuild(updated));
1232
+ });
1233
+ document.command("retry-backfill").description("Retry adding the memories already saved in lobes added to a living document, when that failed").argument("<documentId>", "Living document id").action(async (documentId, _options, command) => {
1234
+ const result = await context.client(command).retryLivingDocumentLobeBackfill({ id: documentId });
1235
+ context.output(command).data(result, ({ document: updated }) => renderRetriedBackfill(updated));
1236
+ });
1237
+ configureGetCommand(program.command("read-living-document", { hidden: true }).description("Legacy living document read"), context);
1238
+ };
1239
+ // src/commands/lobe.ts
1240
+ const lobesCursorSchema = z.object({
1241
+ createdAt: z.string().min(1),
1242
+ lobeKey: z.string().min(1)
1243
+ });
1244
+ const parseOwnerRecall = (value) => {
1245
+ if (value === void 0) return void 0;
1246
+ if (value === "on") return true;
1247
+ if (value === "off") return false;
1248
+ throw new MerraiCliUsageError("--owner-recall must be on or off");
1249
+ };
1250
+ const describeLobe = (lobe) => [
1251
+ `- ${lobe.name} (${lobe.lobeKey})`,
1252
+ lobe.ownerRecall ? "" : " (kept out of owner recall)",
1253
+ lobe.purpose === null ? "" : `: ${lobe.purpose}`
1254
+ ].join("");
1255
+ const registerLobeCommands = (program, context) => {
1256
+ const lobe = program.command("lobe").description("Create, list and configure memory lobes");
1257
+ lobe.command("create").description("Create a memory lobe").argument("<key>", "Lobe key").action(async (key, _options, command) => {
1258
+ const result = await context.client(command).createLobe({ lobeKey: key });
1259
+ context.output(command).data(result, (value) => `Created lobe ${value.lobeKey}.`);
1260
+ });
1261
+ lobe.command("list").description("List memory lobes, oldest first, a page at a time").option("--limit <count>", "Lobes per page, from 1 to 50").option("--cursor <json>", "Continue from a previous page's nextCursor").action(async (options, command) => {
1262
+ const result = await context.client(command).listLobesPage({
1263
+ cursor: parseCursorJson$1(lobesCursorSchema, options.cursor, "{\"createdAt\":\"…\",\"lobeKey\":\"…\"}"),
1264
+ limit: parseIntegerOption(options.limit, "--limit", {
1265
+ maximum: 50,
1266
+ minimum: 1
1267
+ })
1268
+ });
1269
+ context.output(command).data(result, (page) => [
1270
+ ...page.lobes.length === 0 ? ["No lobes found."] : [],
1271
+ ...page.lobes.map(describeLobe),
1272
+ ...renderMoreCursor(page.nextCursor)
1273
+ ].join("\n"));
1274
+ });
1275
+ lobe.command("update").description("Set a lobe's purpose or whether the owner's agent reads it").argument("<key>", "Lobe key").option("--purpose <text>", "What this lobe is for").option("--clear-purpose", "Remove the lobe's purpose").option("--owner-recall <on|off>", "Whether the owner's agent reads it").action(async (key, options, command) => {
1276
+ if (options.purpose !== void 0 && options.clearPurpose === true) throw new MerraiCliUsageError("Use --purpose or --clear-purpose, not both");
1277
+ const input = { lobeKey: key };
1278
+ const ownerRecall = parseOwnerRecall(options.ownerRecall);
1279
+ if (ownerRecall !== void 0) input.ownerRecall = ownerRecall;
1280
+ if (options.purpose !== void 0) input.purpose = options.purpose;
1281
+ if (options.clearPurpose === true) input.purpose = null;
1282
+ if (input.ownerRecall === void 0 && input.purpose === void 0) throw new MerraiCliUsageError("Give --purpose, --clear-purpose or --owner-recall");
1283
+ const result = await context.client(command).updateLobe(input);
1284
+ context.output(command).data(result, describeLobe);
1285
+ });
1286
+ };
1287
+ // src/commands/memory.ts
1288
+ /** How often and for how long `memory clear` follows a clear it started. */
1289
+ const CLEAR_POLL_INTERVAL_MS = 1e3;
1290
+ const CLEAR_WAIT_LIMIT_MS = 6e5;
1291
+ const defaultSleep = async (milliseconds) => new Promise((resolve) => {
1292
+ setTimeout(resolve, milliseconds);
1293
+ });
1294
+ const renderClearStatus = (status) => {
1295
+ const counts = `${status.deleted} memories and ${status.deletedSources} sources deleted`;
1296
+ switch (status.status) {
1297
+ case "complete": return `Cleared lobe ${status.lobeKey}: ${counts}.`;
1298
+ case "running": return `Clearing lobe ${status.lobeKey} continues in the background (${counts}, ${status.remainingSources} sources left). Follow it with: merrai memory clear-status ${status.clearId}`;
1299
+ case "failed": return `Clearing lobe ${status.lobeKey} stopped (${counts}, ${status.remainingSources} sources left). Run the clear again to finish it.`;
1300
+ default: return status.status;
1301
+ }
1302
+ };
1303
+ /**
1304
+ * Follows a clear until it leaves `running` or the wait limit passes,
1305
+ * reporting progress on stderr whenever it changes.
1306
+ */
1307
+ const followClear = async (context, command, started) => {
1308
+ const sleep = context.runtime.sleep ?? defaultSleep;
1309
+ const client = context.client(command);
1310
+ const output = context.output(command);
1311
+ let status = started;
1312
+ let lastProgress = "";
1313
+ for (let waited = 0; status.status === "running" && waited < CLEAR_WAIT_LIMIT_MS; waited += CLEAR_POLL_INTERVAL_MS) {
1314
+ const progress = `Clearing lobe ${status.lobeKey}: ${status.deletedSources} sources and ${status.deleted} memories deleted, ${status.remainingSources} sources left.`;
1315
+ if (progress !== lastProgress) {
1316
+ output.diagnostic(progress);
1317
+ lastProgress = progress;
1318
+ }
1319
+ await sleep(CLEAR_POLL_INTERVAL_MS);
1320
+ status = await client.clearLobeStatus({ clearId: status.clearId });
1321
+ }
1322
+ return status;
1323
+ };
1324
+ /** A clear that stopped is a server-side failure: report it and exit non-zero. */
1325
+ const finishClear = (context, command, status) => {
1326
+ context.output(command).data(status, renderClearStatus);
1327
+ if (status.status === "failed") throw new Error(renderClearStatus(status));
1328
+ };
1329
+ const renderRecordedDate = (recordedAt) => recordedAt === null ? "undated" : recordedAt.slice(0, 10);
1330
+ /**
1331
+ * "- [category] 2026-07-17: text", "(inferred)" after a guess, then what it
1332
+ * replaced and its update marks ("↳ updated by: …", "replaces: …") indented under it.
1333
+ */
1334
+ const renderMemoryLines = (memories, emptyText = "No memories found.") => {
1335
+ if (memories.length === 0) return emptyText;
1336
+ return searchResultLines(memories, (memory) => {
1337
+ const category = memory.category === null ? "" : `[${memory.category}] `;
1338
+ const inferred = memory.inferred === true ? " (inferred)" : "";
1339
+ return `- ${category}${renderRecordedDate(memory.recordedAt)}: ${memory.content}${inferred}`;
1340
+ }).map((lines) => lines.join("\n ")).join("\n");
1341
+ };
1342
+ const renderProfileMemorySection = (title, memories, renderMemory) => memories.length === 0 ? [] : [`${title}:`, ...memories.map((memory) => `- ${renderMemory(memory)}`)];
1343
+ const renderProfileDetails = (profile) => [
1344
+ `Scope: ${profile.scope}`,
1345
+ ...renderProfileMemorySection("Facts", profile.facts, (memory) => memory.content),
1346
+ ...renderProfileMemorySection("Ongoing context", profile.ongoingContext, (memory) => memory.content),
1347
+ ...renderProfileMemorySection("Dynamic context", profile.dynamicContext, (memory) => `${memory.content} (expires ${memory.profileExpiresAt})`)
1348
+ ];
1349
+ const renderProfileRefresh = (refresh) => {
1350
+ if (refresh.status === "queued") return `Profile refresh queued (${refresh.candidateMemoryCount} pending).`;
1351
+ if (refresh.status === "failed") return "Profile refresh could not be scheduled; retry shortly.";
1352
+ return null;
1353
+ };
1354
+ const renderProfile = (overview) => {
1355
+ const lines = [`# ${overview.account.name}`];
1356
+ if (overview.account.primaryRole !== null) lines.push(`Role: ${overview.account.primaryRole}`);
1357
+ if (overview.account.workplace !== null) lines.push(`Workplace: ${overview.account.workplace}`);
1358
+ if (overview.profile !== null) lines.push(...renderProfileDetails(overview.profile));
1359
+ const refreshLine = renderProfileRefresh(overview.refresh);
1360
+ if (refreshLine !== null) lines.push(refreshLine);
1361
+ return lines.join("\n");
1362
+ };
1363
+ const renderUndatedExclusion = (count) => count === 0 ? [] : [`${count} undated ${count === 1 ? "memory was" : "memories were"} excluded by the date range.`];
1364
+ /** A search_memories reply: its memories, then any undated ones a date range excluded. */
1365
+ const renderSearchReply = (result, emptyText) => [renderMemoryLines(result.memories, emptyText), ...renderUndatedExclusion(result.undatedExcludedCount)].join("\n");
1366
+ const memoriesCursorSchema = z.object({
1367
+ createdAt: z.string().min(1),
1368
+ id: z.string().min(1)
1369
+ });
1370
+ const parseMemoriesCursorJson = (value) => {
1371
+ try {
1372
+ return memoriesCursorSchema.safeParse(JSON.parse(value));
1373
+ } catch {
1374
+ return null;
1375
+ }
1376
+ };
1377
+ /** Accepts the `nextCursor` JSON a previous `memory list` printed. */
1378
+ const parseMemoriesCursor = (value) => {
1379
+ if (value === void 0) return void 0;
1380
+ const parsed = parseMemoriesCursorJson(value);
1381
+ if (parsed?.success !== true) throw new MerraiCliUsageError("cursor must be the nextCursor JSON from a previous list, for example {\"createdAt\":\"…\",\"id\":\"…\"}");
1382
+ return parsed.data;
1383
+ };
1384
+ /** A page of current memories in Search's lines, then how to continue. */
1385
+ const renderMemoryList = (page) => {
1386
+ const lines = [renderMemoryLines(page.items, "No memories found.")];
1387
+ if (page.nextCursor !== null) lines.push(`More: --cursor '${JSON.stringify(page.nextCursor)}'`);
1388
+ return lines.join("\n");
1389
+ };
1390
+ const aboutSchema = z.enum([
1391
+ "owner",
1392
+ "other",
1393
+ "none"
1394
+ ]);
1395
+ const stanceSchema = z.enum([
1396
+ "reported",
1397
+ "view",
1398
+ "decision",
1399
+ "inferred"
1400
+ ]);
1401
+ const judgmentStanceSchema = z.enum(["view", "decision"]);
1402
+ const parseChoice = (schema, value, name, values) => {
1403
+ const parsed = schema.safeParse(value);
1404
+ if (!parsed.success) throw new MerraiCliUsageError(`${name} must be one of: ${values.join(", ")}`);
1405
+ return parsed.data;
1406
+ };
1407
+ const openItemsCursorSchema = z.object({
1408
+ asOf: z.string().min(1),
1409
+ id: z.string().min(1),
1410
+ startsOn: z.string().min(1)
1411
+ });
1412
+ const judgmentsCursorSchema = z.object({
1413
+ createdAt: z.string().min(1),
1414
+ id: z.string().min(1)
1415
+ });
1416
+ /** "- 2026-11-10 (planned): text", earliest first. */
1417
+ const renderOpenItems = (result) => [
1418
+ result.items.length === 0 ? `Nothing coming up from ${result.asOf}.` : `Coming up from ${result.asOf}:`,
1419
+ ...result.items.map((item) => `- ${item.startsOn}${item.role === null ? "" : ` (${item.role})`}: ${item.content}`),
1420
+ ...renderMoreCursor(result.nextCursor)
1421
+ ].join("\n");
1422
+ /** Each view or decision, then the facts it rests on or weighs against. */
1423
+ const renderJudgments = (result) => [
1424
+ ...result.items.length === 0 ? ["No views or decisions found."] : [],
1425
+ ...result.items.map((item) => [`- ${item.stance}${item.holder === null ? "" : ` (${item.holder})`}${item.reviewState === null ? "" : " [evidence changed]"}: ${item.content}`, ...item.basis.map((fact) => ` ${fact.link === "rests_on" ? "rests on" : "weighs against"}${fact.current ? "" : " (no longer current)"}: ${fact.content}`)].join("\n")),
1426
+ ...renderMoreCursor(result.nextCursor)
1427
+ ].join("\n");
1428
+ /** The summary, each line with the exemplars it cites, then the exemplars. */
1429
+ const renderStyle = (result) => result.style === null ? `No style profile for ${result.lobeKey} yet.` : [
1430
+ `How you write in ${result.lobeKey} (from ${result.style.sampleSize} of your own passages):`,
1431
+ ...result.style.summary.map((claim) => `- ${claim.aspect}: ${claim.text} [${claim.exemplarIds.join(", ")}]`),
1432
+ "",
1433
+ "Exemplars:",
1434
+ ...result.style.exemplars.flatMap((exemplar) => [
1435
+ `[${exemplar.id}]`,
1436
+ exemplar.text,
1437
+ ""
1438
+ ])
1439
+ ].join("\n").trimEnd();
1440
+ /** `memory by-date` keeps its earlier default of 20 within the shared maximum of 25. */
1441
+ const BY_DATE_DEFAULT_LIMIT = 20;
1442
+ const configureAddCommand = (command, context, contract) => {
1443
+ 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").option("--lobe <key>", "Existing lobe to save into (default: main)").option("--lobe-key <key>", "Legacy alias for --lobe");
1444
+ if (contract === "legacy") command.option("--source <source>", "Source identifier");
1445
+ command.action(async (positional, options, actionCommand) => {
1446
+ const memory = await readTextInput({
1447
+ cwd: context.runtime.cwd,
1448
+ file: options.file,
1449
+ option: options.memory,
1450
+ positional,
1451
+ stdin: context.runtime.stdin
1452
+ });
1453
+ const observationDate = parseDateOption(options.observationDate, "--observation-date");
1454
+ const lobeKey = resolveLobeKey(options);
1455
+ const source = contract === "legacy" ? options.source : void 0;
1456
+ const idempotencyKey = deriveMemorySaveIdempotencyKey({
1457
+ lobeKey,
1458
+ memory,
1459
+ now: context.runtime.now?.() ?? /* @__PURE__ */ new Date(),
1460
+ observationDate,
1461
+ source
1462
+ });
1463
+ const client = context.client(actionCommand);
1464
+ const result = contract === "recall" ? await client.recall.addMemory({
1465
+ idempotencyKey,
1466
+ lobeKey,
1467
+ memory,
1468
+ observationDate
1469
+ }) : await client.addMemory({
1470
+ idempotencyKey,
1471
+ lobeKey,
1472
+ memory,
1473
+ observationDate,
1474
+ source
1475
+ });
1476
+ context.output(actionCommand).data(result, (value) => describeQueuedIngestion("Memory", value.ingestionId));
1477
+ });
1478
+ };
1479
+ const configureSearchCommand = (command, context) => {
1480
+ command.argument("[query]", "Search query").option("--query <text>", "Search query").option("--limit <number>", "Maximum results").option("--lobe <key>", "Search one of your lobes instead of the lobes your agent reads").option("--topic <key>", "Only memories with this topic; repeat for any of several", collectOption, []).option("--about <who>", "Only memories about: owner, other or none").option("--stance <stance>", "Only memories with this stance (reported, view, decision or inferred); repeat for any of several", collectOption, []);
1481
+ command.action(async (positional, options, actionCommand) => {
1482
+ const query = (options.query ?? positional)?.trim();
1483
+ const topics = options.topic.length === 0 ? void 0 : options.topic;
1484
+ const about = options.about === void 0 ? void 0 : parseChoice(aboutSchema, options.about, "--about", [
1485
+ "owner",
1486
+ "other",
1487
+ "none"
1488
+ ]);
1489
+ const stance = options.stance.length === 0 ? void 0 : options.stance.map((value) => parseChoice(stanceSchema, value, "--stance", [
1490
+ "reported",
1491
+ "view",
1492
+ "decision",
1493
+ "inferred"
1494
+ ]));
1495
+ if ((query === void 0 || query.length === 0) && topics === void 0 && about === void 0 && stance === void 0) throw new MerraiCliUsageError("Provide a search query, or filter with --topic, --about or --stance");
1496
+ const limit = parseIntegerOption(options.limit, "--limit", {
1497
+ maximum: 25,
1498
+ minimum: 1
1499
+ });
1500
+ const result = await context.client(actionCommand).recall.searchMemories({
1501
+ about,
1502
+ limit,
1503
+ lobeKey: options.lobe,
1504
+ query: query === void 0 || query.length === 0 ? void 0 : query,
1505
+ stance,
1506
+ topics
1507
+ });
1508
+ context.output(actionCommand).data(result, (value) => renderSearchReply(value, "No memories found."));
1509
+ });
1510
+ };
1511
+ const configureDateCommand = (command, context) => {
1512
+ command.option("--start <datetime>", "Inclusive ISO 8601 lower bound").option("--end <datetime>", "Inclusive ISO 8601 upper bound").option("--limit <number>", "Maximum results, 1-25 (default 20)").action(async (options, actionCommand) => {
1513
+ const start = parseDateOption(options.start, "--start");
1514
+ const end = parseDateOption(options.end, "--end");
1515
+ if (start === void 0 && end === void 0) throw new MerraiCliUsageError("Provide at least one of --start or --end");
1516
+ const input = {
1517
+ end,
1518
+ limit: parseIntegerOption(options.limit, "--limit", {
1519
+ maximum: 25,
1520
+ minimum: 1
1521
+ }) ?? BY_DATE_DEFAULT_LIMIT,
1522
+ start
1523
+ };
1524
+ const result = await context.client(actionCommand).recall.searchMemories(input);
1525
+ context.output(actionCommand).data(result, (value) => renderSearchReply(value, "No memories found in the requested date range."));
1526
+ });
1527
+ };
1528
+ const configureStatusCommand = (command, context) => {
1529
+ command.option("--lobe <key>", "Restrict to a lobe").option("--lobe-key <key>", "Legacy alias for --lobe").action(async (options, actionCommand) => {
1530
+ const lobeKey = resolveLobeKey(options);
1531
+ const result = await context.client(actionCommand).memoryStatus({ lobeKey });
1532
+ context.output(actionCommand).data(result, () => lobeKey === void 0 ? `${result.count} memories.` : `${result.count} memories in ${lobeKey}.`);
1533
+ });
1534
+ };
1535
+ const configureClearCommand = (command, context, requireConfirmation) => {
1536
+ command.argument("[lobe]", "Lobe to clear").option("--lobe <key>", "Lobe to clear").option("--lobe-key <key>", "Legacy alias for --lobe").option("--yes", "Skip confirmation").option("--no-wait", "Return once the clear has started instead of following it").action(async (positional, options, actionCommand) => {
1537
+ const lobeKey = resolveLobeKey(options) ?? positional;
1538
+ if (lobeKey === void 0 || lobeKey.trim().length === 0) throw new MerraiCliUsageError("Provide the lobe to clear");
1539
+ if (requireConfirmation && options.yes !== true) {
1540
+ if (!await confirmAction({
1541
+ input: context.runtime.stdin,
1542
+ message: `Clear all memories in lobe '${lobeKey}'?`,
1543
+ output: context.runtime.stderr
1544
+ })) throw new MerraiCliUsageError("Clear cancelled. Use --yes for noninteractive confirmation.");
1545
+ }
1546
+ const started = await context.client(actionCommand).clearLobe({ lobeKey });
1547
+ finishClear(context, actionCommand, options.wait === false ? started : await followClear(context, actionCommand, started));
1548
+ });
1549
+ };
1550
+ const registerMemoryCommands = (program, context) => {
1551
+ const memory = program.command("memory").description("Manage and recall memories");
1552
+ configureAddCommand(memory.command("add").description("Queue a memory"), context, "recall");
1553
+ configureAddCommand(program.command("add-memory", { hidden: true }).description("Legacy memory add"), context, "legacy");
1554
+ configureSearchCommand(memory.command("search").description("Search memories"), context);
1555
+ const configureListCommand = (command) => {
1556
+ command.option("--lobe <key>", "Only memories in this lobe").option("--lobe-key <key>", "Legacy alias for --lobe").option("--limit <count>", "Memories per page, from 1 to 100").option("--cursor <json>", "Continue from a previous page's nextCursor").action(async (options, actionCommand) => {
1557
+ const result = await context.client(actionCommand).memories({
1558
+ cursor: parseMemoriesCursor(options.cursor),
1559
+ limit: parseIntegerOption(options.limit, "--limit", {
1560
+ maximum: 100,
1561
+ minimum: 1
1562
+ }),
1563
+ lobeKey: resolveLobeKey(options)
1564
+ });
1565
+ context.output(actionCommand).data(result, renderMemoryList);
1566
+ });
1567
+ };
1568
+ configureListCommand(memory.command("list").description("List current memories, newest first, one page at a time"));
1569
+ configureListCommand(program.command("memories", { hidden: true }).description("Legacy memory list"));
1570
+ const profileAction = async (command, lobeKey) => {
1571
+ const result = await context.client(command).memoryOverview(lobeKey === void 0 ? void 0 : { lobeKey });
1572
+ context.output(command).data(result, renderProfile);
1573
+ };
1574
+ memory.command("profile").description("Show the account and memory profile").option("--lobe <key>", "Read one lobe's profile instead of the lobes your agent reads").action(async (options, command) => profileAction(command, options.lobe));
1575
+ program.command("who-am-i", { hidden: true }).aliases(["whoami"]).description("Legacy memory profile").action(async (_options, command) => profileAction(command));
1576
+ configureDateCommand(memory.command("by-date").description("Recall memories by date"), context);
1577
+ memory.command("open-items").description("List what is coming up: plans and deadlines still ahead, and decisions not yet carried out, earliest first").option("--lobe <key>", "Read one of your lobes instead of the lobes your agent reads").option("--as-of <day>", "Count from this day, YYYY-MM-DD (default: today here)").option("--until <day>", "Only items starting on or before this day, YYYY-MM-DD").option("--limit <count>", "Items per page, from 1 to 50").option("--cursor <json>", "Continue from a previous page's nextCursor").action(async (options, command) => {
1578
+ const result = await context.client(command).listOpenItems({
1579
+ asOf: parseDayOption(options.asOf, "--as-of") ?? localDay(context.runtime.now?.() ?? /* @__PURE__ */ new Date()),
1580
+ cursor: parseCursorJson$1(openItemsCursorSchema, options.cursor, "{\"asOf\":\"…\",\"id\":\"…\",\"startsOn\":\"…\"}"),
1581
+ limit: parseIntegerOption(options.limit, "--limit", {
1582
+ maximum: 50,
1583
+ minimum: 1
1584
+ }),
1585
+ lobeKey: options.lobe,
1586
+ until: parseDayOption(options.until, "--until")
1587
+ });
1588
+ context.output(command).data(result, renderOpenItems);
1589
+ });
1590
+ memory.command("judgments").description("List current views and decisions, newest first, with the facts each rests on or weighs against").option("--lobe <key>", "Read one of your lobes instead of the lobes your agent reads").option("--stance <stance>", "Only view or only decision").option("--evidence-changed", "Only those whose supporting facts changed after they were formed").option("--limit <count>", "Items per page, from 1 to 50").option("--cursor <json>", "Continue from a previous page's nextCursor").action(async (options, command) => {
1591
+ const result = await context.client(command).listJudgments({
1592
+ cursor: parseCursorJson$1(judgmentsCursorSchema, options.cursor, "{\"createdAt\":\"…\",\"id\":\"…\"}"),
1593
+ limit: parseIntegerOption(options.limit, "--limit", {
1594
+ maximum: 50,
1595
+ minimum: 1
1596
+ }),
1597
+ lobeKey: options.lobe,
1598
+ reviewState: options.evidenceChanged === true ? "evidence_changed" : void 0,
1599
+ stance: options.stance === void 0 ? void 0 : parseChoice(judgmentStanceSchema, options.stance, "--stance", ["view", "decision"])
1600
+ });
1601
+ context.output(command).data(result, renderJudgments);
1602
+ });
1603
+ configureDateCommand(program.command("search-memories-by-date", { hidden: true }).description("Legacy date recall"), context);
1604
+ configureStatusCommand(memory.command("status").description("Count processed memories"), context);
1605
+ configureStatusCommand(program.command("memory-status", { hidden: true }).description("Legacy status"), context);
1606
+ configureClearCommand(memory.command("clear").description("Clear a memory lobe"), context, true);
1607
+ memory.command("clear-status").description("Show the progress of a lobe clear").argument("<clearId>", "Clear id printed when the clear started").action(async (clearId, _options, command) => {
1608
+ finishClear(context, command, await context.client(command).clearLobeStatus({ clearId }));
1609
+ });
1610
+ configureClearCommand(program.command("clear-lobe", { hidden: true }).description("Legacy lobe clear"), context, false);
1611
+ memory.command("style").description("Show how you write: passages in your own words and a summary citing them").option("--lobe <key>", "Read one of your lobes instead of main, where your own chats and notes are kept").action(async (options, command) => {
1612
+ const result = await context.client(command).getStyleProfile(options.lobe === void 0 ? {} : { lobeKey: options.lobe });
1613
+ context.output(command).data(result, renderStyle);
1614
+ });
1615
+ const synthesis = memory.command("synthesis").description("Rebuild the patterns of how you think and the profile of how you write");
1616
+ synthesis.command("start").description("Rebuild every lobe, or one, now; unchanged inputs are not sent to a model again").option("--lobe <key>", "Lobe key; omitted means every lobe").action(async (options, command) => {
1617
+ const result = await context.client(command).startMemorySynthesis(options.lobe === void 0 ? {} : { lobeKey: options.lobe });
1618
+ context.output(command).data(result, renderSynthesis);
1619
+ });
1620
+ synthesis.command("status").description("Show each lobe's patterns and style, or one lobe's").option("--lobe <key>", "Lobe key; omitted means every lobe").action(async (options, command) => {
1621
+ const result = await context.client(command).memorySynthesisStatus(options.lobe === void 0 ? {} : { lobeKey: options.lobe });
1622
+ context.output(command).data(result, renderSynthesis);
1623
+ });
1624
+ const backfill = memory.command("backfill").description("Label stored memories with topics, who they are about and their stance");
1625
+ backfill.command("start").description("Label every lobe, or one; a start while one runs joins it").option("--lobe <key>", "Lobe key; omitted means every lobe").action(async (options, command) => {
1626
+ const result = await context.client(command).startMemoryBackfill(options.lobe === void 0 ? {} : { lobeKey: options.lobe });
1627
+ context.output(command).data(result, renderBackfill);
1628
+ });
1629
+ backfill.command("status").description("Show the backfill's progress for every lobe, or one").option("--lobe <key>", "Lobe key; omitted means every lobe").action(async (options, command) => {
1630
+ const result = await context.client(command).memoryBackfillStatus(options.lobe === void 0 ? {} : { lobeKey: options.lobe });
1631
+ context.output(command).data(result, renderBackfill);
1632
+ });
1633
+ };
1634
+ const renderSynthesis = (result) => {
1635
+ if (result.status === "never") return "No synthesis has run.";
1636
+ return [`Synthesis ${result.status}.`, ...result.lobes.map((lobe) => {
1637
+ const progress = lobe.state === "pending" ? `pending until ${lobe.notBefore}` : `${lobe.state}, ${lobe.patternCount} ${lobe.patternCount === 1 ? "pattern" : "patterns"}, style ${lobe.styleBuiltAt === null ? "not built" : "built"}`;
1638
+ return lobe.lastError === null ? `- ${lobe.lobeKey}: ${progress}` : `- ${lobe.lobeKey}: ${progress} (${lobe.lastError})`;
1639
+ })].join("\n");
1640
+ };
1641
+ const renderBackfill = (result) => {
1642
+ if (result.status === "never") return "No backfill has run.";
1643
+ return [result.lastError === null ? `Backfill ${result.status}.` : `Backfill ${result.status} (${result.lastError}).`, ...result.lobes.map((lobe) => {
1644
+ const progress = lobe.state === "queued" ? "queued" : `${lobe.state}, ${lobe.labelled} of ${lobe.total} labelled`;
1645
+ return lobe.lastError === null ? `- ${lobe.lobeKey}: ${progress}` : `- ${lobe.lobeKey}: ${progress} (${lobe.lastError})`;
1646
+ })].join("\n");
1647
+ };
1648
+ // src/commands/sources.ts
1649
+ const SOURCE_KINDS = [
1650
+ "agent_conversation",
1651
+ "external_chat",
1652
+ "imported_chat",
1653
+ "manual_entry",
1654
+ "memory_source",
1655
+ "upload"
1656
+ ];
1657
+ const SOURCE_STATUSES = [
1658
+ "complete",
1659
+ "deleted",
1660
+ "failed",
1661
+ "partial",
1662
+ "pending",
1663
+ "processing"
1664
+ ];
1665
+ const parseChoices = (values, choices, name) => {
1666
+ if (values === void 0) return void 0;
1667
+ return values.map((value) => {
1668
+ const choice = choices.find((candidate) => candidate === value);
1669
+ if (choice === void 0) throw new MerraiCliUsageError(`${name} must be one of: ${choices.join(", ")}`);
1670
+ return choice;
1671
+ });
1672
+ };
1673
+ const cursorSchema = z.object({
1674
+ createdAt: z.string().min(1),
1675
+ id: z.string().min(1)
1676
+ });
1677
+ const parseCursorJson = (value) => {
1678
+ try {
1679
+ return cursorSchema.safeParse(JSON.parse(value));
1680
+ } catch {
1681
+ return null;
1682
+ }
1683
+ };
1684
+ /** Accepts the `nextCursor` JSON a previous `sources list` printed. */
1685
+ const parseCursor = (value) => {
1686
+ if (value === void 0) return void 0;
1687
+ const parsed = parseCursorJson(value);
1688
+ if (parsed?.success !== true) throw new MerraiCliUsageError("cursor must be the nextCursor JSON from a previous list, for example {\"createdAt\":\"…\",\"id\":\"…\"}");
1689
+ return parsed.data;
1690
+ };
1691
+ const describeKind = (source) => source.sourceProvider === null ? source.sourceKind : `${source.sourceKind}/${source.sourceProvider}`;
1692
+ /**
1693
+ * The list's source segment: its kind, then where it came from when that is
1694
+ * known and says more than the kind or provider already does.
1695
+ */
1696
+ const describeOrigin = (source) => source.origin === null || source.origin === source.sourceKind || source.origin === source.sourceProvider ? describeKind(source) : `${describeKind(source)} from ${source.origin}`;
1697
+ const describeStatus = (source) => source.pausedReason === "quota_exceeded" ? `${source.status} (waiting for memory quota)` : source.status;
1698
+ const renderSourceList = (page) => {
1699
+ const lines = page.items.length === 0 ? ["No sources found."] : page.items.map((source) => `- ${source.title}: ${describeStatus(source)}, ${describeOrigin(source)}, ${source.memoryCount} memories (${source.artifactId})`);
1700
+ if (page.nextCursor !== null) lines.push(`More: --cursor '${JSON.stringify(page.nextCursor)}'`);
1701
+ return lines.join("\n");
1702
+ };
1703
+ const renderSource = (source) => [
1704
+ source.title,
1705
+ `ID: ${source.artifactId}`,
1706
+ `Status: ${describeStatus(source)}`,
1707
+ `Source: ${describeKind(source)}`,
1708
+ ...source.origin === null ? [] : [`From: ${source.origin}`],
1709
+ `Lobe: ${source.lobeKey}`,
1710
+ `Memories: ${source.memoryCount}`,
1711
+ ...source.blockedWindows > 0 ? [`Blocked windows: ${source.blockedWindows} (${source.retryableBlockedWindows} retryable${source.availableActions.includes("retry_blocked_windows") ? ` with \`merrai sources retry ${source.artifactId}\`` : ""})`] : [],
1712
+ `Last activity: ${source.lastActivityAt}`,
1713
+ `Actions: ${source.availableActions.join(", ") || "none"}`
1714
+ ].join("\n");
1715
+ const registerSourceCommands = (program, context) => {
1716
+ const sources = program.command("sources").description("List, inspect, retry, reprocess and delete the sources memories come from");
1717
+ sources.command("list").description("List sources, newest first").option("--kind <kind...>", `Only these kinds: ${SOURCE_KINDS.join(", ")}`).option("--provider <provider...>", "Only these providers, such as granola or claude-code").option("--status <status...>", `Only these states: ${SOURCE_STATUSES.join(", ")}`).option("--lobe <key>", "Only sources in this lobe").option("--lobe-key <key>", "Legacy alias for --lobe").option("--limit <count>", "Sources per page, from 1 to 100").option("--cursor <json>", "Continue from a previous page's nextCursor").action(async (options, command) => {
1718
+ const input = {
1719
+ cursor: parseCursor(options.cursor),
1720
+ limit: parseIntegerOption(options.limit, "limit", {
1721
+ maximum: 100,
1722
+ minimum: 1
1723
+ }),
1724
+ lobeKey: resolveLobeKey(options),
1725
+ providers: options.provider,
1726
+ sourceKinds: parseChoices(options.kind, SOURCE_KINDS, "kind"),
1727
+ statuses: parseChoices(options.status, SOURCE_STATUSES, "status")
1728
+ };
1729
+ const result = await context.client(command).sourceArtifactList(input);
1730
+ context.output(command).data(result, renderSourceList);
1731
+ });
1732
+ sources.command("show").description("Show one source's processing state and actions").argument("<id>", "Source artifact ID").action(async (id, _options, command) => {
1733
+ const result = await context.client(command).sourceArtifactGet({ artifactId: id });
1734
+ context.output(command).data(result, renderSource);
1735
+ });
1736
+ sources.command("retry").description("Extract again the parts a partly processed source could not extract").argument("<id>", "Source artifact ID of a partial source").action(async (id, _options, command) => {
1737
+ const result = await context.client(command).sourceArtifactRetry({ artifactId: id });
1738
+ context.output(command).data(result, (value) => describeQueuedIngestion("Retry", value.ingestionId));
1739
+ });
1740
+ sources.command("reprocess").description("Process a failed source again from the start").argument("<id>", "Source artifact ID of a failed source").action(async (id, _options, command) => {
1741
+ const result = await context.client(command).sourceArtifactReprocess({ artifactId: id });
1742
+ context.output(command).data(result, (value) => describeQueuedIngestion("Reprocess", value.ingestionId));
1743
+ });
1744
+ sources.command("delete").description("Delete a source and the memories that came only from it").argument("<id>", "Source artifact ID").option("--yes", "Skip confirmation").action(async (id, options, command) => {
1745
+ if (options.yes !== true) {
1746
+ if (!await confirmAction({
1747
+ input: context.runtime.stdin,
1748
+ message: `Delete source ${id} and the memories that came only from it?`,
1749
+ output: context.runtime.stderr
1750
+ })) throw new MerraiCliUsageError("Delete cancelled. Use --yes for noninteractive confirmation.");
1751
+ }
1752
+ const result = await context.client(command).sourceArtifactDelete({ artifactId: id });
1753
+ context.output(command).data(result, () => `Deleted source ${id}.`);
1754
+ });
1755
+ };
1756
+ // src/commands/system.ts
1757
+ const renderLabelledJson = (label) => (value) => `${label}\n${JSON.stringify(value, null, 2)}`;
1758
+ const redactAuthSessionToken = (result) => ({
1759
+ session: {
1760
+ createdAt: result.session.createdAt,
1761
+ expiresAt: result.session.expiresAt,
1762
+ id: result.session.id,
1763
+ ipAddress: result.session.ipAddress,
1764
+ updatedAt: result.session.updatedAt,
1765
+ userAgent: result.session.userAgent,
1766
+ userId: result.session.userId
1767
+ },
1768
+ user: result.user
1769
+ });
1770
+ const registerSystemCommands = (program, context) => {
1771
+ program.command("health").description("Check API connectivity").action(async (_options, command) => {
1772
+ const result = await context.client(command).healthCheck();
1773
+ context.output(command).data(result, renderLabelledJson("Merrai is reachable."));
1774
+ });
1775
+ program.command("session").description("Fetch the current session").action(async (_options, command) => {
1776
+ const result = await context.client(command).session();
1777
+ const safeResult = result === null ? null : redactAuthSessionToken(result);
1778
+ context.output(command).data(safeResult, renderLabelledJson("Current session:"));
1779
+ });
1780
+ const account = program.command("account").description("Account information");
1781
+ const usageAction = async (command) => {
1782
+ const result = await context.client(command).usageSummary();
1783
+ context.output(command).data(result, renderLabelledJson("Usage:"));
1784
+ };
1785
+ account.command("usage").description("Fetch the current usage summary").action(async (_options, command) => usageAction(command));
1786
+ program.command("usage-summary", { hidden: true }).description("Legacy alias for account usage").action(async (_options, command) => usageAction(command));
1787
+ };
1788
+ // src/commands/topic.ts
1789
+ const scopeInput = (options) => options.lobe === void 0 ? {} : { lobeKey: options.lobe };
1790
+ const renderCatalogue = (catalogue) => {
1791
+ const scope = catalogue.lobeKey === null ? "every lobe" : `lobe ${catalogue.lobeKey}`;
1792
+ if (catalogue.topics.length === 0) return `No topics for ${scope}.`;
1793
+ return [`Topics for ${scope}:`, ...catalogue.topics.map((topic) => `- ${topic.key} (${topic.origin}): ${topic.description}`)].join("\n");
1794
+ };
1795
+ const registerTopicCommands = (program, context) => {
1796
+ const topic = program.command("topic").description("List and change the topics memories are assigned, for every lobe or one");
1797
+ topic.command("list").description("List the topics for every lobe, or for one lobe").option("--lobe <key>", "Lobe key; omitted means every lobe").action(async (options, command) => {
1798
+ const result = await context.client(command).listTopics(scopeInput(options));
1799
+ context.output(command).data(result, renderCatalogue);
1800
+ });
1801
+ topic.command("set").description("Add a topic, or reword one, for every lobe or one lobe").argument("<key>", "Topic key, such as training").argument("<description>", "What the topic holds").option("--lobe <key>", "Lobe key; omitted means every lobe").action(async (key, description, options, command) => {
1802
+ const result = await context.client(command).setTopic({
1803
+ ...scopeInput(options),
1804
+ description,
1805
+ key
1806
+ });
1807
+ context.output(command).data(result, renderCatalogue);
1808
+ });
1809
+ topic.command("retire").description("Stop assigning a topic, for every lobe or one lobe").argument("<key>", "Topic key").option("--lobe <key>", "Lobe key; omitted means every lobe").action(async (key, options, command) => {
1810
+ const result = await context.client(command).retireTopic({
1811
+ ...scopeInput(options),
1812
+ key
1813
+ });
1814
+ context.output(command).data(result, renderCatalogue);
1815
+ });
1816
+ };
1817
+ // src/output.ts
1818
+ const ensureTrailingNewline = (value) => value.endsWith("\n") ? value : `${value}\n`;
1819
+ const createMerraiCliOutput = (options) => ({
1820
+ data: (value, renderText) => {
1821
+ const stringValue = z.string().safeParse(value);
1822
+ const rendered = options.format === "text" && renderText !== void 0 ? renderText(value) : stringValue.success && options.format === "text" ? stringValue.data : JSON.stringify(value, null, 2);
1823
+ options.stdout.write(ensureTrailingNewline(rendered ?? "null"));
1824
+ },
1825
+ diagnostic: (message) => {
1826
+ options.stderr.write(ensureTrailingNewline(message));
1827
+ },
1828
+ error: (message) => {
1829
+ options.stderr.write(ensureTrailingNewline(message));
1830
+ }
1831
+ });
1832
+ // src/runtime.ts
1833
+ const globalOptions = (command) => command.optsWithGlobals();
1834
+ const clientOptions = (runtime, command) => {
1835
+ const options = globalOptions(command);
1836
+ return resolveMerraiClientOptions(runtime.env, {
1837
+ apiKey: options.apiKey,
1838
+ baseURL: options.baseUrl,
1839
+ cookie: options.cookie
1840
+ });
1841
+ };
1842
+ const createMerraiCommandContext = (runtime) => ({
1843
+ client: (command) => runtime.createClient(clientOptions(runtime, command)),
1844
+ debugProcedure: (command, procedureName) => createMerraiDebugProcedure(clientOptions(runtime, command), procedureName),
1845
+ output: (command) => {
1846
+ const options = globalOptions(command);
1847
+ return createMerraiCliOutput({
1848
+ format: options.json === true ? "json" : options.format ?? "json",
1849
+ stderr: runtime.stderr,
1850
+ stdout: runtime.stdout
1851
+ });
1852
+ },
1853
+ runtime
1854
+ });
1855
+ // src/program.ts
1856
+ const CLI_VERSION = version;
1857
+ const parseFormat = (value) => {
1858
+ if (value !== "json" && value !== "text") throw new InvalidArgumentError("format must be json or text");
1859
+ return value;
1860
+ };
1861
+ const createMerraiProgram = (runtime) => {
1862
+ const program = new Command();
1863
+ const context = createMerraiCommandContext(runtime);
1864
+ 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({
1865
+ writeErr: (value) => runtime.stderr.write(value),
1866
+ writeOut: (value) => runtime.stdout.write(value)
1867
+ });
1868
+ registerSystemCommands(program, context);
1869
+ registerMemoryCommands(program, context);
1870
+ registerEntityCommands(program, context);
1871
+ registerLivingDocumentCommands(program, context);
1872
+ registerLobeCommands(program, context);
1873
+ registerTopicCommands(program, context);
1874
+ registerIngestCommands(program, context);
1875
+ registerSourceCommands(program, context);
1876
+ registerAppCommands(program, context);
1877
+ registerIngestionCommands(program, context);
1878
+ registerDebugCommands(program, context);
1879
+ registerAuthCommands(program, context);
1880
+ return program;
1881
+ };
1882
+ const runMerraiCli = async (runtime) => {
1883
+ const program = createMerraiProgram(runtime);
1884
+ if (runtime.argv.length === 0) {
1885
+ program.outputHelp();
1886
+ return MERRAI_CLI_EXIT_CODES.success;
1887
+ }
1888
+ try {
1889
+ await program.parseAsync([...runtime.argv], { from: "user" });
1890
+ return MERRAI_CLI_EXIT_CODES.success;
1891
+ } catch (error) {
1892
+ const result = classifyMerraiCliError(error);
1893
+ if (result.shouldRender) runtime.stderr.write(result.message.endsWith("\n") ? result.message : `${result.message}\n`);
1894
+ return result.exitCode;
1895
+ }
1896
+ };
1897
+ // src/bin.ts
1898
+ const exitCode = await runMerraiCli({
1899
+ argv: process.argv.slice(2),
1900
+ createClient: createMerraiThrowingClient,
1901
+ cwd: process.cwd(),
1902
+ env: process.env,
1903
+ stderr: process.stderr,
1904
+ stdin: process.stdin,
1905
+ stdout: process.stdout
1906
+ });
1907
+ process.exitCode = exitCode;
1908
+ export {};
1909
+
1910
+ //# sourceMappingURL=bin.mjs.map