@sol-merrai/cli 0.2.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -1,146 +1,42 @@
1
1
  #!/usr/bin/env node
2
- import { ORPCError, createORPCClient } from "@orpc/client";
2
+ import { createORPCClient } from "@orpc/client";
3
3
  import { RPCLink } from "@orpc/client/fetch";
4
4
  import { Command, CommanderError, InvalidArgumentError } from "commander";
5
- import fs from "node:fs";
6
- import os from "node:os";
7
- import path from "node:path";
8
- import fs$1 from "node:fs/promises";
9
- import { createInterface } from "node:readline/promises";
10
-
11
- //#region src/client.ts
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
12
13
  const resolveBaseURL = (baseURL) => {
13
14
  const resolved = baseURL?.trim();
14
- if (!resolved) throw new Error("baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials");
15
+ if (resolved === void 0 || resolved === "") throw new Error("baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials");
15
16
  return resolved.endsWith("/") ? resolved.slice(0, -1) : resolved;
16
17
  };
17
18
  const resolveHeaders = (headers, apiKey, cookie) => {
18
19
  const resolvedHeaders = new Headers(headers);
19
- if (apiKey) resolvedHeaders.set("x-api-key", apiKey);
20
- if (cookie) resolvedHeaders.set("Cookie", cookie);
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);
21
23
  return Object.fromEntries(resolvedHeaders.entries());
22
24
  };
23
- const createRawMerraiClient = (options = {}) => {
24
- return createORPCClient(new RPCLink({
25
- fetch: options.fetch,
26
- headers: () => resolveHeaders(options.headers, options.apiKey, options.cookie),
27
- url: `${resolveBaseURL(options.baseURL)}/rpc`
28
- }));
29
- };
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] });
30
33
  const createMerraiThrowingClient = (options = {}) => createRawMerraiClient(options);
31
-
32
- //#endregion
33
- //#region package.json
34
- var version = "0.2.0";
35
-
36
- //#endregion
37
- //#region src/config.ts
38
- const DEFAULT_MERRAI_BASE_URL = "https://api.merrai.app";
39
- const CREDENTIALS_VERSION = 1;
40
- const trimmed = (value) => {
41
- const result = value?.trim();
42
- return result === void 0 || result.length === 0 ? void 0 : result;
43
- };
44
- const isUnknownRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
45
- const resolveHomeDirectory = (env) => trimmed(env.HOME) ?? trimmed(env.USERPROFILE) ?? os.homedir();
46
- const resolveMerraiConfigPaths = (env) => {
47
- const home = resolveHomeDirectory(env);
48
- const xdgConfigHome = trimmed(env.XDG_CONFIG_HOME);
49
- const windowsAppData = trimmed(env.APPDATA);
50
- const directory = xdgConfigHome ? path.join(xdgConfigHome, "merrai") : process.platform === "win32" && windowsAppData ? path.join(windowsAppData, "Merrai") : path.join(home, ".config", "merrai");
51
- return {
52
- credentials: path.join(directory, "credentials.json"),
53
- directory,
54
- legacyClaudeCredentials: path.join(home, ".merrai-claude-code", "credentials.json")
55
- };
56
- };
57
- const parseCredentials = (raw, options) => {
58
- try {
59
- const value = JSON.parse(raw);
60
- if (!isUnknownRecord(value)) return null;
61
- if (options.requireVersion && value.version !== CREDENTIALS_VERSION) return null;
62
- const apiKey = typeof value.apiKey === "string" ? trimmed(value.apiKey) : void 0;
63
- const baseURL = typeof value.baseURL === "string" ? trimmed(value.baseURL) : void 0;
64
- if (apiKey === void 0) return null;
65
- return {
66
- apiKey,
67
- ...baseURL === void 0 ? {} : { baseURL },
68
- savedAt: typeof value.savedAt === "string" ? value.savedAt : (/* @__PURE__ */ new Date(0)).toISOString(),
69
- version: CREDENTIALS_VERSION
70
- };
71
- } catch {
72
- return null;
73
- }
74
- };
75
- const readCredentialsFile = (file, options) => {
76
- if (!fs.existsSync(file)) return null;
77
- try {
78
- const credentials = parseCredentials(fs.readFileSync(file, "utf8"), { requireVersion: options.requireVersion });
79
- if (credentials === null && options.strict) throw new Error(`Invalid Merrai credentials file at ${file}. Run 'merrai auth set-key' to replace it.`);
80
- return credentials;
81
- } catch (error) {
82
- if (options.strict) throw error;
83
- return null;
84
- }
85
- };
86
- const loadMerraiCredentials = (env, options = {}) => {
87
- const paths = resolveMerraiConfigPaths(env);
88
- return readCredentialsFile(paths.credentials, {
89
- requireVersion: true,
90
- strict: options.strict === true
91
- }) ?? readCredentialsFile(paths.legacyClaudeCredentials, {
92
- requireVersion: false,
93
- strict: options.strict === true
94
- });
95
- };
96
- const saveMerraiCredentials = (env, input) => {
97
- const apiKey = trimmed(input.apiKey);
98
- if (apiKey === void 0) throw new Error("API key cannot be empty");
99
- const paths = resolveMerraiConfigPaths(env);
100
- fs.mkdirSync(paths.directory, {
101
- mode: 448,
102
- recursive: true
103
- });
104
- fs.chmodSync(paths.directory, 448);
105
- const credentials = {
106
- apiKey,
107
- baseURL: trimmed(input.baseURL) ?? DEFAULT_MERRAI_BASE_URL,
108
- savedAt: (/* @__PURE__ */ new Date()).toISOString(),
109
- version: CREDENTIALS_VERSION
110
- };
111
- fs.writeFileSync(paths.credentials, JSON.stringify(credentials, null, 2), { mode: 384 });
112
- fs.chmodSync(paths.credentials, 384);
113
- return credentials;
114
- };
115
- const removeFileIfPresent = (file) => {
116
- try {
117
- fs.unlinkSync(file);
118
- return true;
119
- } catch (error) {
120
- if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
121
- throw error;
122
- }
123
- };
124
- const clearMerraiCredentials = (env, options = {}) => {
125
- const paths = resolveMerraiConfigPaths(env);
126
- const removedShared = removeFileIfPresent(paths.credentials);
127
- const removedLegacy = options.includeLegacy === true ? removeFileIfPresent(paths.legacyClaudeCredentials) : false;
128
- return removedShared || removedLegacy;
129
- };
130
- const resolveMerraiClientOptions = (env, overrides, options = {}) => {
131
- const apiKeyOverride = trimmed(overrides.apiKey) ?? trimmed(env.MERRAI_API_KEY);
132
- const baseURLOverride = trimmed(overrides.baseURL) ?? trimmed(env.MERRAI_BASE_URL);
133
- const credentials = apiKeyOverride !== void 0 && baseURLOverride !== void 0 ? null : loadMerraiCredentials(env, { strict: options.strictCredentials !== false });
134
- return {
135
- apiKey: apiKeyOverride ?? credentials?.apiKey,
136
- baseURL: baseURLOverride ?? credentials?.baseURL ?? DEFAULT_MERRAI_BASE_URL,
137
- cookie: trimmed(overrides.cookie) ?? trimmed(env.MERRAI_COOKIE)
138
- };
139
- };
140
-
141
- //#endregion
142
- //#region src/errors.ts
34
+ // package.json
35
+ var version = "0.10.0";
36
+ // src/errors.ts
143
37
  const MERRAI_CLI_EXIT_CODES = {
38
+ /** An App Artifact handler ran and failed: its own error, not Merrai's. */
39
+ appFailed: 6,
144
40
  auth: 3,
145
41
  network: 10,
146
42
  notFound: 4,
@@ -148,69 +44,218 @@ const MERRAI_CLI_EXIT_CODES = {
148
44
  success: 0,
149
45
  usage: 2
150
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
+ };
151
59
  var MerraiCliUsageError = class extends Error {
152
60
  constructor(message, options) {
153
61
  super(message, options);
154
62
  this.name = "MerraiCliUsageError";
155
63
  }
156
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;
157
96
  const renderJsonError = (message, metadata = {}) => JSON.stringify({ error: {
158
97
  ...metadata,
159
98
  message
160
99
  } }, null, 2);
161
- const renderOrpcError = (error) => renderJsonError(error.message, {
162
- code: error.code,
163
- ...error.data === void 0 ? {} : { data: error.data },
164
- status: error.status
165
- });
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
+ };
166
109
  const classifyMerraiCliError = (error) => {
167
110
  if (error instanceof CommanderError) return {
168
111
  exitCode: error.code === "commander.helpDisplayed" || error.code === "commander.version" ? MERRAI_CLI_EXIT_CODES.success : MERRAI_CLI_EXIT_CODES.usage,
169
112
  message: error.message,
170
113
  shouldRender: false
171
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
+ };
172
120
  if (error instanceof MerraiCliUsageError) return {
173
121
  exitCode: MERRAI_CLI_EXIT_CODES.usage,
174
122
  message: renderJsonError(error.message, { code: "USAGE_ERROR" }),
175
123
  shouldRender: true
176
124
  };
177
- if (error instanceof ORPCError) {
178
- const code = error.code;
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;
179
133
  if (code === "BAD_REQUEST" || code === "UNPROCESSABLE_CONTENT") return {
180
134
  exitCode: MERRAI_CLI_EXIT_CODES.usage,
181
- message: renderOrpcError(error),
135
+ message: renderOrpcError(orpcError.data),
182
136
  shouldRender: true
183
137
  };
184
138
  if (code === "UNAUTHORIZED" || code === "FORBIDDEN") return {
185
139
  exitCode: MERRAI_CLI_EXIT_CODES.auth,
186
- message: renderOrpcError(error),
140
+ message: renderOrpcError(isInvalidApiKeyError(orpcError.data) ? {
141
+ ...orpcError.data,
142
+ message: INVALID_API_KEY_CLI_MESSAGE
143
+ } : orpcError.data),
187
144
  shouldRender: true
188
145
  };
189
146
  if (code === "NOT_FOUND" || code === "CONFLICT") return {
190
147
  exitCode: MERRAI_CLI_EXIT_CODES.notFound,
191
- message: renderOrpcError(error),
148
+ message: renderOrpcError(orpcError.data),
192
149
  shouldRender: true
193
150
  };
194
- if (code === "RATE_LIMITED" || code === "TOO_MANY_REQUESTS" || code === "PAYLOAD_TOO_LARGE" || code === "RESOURCE_EXHAUSTED" || error.status === 429) return {
151
+ if (code === "RATE_LIMITED" || code === "TOO_MANY_REQUESTS" || code === "PAYLOAD_TOO_LARGE" || code === "RESOURCE_EXHAUSTED" || orpcError.data.status === 429) return {
195
152
  exitCode: MERRAI_CLI_EXIT_CODES.rateLimit,
196
- message: renderOrpcError(error),
153
+ message: renderOrpcError(orpcError.data),
197
154
  shouldRender: true
198
155
  };
199
156
  return {
200
157
  exitCode: MERRAI_CLI_EXIT_CODES.network,
201
- message: renderOrpcError(error),
158
+ message: renderOrpcError(orpcError.data),
202
159
  shouldRender: true
203
160
  };
204
161
  }
162
+ const nativeError = z.instanceof(Error).safeParse(error);
163
+ const stringError = z.string().safeParse(error);
205
164
  return {
206
165
  exitCode: MERRAI_CLI_EXIT_CODES.network,
207
- message: renderJsonError(error instanceof Error ? error.message : String(error), { code: "NETWORK_ERROR" }),
166
+ message: renderJsonError(nativeError.success ? nativeError.data.message : stringError.success ? stringError.data : "Unexpected CLI failure", { code: "NETWORK_ERROR" }),
208
167
  shouldRender: true
209
168
  };
210
169
  };
211
-
212
- //#endregion
213
- //#region src/input.ts
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();
214
259
  const readStream = async (stream) => {
215
260
  const chunks = [];
216
261
  for await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
@@ -218,9 +263,9 @@ const readStream = async (stream) => {
218
263
  };
219
264
  const readFileOrStdin = async (options) => {
220
265
  if (options.file === "-") return readStream(options.stdin);
221
- const resolvedPath = path.resolve(options.cwd, options.file);
266
+ const resolvedPath = NodePath.resolve(options.cwd, options.file);
222
267
  try {
223
- return await fs$1.readFile(resolvedPath, "utf8");
268
+ return await NodeFSP.readFile(resolvedPath, "utf8");
224
269
  } catch (error) {
225
270
  throw new MerraiCliUsageError(`Unable to read ${resolvedPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
226
271
  }
@@ -228,13 +273,13 @@ const readFileOrStdin = async (options) => {
228
273
  const readStructuredInput = async (options) => {
229
274
  if (options.file !== void 0 && options.input !== void 0) throw new MerraiCliUsageError("Use only one of --input or --file");
230
275
  if (options.file === void 0 && options.input === void 0) throw new MerraiCliUsageError("Provide --input <json> or --file <path|->");
231
- const source = options.input ?? await readFileOrStdin({
276
+ const source = options.input !== void 0 ? options.input : await readFileOrStdin({
232
277
  cwd: options.cwd,
233
- file: options.file,
278
+ file: options.file ?? "-",
234
279
  stdin: options.stdin
235
280
  });
236
281
  try {
237
- return JSON.parse(source);
282
+ return structuredInputSchema.parse(JSON.parse(source));
238
283
  } catch (error) {
239
284
  throw new MerraiCliUsageError(`Invalid JSON from ${options.file === void 0 ? "--input" : options.file}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
240
285
  }
@@ -252,7 +297,7 @@ const readTextInput = async (options) => {
252
297
  };
253
298
  const confirmAction = async (options) => {
254
299
  if (!("isTTY" in options.input && options.input.isTTY === true)) return false;
255
- const prompt = createInterface({
300
+ const prompt = NodeReadlinePromises.createInterface({
256
301
  input: options.input,
257
302
  output: options.output
258
303
  });
@@ -263,6 +308,19 @@ const confirmAction = async (options) => {
263
308
  prompt.close();
264
309
  }
265
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
+ };
266
324
  const readSecretInput = async (options) => {
267
325
  const input = options.input;
268
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");
@@ -319,14 +377,448 @@ const readSecretInput = async (options) => {
319
377
  input.resume();
320
378
  });
321
379
  };
322
-
323
- //#endregion
324
- //#region src/commands/auth.ts
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
325
813
  const registerAuthCommands = (program, context) => {
326
814
  const auth = program.command("auth").description("Manage CLI credentials");
327
815
  auth.command("set-key").argument("[apiKey]", "Merrai API key").description("Validate and save an API key").action(async (positional, _options, actionCommand) => {
328
816
  const globals = actionCommand.optsWithGlobals();
329
- const apiKey = positional?.trim() || globals.apiKey?.trim() || context.runtime.env.MERRAI_API_KEY?.trim() || await readSecretInput({
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({
330
822
  input: context.runtime.stdin,
331
823
  message: "Merrai API key: ",
332
824
  output: context.runtime.stderr
@@ -372,71 +864,132 @@ const registerAuthCommands = (program, context) => {
372
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.");
373
865
  });
374
866
  };
375
-
376
- //#endregion
377
- //#region src/commands/debug.ts
867
+ // src/commands/debug.ts
378
868
  const configureRpcCommand = (command, context) => {
379
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) => {
380
- const client = context.client(actionCommand);
381
- const procedure = Reflect.get(client, procedureName);
382
- if (typeof procedure !== "function") throw new MerraiCliUsageError(`Unknown procedure: ${procedureName}`);
383
- const result = await procedure(options.input !== void 0 || options.file !== void 0 ? await readStructuredInput({
870
+ const procedure = context.debugProcedure(actionCommand, procedureName);
871
+ const input = options.input !== void 0 || options.file !== void 0 ? await readStructuredInput({
384
872
  cwd: context.runtime.cwd,
385
873
  file: options.file,
386
874
  input: options.input,
387
875
  stdin: context.runtime.stdin
388
- }) : void 0);
876
+ }) : void 0;
877
+ const result = z.json().parse(await procedure(input));
389
878
  context.output(actionCommand).data(result);
390
879
  });
391
880
  };
392
881
  const registerDebugCommands = (program, context) => {
393
- configureRpcCommand(program.command("debug").description("Unstable debugging commands").command("rpc").description("Call a top-level oRPC procedure"), context);
882
+ const debug = program.command("debug").description("Unstable debugging commands");
883
+ configureRpcCommand(debug.command("rpc").description("Call a top-level oRPC procedure"), context);
394
884
  configureRpcCommand(program.command("rpc", { hidden: true }).description("Legacy raw oRPC command"), context);
395
885
  };
396
-
397
- //#endregion
398
- //#region src/commands/shared.ts
399
- const ISO_8601_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
400
- const resolveLobeKey = (options) => options.lobe ?? options.lobeKey;
401
- const parseIntegerOption = (value, name, range) => {
402
- if (value === void 0) return;
403
- const parsed = Number(value);
404
- if (!Number.isInteger(parsed) || parsed < range.minimum || parsed > range.maximum) throw new MerraiCliUsageError(`${name} must be an integer from ${range.minimum} to ${range.maximum}`);
405
- return parsed;
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
+ }
406
906
  };
407
- const parseNumberOption = (value, name, range) => {
408
- if (value === void 0) return;
409
- const parsed = Number(value);
410
- if (!Number.isFinite(parsed) || parsed < range.minimum || parsed > range.maximum) throw new MerraiCliUsageError(`${name} must be a number from ${range.minimum} to ${range.maximum}`);
411
- return parsed;
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;
412
911
  };
413
- const parseDateOption = (value, name) => {
414
- if (value === void 0) return;
415
- if (!ISO_8601_DATETIME_PATTERN.test(value) || Number.isNaN(new Date(value).getTime())) throw new MerraiCliUsageError(`${name} must be a valid ISO 8601 datetime`);
416
- return value;
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)}`;
417
920
  };
418
- const parseEntityType = (value) => {
419
- if (value === void 0) return;
420
- switch (value) {
421
- case "action":
422
- case "document":
423
- case "event":
424
- case "knowledge":
425
- case "person": return value;
426
- default: throw new MerraiCliUsageError("--type must be one of: person, event, action, knowledge, document");
427
- }
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})`;
428
933
  };
429
-
430
- //#endregion
431
- //#region src/commands/entity.ts
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;
432
980
  const renderEntities = (result) => {
433
981
  if (result.entities.length === 0) return "No matching entities found.";
434
- return result.entities.map((entity) => `- ${entity.displayName} (${entity.type}, ${entity.memoryCount} memories) — ${entity.id}`).join("\n");
982
+ return result.entities.map((entity) => `- ${entity.displayName} (${entity.type}, ${entity.memoryCount} memories, ${entity.id})`).join("\n");
435
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
+ */
436
988
  const renderEntityMemories = (result) => {
437
- const heading = `# ${result.entity.displayName} (${result.entity.type})`;
989
+ const [entity] = result.matchedEntities;
990
+ const heading = entity === void 0 ? "# Entity" : `# ${entity.displayName} (${entity.type})`;
438
991
  if (result.memories.length === 0) return `${heading}\nNo linked memories.`;
439
- return `${heading}\n${result.memories.map((memory) => `- ${memory.recordedAt.slice(0, 10)} — ${memory.content}`).join("\n")}`;
992
+ return [heading, ...searchResultLines(result.memories, (memory) => `- ${memory.recordedAt?.slice(0, 10) ?? "undated"}: ${memory.content}`).map((lines) => lines.join("\n "))].join("\n");
440
993
  };
441
994
  const configureFindCommand = (command, context) => {
442
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) => {
@@ -455,17 +1008,17 @@ const configureFindCommand = (command, context) => {
455
1008
  });
456
1009
  };
457
1010
  const configureMemoriesCommand = (command, context) => {
458
- command.argument("[entityId]", "Entity id").option("--entity-id <id>", "Entity id").option("--limit <number>", "Maximum results").action(async (positional, options, actionCommand) => {
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) => {
459
1012
  const entityId = options.entityId ?? positional;
460
1013
  if (entityId === void 0 || entityId.trim().length === 0) throw new MerraiCliUsageError("Provide an entity id");
461
1014
  const input = {
462
1015
  entityId,
463
1016
  limit: parseIntegerOption(options.limit, "--limit", {
464
- maximum: 50,
1017
+ maximum: 25,
465
1018
  minimum: 1
466
- })
1019
+ }) ?? ENTITY_MEMORIES_DEFAULT_LIMIT
467
1020
  };
468
- const result = await context.client(actionCommand).memoriesByEntity(input);
1021
+ const result = await context.client(actionCommand).recall.searchMemories(input);
469
1022
  context.output(actionCommand).data(result, renderEntityMemories);
470
1023
  });
471
1024
  };
@@ -476,21 +1029,103 @@ const registerEntityCommands = (program, context) => {
476
1029
  configureMemoriesCommand(entity.command("memories").description("Recall memories linked to an entity"), context);
477
1030
  configureMemoriesCommand(program.command("search-memories-by-entity", { hidden: true }).description("Legacy entity recall"), context);
478
1031
  };
479
-
480
- //#endregion
481
- //#region src/commands/ingest.ts
482
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
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
+ };
483
1108
  const parseMemoriesInput = (value) => {
484
1109
  if (!Array.isArray(value)) throw new MerraiCliUsageError("Memory ingest input must be a JSON array");
485
- return { memories: value };
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
+ };
486
1115
  };
487
1116
  const parseChatInput = (value) => {
488
- if (!isRecord(value) || !Array.isArray(value.memories)) throw new MerraiCliUsageError("Chat ingest input must be an object containing a memories array");
489
- return value;
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
+ };
490
1122
  };
491
1123
  const parseChatsInput = (value) => {
492
- if (!isRecord(value) || !Array.isArray(value.sessions)) throw new MerraiCliUsageError("Multi-chat ingest input must be an object containing a sessions array");
493
- return value;
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
+ };
494
1129
  };
495
1130
  const configureStructuredCommand = (command, context, parse, submit) => {
496
1131
  command.option("--input <json>", "Inline JSON input").option("--file <path>", "Read JSON from a file, or - for stdin").action(async (options, actionCommand) => {
@@ -500,7 +1135,7 @@ const configureStructuredCommand = (command, context, parse, submit) => {
500
1135
  input: options.input,
501
1136
  stdin: context.runtime.stdin
502
1137
  })));
503
- context.output(actionCommand).data(result, () => "Ingest queued.");
1138
+ context.output(actionCommand).data(result, (value) => describeQueuedIngestion("Ingest", value.ingestionId));
504
1139
  });
505
1140
  };
506
1141
  const registerIngestCommands = (program, context) => {
@@ -515,145 +1150,379 @@ const registerIngestCommands = (program, context) => {
515
1150
  registerChats(ingest.command("chats").description("Ingest multiple chat sessions"));
516
1151
  registerChats(program.command("add-chat-sessions", { hidden: true }).description("Legacy multi-chat ingest"));
517
1152
  };
518
-
519
- //#endregion
520
- //#region src/commands/living-document.ts
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(", ")})` : "";
521
1180
  const renderDocumentList = (value) => {
522
1181
  if (value.documents.length === 0) return "No living documents found.";
523
- return value.documents.map((document) => `- ${document.title} — ${document.id}`).join("\n");
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(", ")}.`;
524
1192
  };
525
1193
  const configureGetCommand = (command, context) => {
526
- command.argument("[documentId]", "Living document id").option("--document-id <id>", "Living document id").action(async (positional, options, actionCommand) => {
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) => {
527
1195
  const documentId = options.documentId ?? positional;
528
1196
  if (documentId === void 0 || documentId.trim().length === 0) throw new MerraiCliUsageError("Provide a living document id");
529
- const result = await context.client(actionCommand).recall.readLivingDocument({ documentId });
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
+ });
530
1208
  context.output(actionCommand).data(result, (value) => JSON.stringify(value, null, 2));
531
1209
  });
532
1210
  };
533
1211
  const registerLivingDocumentCommands = (program, context) => {
534
1212
  const document = program.command("document").description("Read living documents");
535
- const listAction = async (command) => {
536
- const result = await context.client(command).recall.listLivingDocuments();
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
+ });
537
1224
  context.output(command).data(result, renderDocumentList);
538
1225
  };
539
- document.command("list").description("List living documents").action(async (_options, command) => listAction(command));
540
- program.command("list-living-documents", { hidden: true }).description("Legacy living document list").action(async (_options, command) => listAction(command));
541
- configureGetCommand(document.command("get").description("Read a living document and its shares"), context);
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
+ });
542
1237
  configureGetCommand(program.command("read-living-document", { hidden: true }).description("Legacy living document read"), context);
543
1238
  };
544
-
545
- //#endregion
546
- //#region src/commands/memory.ts
547
- const renderSearchHits = (hits) => {
548
- if (hits.length === 0) return "No memories found.";
549
- return hits.map((hit) => {
550
- return `- ${hit.category === null ? "" : `[${hit.category}] `}${hit.memoryDate.slice(0, 10)} — ${hit.content}`;
551
- }).join("\n");
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;
552
1353
  };
553
1354
  const renderProfile = (overview) => {
554
1355
  const lines = [`# ${overview.account.name}`];
555
1356
  if (overview.account.primaryRole !== null) lines.push(`Role: ${overview.account.primaryRole}`);
556
1357
  if (overview.account.workplace !== null) lines.push(`Workplace: ${overview.account.workplace}`);
557
- if (overview.profile !== null) {
558
- lines.push(`Scope: ${overview.profile.scope}`);
559
- for (const fact of overview.profile.facts) lines.push(`- ${fact.content}`);
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;
560
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)}'`);
561
1388
  return lines.join("\n");
562
1389
  };
563
- const renderDateResults = (result) => {
564
- if (result.memories.length === 0) return "No memories found in the requested date range.";
565
- return result.memories.map((memory) => `- ${memory.recordedAt.slice(0, 10)} — ${memory.content}`).join("\n");
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;
566
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;
567
1442
  const configureAddCommand = (command, context, contract) => {
568
- command.argument("[text]", "Memory text").option("--memory <text>", "Memory text").option("--file <path>", "Read memory text from a file, or - for stdin").option("--observation-date <datetime>", "ISO 8601 observation time");
569
- if (contract === "legacy") command.option("--source <source>", "Source identifier").option("--lobe <key>", "Memory lobe").option("--lobe-key <key>", "Legacy alias for --lobe");
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");
570
1445
  command.action(async (positional, options, actionCommand) => {
571
- const recallInput = {
572
- memory: await readTextInput({
573
- cwd: context.runtime.cwd,
574
- file: options.file,
575
- option: options.memory,
576
- positional,
577
- stdin: context.runtime.stdin
578
- }),
579
- observationDate: parseDateOption(options.observationDate, "--observation-date")
580
- };
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
+ });
581
1463
  const client = context.client(actionCommand);
582
- const result = contract === "recall" ? await client.recall.addMemory(recallInput) : await client.addMemory({
583
- ...recallInput,
584
- lobeKey: resolveLobeKey(options),
585
- source: options.source
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
586
1475
  });
587
- context.output(actionCommand).data(result, () => "Memory queued.");
1476
+ context.output(actionCommand).data(result, (value) => describeQueuedIngestion("Memory", value.ingestionId));
588
1477
  });
589
1478
  };
590
- const configureSearchCommand = (command, context, contract) => {
591
- command.argument("[query]", "Search query").option("--query <text>", "Search query").option("--limit <number>", "Maximum results");
592
- if (contract === "legacy") command.option("--lobe <key>", "Restrict to a lobe").option("--lobe-key <key>", "Legacy alias for --lobe").option("--threshold <number>", "Minimum vector similarity").option("--mode <mode>", "fast, adaptive, or reflective", "fast").option("--no-graph", "Disable graph expansion").option("--graph-per-seed <number>", "Maximum neighbors per seed").option("--graph-max <number>", "Maximum graph neighbors");
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, []);
593
1481
  command.action(async (positional, options, actionCommand) => {
594
- const query = options.query ?? positional;
595
- if (query === void 0 || query.trim().length === 0) throw new MerraiCliUsageError("Provide a search query");
596
- const mode = options.mode;
597
- if (contract === "legacy" && mode !== "fast" && mode !== "adaptive" && mode !== "reflective") throw new MerraiCliUsageError("--mode must be one of: fast, adaptive, reflective");
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");
598
1496
  const limit = parseIntegerOption(options.limit, "--limit", {
599
- maximum: contract === "recall" ? 25 : 50,
600
- minimum: 1
601
- });
602
- if (contract === "recall") {
603
- const result = await context.client(actionCommand).recall.searchMemory({
604
- limit,
605
- query
606
- });
607
- context.output(actionCommand).data(result, (value) => renderSearchHits(value.memories.map((memory) => ({
608
- ...memory,
609
- memoryDate: memory.recordedAt,
610
- score: 0,
611
- summary: null
612
- }))));
613
- return;
614
- }
615
- const graphPerSeed = parseIntegerOption(options.graphPerSeed, "--graph-per-seed", {
616
- maximum: 10,
617
- minimum: 0
618
- });
619
- const graphMax = parseIntegerOption(options.graphMax, "--graph-max", {
620
1497
  maximum: 25,
621
- minimum: 0
1498
+ minimum: 1
622
1499
  });
623
- const input = {
624
- graph: options.graph === false || graphPerSeed !== void 0 || graphMax !== void 0 ? {
625
- enabled: options.graph !== false,
626
- maxNeighborsPerSeed: graphPerSeed,
627
- maxTotalNeighbors: graphMax
628
- } : void 0,
1500
+ const result = await context.client(actionCommand).recall.searchMemories({
1501
+ about,
629
1502
  limit,
630
- lobeKey: resolveLobeKey(options),
631
- mode: mode === "fast" || mode === "adaptive" || mode === "reflective" ? mode : void 0,
632
- query,
633
- threshold: parseNumberOption(options.threshold, "--threshold", {
634
- maximum: 1,
635
- minimum: 0
636
- })
637
- };
638
- const result = await context.client(actionCommand).searchMemories(input);
639
- context.output(actionCommand).data(result, renderSearchHits);
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."));
640
1509
  });
641
1510
  };
642
1511
  const configureDateCommand = (command, context) => {
643
- command.option("--start <datetime>", "Inclusive ISO 8601 lower bound").option("--end <datetime>", "Inclusive ISO 8601 upper bound").option("--limit <number>", "Maximum results").action(async (options, actionCommand) => {
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) => {
644
1513
  const start = parseDateOption(options.start, "--start");
645
1514
  const end = parseDateOption(options.end, "--end");
646
1515
  if (start === void 0 && end === void 0) throw new MerraiCliUsageError("Provide at least one of --start or --end");
647
1516
  const input = {
648
1517
  end,
649
1518
  limit: parseIntegerOption(options.limit, "--limit", {
650
- maximum: 50,
1519
+ maximum: 25,
651
1520
  minimum: 1
652
- }),
1521
+ }) ?? BY_DATE_DEFAULT_LIMIT,
653
1522
  start
654
1523
  };
655
- const result = await context.client(actionCommand).memoriesByDate(input);
656
- context.output(actionCommand).data(result, renderDateResults);
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."));
657
1526
  });
658
1527
  };
659
1528
  const configureStatusCommand = (command, context) => {
@@ -664,7 +1533,7 @@ const configureStatusCommand = (command, context) => {
664
1533
  });
665
1534
  };
666
1535
  const configureClearCommand = (command, context, requireConfirmation) => {
667
- command.argument("[lobe]", "Lobe to clear").option("--lobe <key>", "Lobe to clear").option("--lobe-key <key>", "Legacy alias for --lobe").option("--yes", "Skip confirmation").action(async (positional, options, actionCommand) => {
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) => {
668
1537
  const lobeKey = resolveLobeKey(options) ?? positional;
669
1538
  if (lobeKey === void 0 || lobeKey.trim().length === 0) throw new MerraiCliUsageError("Provide the lobe to clear");
670
1539
  if (requireConfirmation && options.yes !== true) {
@@ -674,38 +1543,217 @@ const configureClearCommand = (command, context, requireConfirmation) => {
674
1543
  output: context.runtime.stderr
675
1544
  })) throw new MerraiCliUsageError("Clear cancelled. Use --yes for noninteractive confirmation.");
676
1545
  }
677
- const result = await context.client(actionCommand).clearLobe({ lobeKey });
678
- context.output(actionCommand).data(result, () => `Cleared lobe ${lobeKey}.`);
1546
+ const started = await context.client(actionCommand).clearLobe({ lobeKey });
1547
+ finishClear(context, actionCommand, options.wait === false ? started : await followClear(context, actionCommand, started));
679
1548
  });
680
1549
  };
681
1550
  const registerMemoryCommands = (program, context) => {
682
1551
  const memory = program.command("memory").description("Manage and recall memories");
683
1552
  configureAddCommand(memory.command("add").description("Queue a memory"), context, "recall");
684
1553
  configureAddCommand(program.command("add-memory", { hidden: true }).description("Legacy memory add"), context, "legacy");
685
- configureSearchCommand(memory.command("search").description("Search memories"), context, "recall");
686
- configureSearchCommand(program.command("search", { hidden: true }).description("Legacy memory search"), context, "legacy");
687
- const listAction = async (command) => {
688
- const result = await context.client(command).memories();
689
- context.output(command).data(result);
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
+ });
690
1567
  };
691
- memory.command("list").description("List memories").action(async (_options, command) => listAction(command));
692
- program.command("memories", { hidden: true }).description("Legacy memory list").action(async (_options, command) => listAction(command));
693
- const profileAction = async (command) => {
694
- const result = await context.client(command).memoryOverview();
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 });
695
1572
  context.output(command).data(result, renderProfile);
696
1573
  };
697
- memory.command("profile").description("Show the account and memory profile").action(async (_options, command) => profileAction(command));
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));
698
1575
  program.command("who-am-i", { hidden: true }).aliases(["whoami"]).description("Legacy memory profile").action(async (_options, command) => profileAction(command));
699
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
+ });
700
1603
  configureDateCommand(program.command("search-memories-by-date", { hidden: true }).description("Legacy date recall"), context);
701
1604
  configureStatusCommand(memory.command("status").description("Count processed memories"), context);
702
1605
  configureStatusCommand(program.command("memory-status", { hidden: true }).description("Legacy status"), context);
703
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
+ });
704
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
+ });
705
1633
  };
706
-
707
- //#endregion
708
- //#region src/commands/system.ts
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
709
1757
  const renderLabelledJson = (label) => (value) => `${label}\n${JSON.stringify(value, null, 2)}`;
710
1758
  const redactAuthSessionToken = (result) => ({
711
1759
  session: {
@@ -737,13 +1785,41 @@ const registerSystemCommands = (program, context) => {
737
1785
  account.command("usage").description("Fetch the current usage summary").action(async (_options, command) => usageAction(command));
738
1786
  program.command("usage-summary", { hidden: true }).description("Legacy alias for account usage").action(async (_options, command) => usageAction(command));
739
1787
  };
740
-
741
- //#endregion
742
- //#region src/output.ts
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
743
1818
  const ensureTrailingNewline = (value) => value.endsWith("\n") ? value : `${value}\n`;
744
1819
  const createMerraiCliOutput = (options) => ({
745
1820
  data: (value, renderText) => {
746
- const rendered = options.format === "text" && renderText !== void 0 ? renderText(value) : typeof value === "string" && options.format === "text" ? value : JSON.stringify(value, null, 2);
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);
747
1823
  options.stdout.write(ensureTrailingNewline(rendered ?? "null"));
748
1824
  },
749
1825
  diagnostic: (message) => {
@@ -753,19 +1829,19 @@ const createMerraiCliOutput = (options) => ({
753
1829
  options.stderr.write(ensureTrailingNewline(message));
754
1830
  }
755
1831
  });
756
-
757
- //#endregion
758
- //#region src/runtime.ts
1832
+ // src/runtime.ts
759
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
+ };
760
1842
  const createMerraiCommandContext = (runtime) => ({
761
- client: (command) => {
762
- const options = globalOptions(command);
763
- return runtime.createClient(resolveMerraiClientOptions(runtime.env, {
764
- apiKey: options.apiKey,
765
- baseURL: options.baseUrl,
766
- cookie: options.cookie
767
- }));
768
- },
1843
+ client: (command) => runtime.createClient(clientOptions(runtime, command)),
1844
+ debugProcedure: (command, procedureName) => createMerraiDebugProcedure(clientOptions(runtime, command), procedureName),
769
1845
  output: (command) => {
770
1846
  const options = globalOptions(command);
771
1847
  return createMerraiCliOutput({
@@ -776,9 +1852,7 @@ const createMerraiCommandContext = (runtime) => ({
776
1852
  },
777
1853
  runtime
778
1854
  });
779
-
780
- //#endregion
781
- //#region src/program.ts
1855
+ // src/program.ts
782
1856
  const CLI_VERSION = version;
783
1857
  const parseFormat = (value) => {
784
1858
  if (value !== "json" && value !== "text") throw new InvalidArgumentError("format must be json or text");
@@ -795,7 +1869,12 @@ const createMerraiProgram = (runtime) => {
795
1869
  registerMemoryCommands(program, context);
796
1870
  registerEntityCommands(program, context);
797
1871
  registerLivingDocumentCommands(program, context);
1872
+ registerLobeCommands(program, context);
1873
+ registerTopicCommands(program, context);
798
1874
  registerIngestCommands(program, context);
1875
+ registerSourceCommands(program, context);
1876
+ registerAppCommands(program, context);
1877
+ registerIngestionCommands(program, context);
799
1878
  registerDebugCommands(program, context);
800
1879
  registerAuthCommands(program, context);
801
1880
  return program;
@@ -815,9 +1894,7 @@ const runMerraiCli = async (runtime) => {
815
1894
  return result.exitCode;
816
1895
  }
817
1896
  };
818
-
819
- //#endregion
820
- //#region src/bin.ts
1897
+ // src/bin.ts
821
1898
  const exitCode = await runMerraiCli({
822
1899
  argv: process.argv.slice(2),
823
1900
  createClient: createMerraiThrowingClient,
@@ -828,7 +1905,6 @@ const exitCode = await runMerraiCli({
828
1905
  stdout: process.stdout
829
1906
  });
830
1907
  process.exitCode = exitCode;
1908
+ export {};
831
1909
 
832
- //#endregion
833
- export { };
834
1910
  //# sourceMappingURL=bin.mjs.map