@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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/client.ts","../src/config.ts"],"mappings":";;;KAGY,YAAA,uCACV,KAAA,GAAQ,KAAA,KACL,OAAA,oBAA2B,MAAA;AAAA,KAEpB,oBAAA,uCACV,KAAA,GAAQ,KAAA,KACL,OAAA,CAAQ,MAAA;AAAA,KAED,UAAA;AAAA,KAOA,SAAA,sCAKR,SAAA;EAAA,CACG,GAAA,WAAc,SAAA;AAAA;AAAA,UAEJ,cAAA;EACf,MAAA;EACA,eAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,eAAA;EACf,MAAA;EACA,UAAA;AAAA;AAAA,UAGe,oBAAA;EACf,MAAA;EACA,eAAA;AAAA;AAAA,UAGe,qBAAA;EACf,UAAA;EACA,MAAA;AAAA;AAAA,UAGe,gBAAA;EACf,QAAA;IACE,MAAA;IACA,eAAA;IACA,MAAA;IACA,OAAA;EAAA;AAAA;AAAA,UAIa,iBAAA;EACf,QAAA;IAAY,KAAA;IAAe,QAAA;EAAA;EAC3B,MAAA;EACA,UAAA;AAAA;AAAA,UAGe,uBAAA;EACf,IAAA;EACA,IAAA,GAAO,UAAA;EACP,KAAA;AAAA;AAAA,UAGe,qBAAA;EACf,QAAA;EACA,KAAA;AAAA;AAAA,UAGe,mBAAA;EACf,KAAA;EACA,GAAA;EACA,KAAA;AAAA;AAAA,UAGe,kBAAA;EACf,QAAA;EACA,OAAA;EACA,EAAA;EACA,OAAA;EACA,UAAA;AAAA;AAAA,UAGe,wBAAA;EACf,QAAA;IACE,WAAA;IACA,EAAA;IACA,WAAA;IACA,IAAA;IACA,IAAA,EAAM,UAAA;EAAA;EAER,mBAAA;IACE,SAAA;IACA,IAAA;IACA,IAAA;EAAA;AAAA;AAAA,UAIa,uBAAA;EACf,KAA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,6BAAA;AAAA;AAAA,KAGlB,oBAAA,GACV,uBAAA,CAAwB,uBAAA;EACtB,MAAA,EAAQ,uBAAA,CAAwB,6BAAA;AAAA;AAAA,UAGnB,mBAAA;EACf,OAAA;EACA,MAAA;EACA,MAAA;EACA,KAAA,UAAe,KAAA;EACf,OAAA,GAAU,WAAA;AAAA;AAAA,cAGC,cAAA,GAAkB,OAAA;AAAA,cA8BlB,qBAAA,GAAyB,OAAA,GAAS,mBAAA,KAAwB,aAAA,CAAA,YAAA;AAAA,cAW1D,kBAAA,GAAsB,OAAA,GAAS,mBAAA,KAEqB,YAAA;AAAA,cAEpD,0BAAA,GACX,OAAA,GAAS,mBAAA,KACR,oBAAA;;;cCzpBU,uBAAA;AAAA,cACP,mBAAA;AAAA,KAEM,oBAAA,GAAuB,QAAA,CAAS,MAAA;AAAA,UAE3B,4BAAA;EACf,MAAA;EACA,OAAA;EACA,MAAA;AAAA;AAAA,UAGe,iBAAA;EACf,MAAA;EACA,OAAA;EACA,OAAA;EACA,OAAA,SAAgB,mBAAA;AAAA;AAAA,UAGD,iBAAA;EACf,WAAA;EACA,SAAA;EACA,uBAAA;AAAA;AAAA,cAcW,wBAAA,GACX,GAAA,EAAK,oBAAA,KACJ,iBAAA;AAAA,cAiFU,qBAAA,GACX,GAAA,EAAK,oBAAA,EACL,OAAA;EAAW,MAAA;AAAA,MACV,iBAAA;AAAA,cAcU,qBAAA,GACX,GAAA,EAAK,oBAAA,EACL,KAAA;EAAS,MAAA;EAAgB,OAAA;AAAA,MACxB,iBAAA;AAAA,cAkCU,sBAAA,GACX,GAAA,EAAK,oBAAA,EACL,OAAA;EAAW,aAAA;AAAA;AAAA,cAWA,0BAAA,GACX,GAAA,EAAK,oBAAA,EACL,SAAA,EAAW,4BAAA,EACX,OAAA;EAAW,iBAAA;AAAA,MACV,mBAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/client.ts","../src/errors.ts","../src/memory-replacement.ts","../src/idempotency.ts","../src/config.ts"],"mappings":";;;KAIY,qBAAqB,iBAAiB,oBAAoB,OACpE,eACA,mBACA;KAGU,aAAa,iBAAiB,oBAAoB,WAC5D,qBAAqB,OAAO;KAGlB;KAOA,+CAKR;GACG,cAAc;;UAEJ;EACf;EACA;EACA;EACA;EACA;;UAGe;;EAEf;EACA;;UAGe;EACf;;EAEA;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;EACA;IACE;IACA;IACA;IACA;;;UAIa;EACf;EACA;;UAGe;EACf;EACA,OAAO;EACP;;;;;;;KAQU;KAEA;EAEN;EACA;EACA;EACA,OAAO;;;EAIP;EACA;EACA;EACA;EACA,OAAO;;EAGP;EACA;EACA;EACA;;KAEM,kBACR;EACE;EAAuB,cAAc;;UAE1B;EACf,WAAW;EACX;EACA;EACA;EACA;EACA;;;UAIe;EACf;EACA,WAAW;;;;;;UAOI;;;;;;;EAOf;EACA;EACA;EACA,WAAW;;EAEX;;;UAIe,iCAAiC;;;;;EAKhD,WAAW;;;;;EAKX,SAAS;;EAET;;UAGe;EACf;IACE;IACA;IACA;IACA;IACA,MAAM;;;;;;;;UASO;EACf;EACA;EACA;EACA,aAAa;;EAEb;;EAEA;EACA;EACA;;EAEA;EACA,QAAQ;;EAER,SAAS;;;KAIC;;KAEA;;UAGK;EACf;IACE;IACA;IACA;IACA,YAAY;IACZ;IACA;;IAEA;IACA;IACA,QAAQ;IACR,SAAS;;;EAGX;IACE;IACA;IACA;IACA;IACA,MAAM;;EAER,UAAU;EACV;;EAEA;;UAGe;EACf;IACE;IACA;IACA;IACA;IACA;;EAEF;IACE,iBAAiB,KAAK;MACpB;;IAEF,OAAO,KAAK;IACZ,gBAAgB,KAAK;IACrB;IACA;;EAEF;IACE;IACA;;;UAIa;EACf;;KAGU;;;;;KAMA;EACN;;EACA;EAAkB;;UAEP;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;EAOA;IACE;IACA;IACA;;EAEF,YAAY;EACZ;;;;;;;EAOA;IACE;IACA;IACA;;EAEF;EACA;EACA,QAAQ;EACR;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,OAAO;EACP;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,WAAW;EACX;IACE;IACA;IACA;IACA;;;UAIa;EACf;IACE;MAAkB;MAAmB;;IACrC;;IAEA,YAAY;IACZ;IACA;IACA;;EAEF;IACE;IACA;IACA;;;UAIa;EACf;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf;IACE;MACE;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF;IACA;IACA;;IAEA,YAAY;IACZ;IACA;IACA;;;UAIa;EACf,gBAAgB;EAChB,UAAU;;UAGK;EACf,QAAQ;;UAGO;EACf;;UAGe;EACf;;UAGe;EACf;EACA;IACE;IACA;IACA;;EAEF;EACA;EACA,kBAAkB,eAAe;;UAGlB;EACf;EACA;;UAGe;EACf;EACA;EACA,mBAAmB,eAAe;;;;;;EAMlC;EACA;IACE;;;;;;IAMA,WAAW,eAAe;IAC1B;MACE;MACA;;;;;;MAMA;MACA;MACA;;;;UAKW;EACf;EACA;;UAGe;EACf;;UAGe;EACf;;UAGe;EACf;;;;;;UAOe;EACf;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;;;UAIe;EACf;;;UAIe;;EAEf;EACA;IACE;;IAEA;IACA;IACA;;IAEA;;IAEA;IACA;;EAEF;;;UAIe;EACf;;;UAIe;EACf;IACE;IACA;;IAEA;IACA;IACA;;IAEA;IACA;;EAEF;;;UAIe;;EAEf;EACA;;;UAIe;EACf;EACA;IACE;;IAEA;IACA;MAAa;MAAY;MAA2B;;IACpD;IACA;MACE;MACA;MACA;;;;UAKW;EACf;;UAGe;EACf;;UAGe;EACf,UAAU;;UAGK;EACf;;UAGe;EACf,UAAU;;UAGK;EACf;;UAGe;EACf;;UAGe;EACf;EACA;;EAEA;;EAEA;;EAEA;EACA;;;UAIe;EACf;EACA;;UAGe;EACf,SAAS;;EAET;;;UAIe;EACf;;EAEA;;EAEA;EACA;;UAGe;EACf,OAAO;EACP,YAAY;;UAGG;EACf;EACA;;EAEA;;;UAIe;EACf;;UAGe,4BAA4B;EAC3C;EACA;;UAGe,+BAA+B;EAC9C;;;UAIe;EACf;IACE;IACA;IACA;;EAEF;;;UAIe;;EAEf;EACA;EACA;;;UAIe;EACf;EACA,SAAS;;EAET;EACA;EACA;;;UAIe;EACf;EACA;EACA,WAAW;EACX;EACA;EACA;EACA;EACA,QAAQ;;EAER;EACA;;UAGe;EACf;EACA,OAAO;EACP,YAAY;;;UAIG;EACf;EACA;;UAGe;EACf,SAAS;;EAET;EACA;EACA;EACA;;;UAIe;EACf;IACE;;IAEA;IACA;IACA;;EAEF;EACA,WAAW;EACX;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,OAAO;EACP,YAAY;;;UAIG;EACf,WAAW;EACX;EACA;EACA;EACA;EACA;;EAEA,QAAQ;EACR;EACA;EACA;;EAEA;;EAEA,UAAU;EACV;EACA;;;UAIe;EACf;EACA;;UAGe;EACf,SAAS;;EAET;EACA;;UAGe;EACf,OAAO;EACP,YAAY;;UAGG;EACf;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;KAIQ;KACA;UAMK;EACf;EACA;EACA;EACA,OAAO;EACP;EACA,MAAM;EACN;EACA;;UAGe;EACf;IACE;IACA,MAAM;;IAEN;IACA;;EAEF;IACE;MACE;MACA;MACA;MACA;MACA;MACA;;IAEF;MACE;MACA;MACA;MACA;MACA;;IAEF;MACE;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;;IAEF;MACE;MACA;MACA;MACA;MACA;MACA;;;EAGJ;IACE,sBAAsB;IACtB,WAAW;IACX,iBAAiB;;EAEnB;EACA,MAAM;EACN;IACE;IACA,IAAI;IACJ;IACA;;;UAIa;;;;;EA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wBACR;qBAKU,6BACX,UAAS,wBACR;qBCj6CU;cAGP,0BAAwB,EAAA;;;;;GAI5B,EAAA,KAAA;;;;;qBAMW,uBAEX,mBACC,SAAS,EAAE,aAAa;;;;;qBCjCd,oBAAqB,MAAM;;;;;;;qBAmB3B,0BACX,UAAU;;;;;;;qBA+CC,0BACX,gBAAgB,gCAChB,UAAU;;;;;;qBAkBC,oBACX;EACE;EACA,kBAAkB;EAClB,WAAW;GAGb,kBAAkB,UAClB,aAAa,QAAQ;;KCzIX,iFAMC;YACG,cAAc;;;;;;;;qBAqCjB,uBACX,mBACA;YAAqB,cAAc;;;;;;;;qBAaxB,iCAAkC;EAC7C;EACA;EACA,KAAK;EACL;EACA;;qBC9DW;cACP;KAEM,uBAAuB,SAAS;UAE3B;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA,gBAAgB;;UAGD;EACf;EACA;EACA;;qBAoBW,2BACX,KAAK,yBACJ;qBA4EU,wBACX,KAAK,sBACL;EAAW;MACV;qBAcU,wBACX,KAAK,sBACL;EAAS;EAAgB;MACxB;qBAuCU,yBACX,KAAK,sBACL;EAAW;;qBAWA,6BACX,KAAK,sBACL,WAAW,8BACX;EAAW;MACV"}
package/dist/index.mjs CHANGED
@@ -1,74 +1,226 @@
1
1
  import { createORPCClient, createSafeClient } from "@orpc/client";
2
2
  import { RPCLink } from "@orpc/client/fetch";
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
-
7
- //#region src/client.ts
3
+ import "commander";
4
+ import { z } from "zod";
5
+ import * as NodeCrypto from "node:crypto";
6
+ import * as NodeFS from "node:fs";
7
+ import * as NodeOS from "node:os";
8
+ import * as NodePath from "node:path";
9
+ // src/client.ts
8
10
  const resolveBaseURL = (baseURL) => {
9
11
  const resolved = baseURL?.trim();
10
- if (!resolved) throw new Error("baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials");
12
+ if (resolved === void 0 || resolved === "") throw new Error("baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials");
11
13
  return resolved.endsWith("/") ? resolved.slice(0, -1) : resolved;
12
14
  };
13
15
  const resolveHeaders = (headers, apiKey, cookie) => {
14
16
  const resolvedHeaders = new Headers(headers);
15
- if (apiKey) resolvedHeaders.set("x-api-key", apiKey);
16
- if (cookie) resolvedHeaders.set("Cookie", cookie);
17
+ resolvedHeaders.set("x-merrai-unknown-fields", "strip");
18
+ if (apiKey !== void 0 && apiKey !== "") resolvedHeaders.set("x-api-key", apiKey);
19
+ if (cookie !== void 0 && cookie !== "") resolvedHeaders.set("Cookie", cookie);
17
20
  return Object.fromEntries(resolvedHeaders.entries());
18
21
  };
19
- const createRawMerraiClient = (options = {}) => {
20
- return createORPCClient(new RPCLink({
21
- fetch: options.fetch,
22
- headers: () => resolveHeaders(options.headers, options.apiKey, options.cookie),
23
- url: `${resolveBaseURL(options.baseURL)}/rpc`
24
- }));
22
+ const createMerraiRpcLink = (options) => new RPCLink({
23
+ fetch: options.fetch,
24
+ headers: () => resolveHeaders(options.headers, options.apiKey, options.cookie),
25
+ url: `${resolveBaseURL(options.baseURL)}/rpc`
26
+ });
27
+ const createRawMerraiClient = (options = {}) => createORPCClient(createMerraiRpcLink(options));
28
+ const createMerraiClient = (options = {}) => {
29
+ return createSafeClient(createRawMerraiClient(options));
25
30
  };
26
- const createMerraiClient = (options = {}) => createSafeClient(createRawMerraiClient(options));
27
31
  const createMerraiThrowingClient = (options = {}) => createRawMerraiClient(options);
28
-
29
- //#endregion
30
- //#region src/config.ts
32
+ z.object({
33
+ code: z.string(),
34
+ data: z.unknown().optional(),
35
+ message: z.string(),
36
+ status: z.number()
37
+ });
38
+ 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.";
39
+ const invalidApiKeyErrorSchema = z.object({
40
+ code: z.literal("UNAUTHORIZED"),
41
+ data: z.object({ reason: z.literal("INVALID_API_KEY") })
42
+ });
43
+ /**
44
+ * True when the server refused the request's API key as unknown, malformed,
45
+ * revoked or expired. That key will not work again.
46
+ */
47
+ const isInvalidApiKeyError = (error) => invalidApiKeyErrorSchema.safeParse(error).success;
48
+ z.object({
49
+ code: z.literal("NOT_FOUND"),
50
+ data: z.object({ reason: z.string() })
51
+ });
52
+ // src/memory-replacement.ts
53
+ /**
54
+ * Exhaustive at compile time; a precision this client does not know reads as
55
+ * unknown rather than failing the output.
56
+ */
57
+ const unsupportedPrecision = (_time) => "unknown";
58
+ /**
59
+ * The calendar reading alone: "2024-04-05", "week of 2024-04-01",
60
+ * "2024-04-20 to 2024-04-21".
61
+ */
62
+ const calendarText = (time) => {
63
+ switch (time.precision) {
64
+ case "week": return `week of ${time.value}`;
65
+ case "day":
66
+ case "month":
67
+ case "year": return time.value;
68
+ case "range": return `${time.start} to ${time.end}`;
69
+ case "unknown": return "unknown";
70
+ default: return unsupportedPrecision(time);
71
+ }
72
+ };
73
+ /** A plan's or deadline's role; null for what happened or an unstated role. */
74
+ const forwardRole = (time) => {
75
+ const role = time.precision === "unknown" ? null : time.role;
76
+ return role === "planned" || role === "due" ? role : null;
77
+ };
78
+ /**
79
+ * An event time as the server words it: a plan or a deadline names its role
80
+ * ("due 2024-04-20"); what happened is the calendar reading alone.
81
+ */
82
+ const describeEventTime = (time) => {
83
+ if (time.precision === "multiple") return time.alternatives.map(describeEventTime).join(" or ");
84
+ const role = forwardRole(time);
85
+ return role === null ? calendarText(time) : `${role} ${calendarText(time)}`;
86
+ };
87
+ /** Whether any reading of the time is a plan or a deadline. */
88
+ const hasForwardRole = (time) => (time.precision === "multiple" ? time.alternatives : [time]).some((reading) => forwardRole(reading) !== null);
89
+ /**
90
+ * "replaces: <earlier text> (due 2024-04-20)": the line Merrai's Search and
91
+ * recall evidence show under a Memory that replaced an earlier value (the
92
+ * latest Memory it supersedes), so a terse update keeps its subject and the
93
+ * old value. Null when it replaced none.
94
+ */
95
+ const renderMemoryReplacement = (replaced) => {
96
+ if (replaced === null || replaced === void 0) return null;
97
+ const time = replaced.eventTime === null || replaced.eventTime.precision === "unknown" ? null : describeEventTime(replaced.eventTime);
98
+ return time === null ? `replaces: ${replaced.content}` : `replaces: ${replaced.content} (${time})`;
99
+ };
100
+ const UPDATE_MARK_LABELS = {
101
+ updated_by: "↳ updated by",
102
+ updates: "replaces"
103
+ };
104
+ /**
105
+ * A linked memory as a mark names it: by its id when the reader is shown it
106
+ * too, otherwise its text with when it happened or is planned or due and the
107
+ * day it was said: "Budget is now $4,000. (said 2024-03-16)".
108
+ */
109
+ const linkedMemoryText = (mark, shownIds) => {
110
+ if (shownIds.has(mark.id)) return mark.id;
111
+ const time = mark.eventTime;
112
+ 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);
113
+ return notes.length === 0 ? mark.content : `${mark.content} (${notes.join("; ")})`;
114
+ };
115
+ /**
116
+ * "↳ updated by: …" and "replaces: …": the update marks Merrai's Search shows
117
+ * under a memory, newer values first, one line per relation. A later value
118
+ * never retires the earlier one; both stay current. A relation this client
119
+ * does not know is left out rather than failing the output.
120
+ */
121
+ const renderMemoryUpdateMarks = (marks, shownIds) => ["updated_by", "updates"].flatMap((relation) => {
122
+ const members = (marks ?? []).filter((mark) => mark.relation === relation);
123
+ return members.length === 0 ? [] : [`${UPDATE_MARK_LABELS[relation]}: ${members.map((mark) => linkedMemoryText(mark, shownIds)).join("; ")}`];
124
+ });
125
+ /**
126
+ * Each search result's lines as Merrai's Search shows them: its own line
127
+ * (`renderLine`), labelled with its id when another result's mark names it,
128
+ * then what it replaced and its update marks.
129
+ */
130
+ const searchResultLines = (results, renderLine) => {
131
+ const shownIds = new Set(results.map((result) => result.id));
132
+ const named = new Set(results.flatMap((result) => (result.linked ?? []).flatMap((mark) => shownIds.has(mark.id) ? [mark.id] : [])));
133
+ return results.map((result) => {
134
+ const line = renderLine(result);
135
+ const replaced = renderMemoryReplacement(result.replaces);
136
+ return [
137
+ named.has(result.id) ? `${line} [${result.id}]` : line,
138
+ ...replaced === null ? [] : [replaced],
139
+ ...renderMemoryUpdateMarks(result.linked, shownIds)
140
+ ];
141
+ });
142
+ };
143
+ // src/idempotency.ts
144
+ /** Accepted by every write API's `idempotencyKey`, including `addChatSessions`. */
145
+ const IDEMPOTENCY_KEY_HEX_LENGTH = 48;
146
+ const isKeyMaterialRecord = (value) => value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
147
+ const canonicalJson = (value) => {
148
+ if (value === void 0) return "null";
149
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
150
+ 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(",")}}`;
151
+ return JSON.stringify(value);
152
+ };
153
+ /**
154
+ * A stable idempotency key derived from what one write sends, so a rerun joins
155
+ * the existing ingestion; any change to content, source, lobe or dates changes
156
+ * it. `operation` namespaces keys by API shape. Undefined fields are omitted,
157
+ * so an absent option and an explicit `undefined` produce the same key.
158
+ */
159
+ const deriveIdempotencyKey = (operation, payload) => NodeCrypto.createHash("sha256").update(canonicalJson({
160
+ operation,
161
+ payload,
162
+ version: 1
163
+ })).digest("hex").slice(0, IDEMPOTENCY_KEY_HEX_LENGTH);
164
+ /**
165
+ * The key for saving one memory (CLI `memory add`, the plugin's
166
+ * `/merrai:save`). Without a supplied observation time, the same sentence
167
+ * saved on a later day is a new occurrence ("went running"), not a retry, so
168
+ * the UTC day joins the key; same-day reruns still collapse into one save.
169
+ */
170
+ const deriveMemorySaveIdempotencyKey = (input) => deriveIdempotencyKey("memory-save", {
171
+ lobeKey: input.lobeKey,
172
+ memory: input.memory,
173
+ observationDate: input.observationDate,
174
+ occurrenceDay: input.observationDate === void 0 ? input.now.toISOString().slice(0, 10) : void 0,
175
+ source: input.source
176
+ });
177
+ // src/config.ts
31
178
  const DEFAULT_MERRAI_BASE_URL = "https://api.merrai.app";
32
179
  const CREDENTIALS_VERSION = 1;
33
180
  const trimmed = (value) => {
34
181
  const result = value?.trim();
35
182
  return result === void 0 || result.length === 0 ? void 0 : result;
36
183
  };
37
- const isUnknownRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
38
- const resolveHomeDirectory = (env) => trimmed(env.HOME) ?? trimmed(env.USERPROFILE) ?? os.homedir();
184
+ const credentialsValueSchema = z.object({
185
+ apiKey: z.string().trim().min(1),
186
+ baseURL: z.string().trim().min(1).nullish(),
187
+ savedAt: z.string().optional(),
188
+ version: z.literal(CREDENTIALS_VERSION).optional()
189
+ });
190
+ const systemErrorSchema = z.object({ code: z.string() });
191
+ const resolveHomeDirectory = (env) => trimmed(env.HOME) ?? trimmed(env.USERPROFILE) ?? NodeOS.homedir();
39
192
  const resolveMerraiConfigPaths = (env) => {
40
193
  const home = resolveHomeDirectory(env);
41
194
  const xdgConfigHome = trimmed(env.XDG_CONFIG_HOME);
42
195
  const windowsAppData = trimmed(env.APPDATA);
43
- const directory = xdgConfigHome ? path.join(xdgConfigHome, "merrai") : process.platform === "win32" && windowsAppData ? path.join(windowsAppData, "Merrai") : path.join(home, ".config", "merrai");
196
+ const directory = xdgConfigHome !== void 0 ? NodePath.join(xdgConfigHome, "merrai") : process.platform === "win32" && windowsAppData !== void 0 ? NodePath.join(windowsAppData, "Merrai") : NodePath.join(home, ".config", "merrai");
44
197
  return {
45
- credentials: path.join(directory, "credentials.json"),
198
+ credentials: NodePath.join(directory, "credentials.json"),
46
199
  directory,
47
- legacyClaudeCredentials: path.join(home, ".merrai-claude-code", "credentials.json")
200
+ legacyClaudeCredentials: NodePath.join(home, ".merrai-claude-code", "credentials.json")
48
201
  };
49
202
  };
50
203
  const parseCredentials = (raw, options) => {
51
204
  try {
52
- const value = JSON.parse(raw);
53
- if (!isUnknownRecord(value)) return null;
205
+ const parsed = credentialsValueSchema.safeParse(JSON.parse(raw));
206
+ if (!parsed.success) return null;
207
+ const value = parsed.data;
54
208
  if (options.requireVersion && value.version !== CREDENTIALS_VERSION) return null;
55
- const apiKey = typeof value.apiKey === "string" ? trimmed(value.apiKey) : void 0;
56
- const baseURL = typeof value.baseURL === "string" ? trimmed(value.baseURL) : void 0;
57
- if (apiKey === void 0) return null;
58
- return {
59
- apiKey,
60
- ...baseURL === void 0 ? {} : { baseURL },
61
- savedAt: typeof value.savedAt === "string" ? value.savedAt : (/* @__PURE__ */ new Date(0)).toISOString(),
209
+ const credentials = {
210
+ apiKey: value.apiKey,
211
+ savedAt: value.savedAt ?? (/* @__PURE__ */ new Date(0)).toISOString(),
62
212
  version: CREDENTIALS_VERSION
63
213
  };
214
+ if (value.baseURL !== void 0 && value.baseURL !== null) credentials.baseURL = value.baseURL;
215
+ return credentials;
64
216
  } catch {
65
217
  return null;
66
218
  }
67
219
  };
68
220
  const readCredentialsFile = (file, options) => {
69
- if (!fs.existsSync(file)) return null;
221
+ if (!NodeFS.existsSync(file)) return null;
70
222
  try {
71
- const credentials = parseCredentials(fs.readFileSync(file, "utf8"), { requireVersion: options.requireVersion });
223
+ const credentials = parseCredentials(NodeFS.readFileSync(file, "utf8"), { requireVersion: options.requireVersion });
72
224
  if (credentials === null && options.strict) throw new Error(`Invalid Merrai credentials file at ${file}. Run 'merrai auth set-key' to replace it.`);
73
225
  return credentials;
74
226
  } catch (error) {
@@ -90,27 +242,28 @@ const saveMerraiCredentials = (env, input) => {
90
242
  const apiKey = trimmed(input.apiKey);
91
243
  if (apiKey === void 0) throw new Error("API key cannot be empty");
92
244
  const paths = resolveMerraiConfigPaths(env);
93
- fs.mkdirSync(paths.directory, {
245
+ NodeFS.mkdirSync(paths.directory, {
94
246
  mode: 448,
95
247
  recursive: true
96
248
  });
97
- fs.chmodSync(paths.directory, 448);
249
+ NodeFS.chmodSync(paths.directory, 448);
98
250
  const credentials = {
99
251
  apiKey,
100
- baseURL: trimmed(input.baseURL) ?? DEFAULT_MERRAI_BASE_URL,
252
+ baseURL: trimmed(input.baseURL) ?? "https://api.merrai.app",
101
253
  savedAt: (/* @__PURE__ */ new Date()).toISOString(),
102
254
  version: CREDENTIALS_VERSION
103
255
  };
104
- fs.writeFileSync(paths.credentials, JSON.stringify(credentials, null, 2), { mode: 384 });
105
- fs.chmodSync(paths.credentials, 384);
256
+ NodeFS.writeFileSync(paths.credentials, JSON.stringify(credentials, null, 2), { mode: 384 });
257
+ NodeFS.chmodSync(paths.credentials, 384);
106
258
  return credentials;
107
259
  };
108
260
  const removeFileIfPresent = (file) => {
109
261
  try {
110
- fs.unlinkSync(file);
262
+ NodeFS.unlinkSync(file);
111
263
  return true;
112
264
  } catch (error) {
113
- if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
265
+ const systemError = systemErrorSchema.safeParse(error);
266
+ if (systemError.success && systemError.data.code === "ENOENT") return false;
114
267
  throw error;
115
268
  }
116
269
  };
@@ -126,11 +279,10 @@ const resolveMerraiClientOptions = (env, overrides, options = {}) => {
126
279
  const credentials = apiKeyOverride !== void 0 && baseURLOverride !== void 0 ? null : loadMerraiCredentials(env, { strict: options.strictCredentials !== false });
127
280
  return {
128
281
  apiKey: apiKeyOverride ?? credentials?.apiKey,
129
- baseURL: baseURLOverride ?? credentials?.baseURL ?? DEFAULT_MERRAI_BASE_URL,
282
+ baseURL: baseURLOverride ?? credentials?.baseURL ?? "https://api.merrai.app",
130
283
  cookie: trimmed(overrides.cookie) ?? trimmed(env.MERRAI_COOKIE)
131
284
  };
132
285
  };
286
+ export { DEFAULT_MERRAI_BASE_URL, INVALID_API_KEY_CLI_MESSAGE, clearMerraiCredentials, createMerraiClient, createMerraiThrowingClient, createRawMerraiClient, deriveIdempotencyKey, deriveMemorySaveIdempotencyKey, describeEventTime, isInvalidApiKeyError, loadMerraiCredentials, renderMemoryReplacement, renderMemoryUpdateMarks, resolveBaseURL, resolveMerraiClientOptions, resolveMerraiConfigPaths, saveMerraiCredentials, searchResultLines };
133
287
 
134
- //#endregion
135
- export { DEFAULT_MERRAI_BASE_URL, clearMerraiCredentials, createMerraiClient, createMerraiThrowingClient, createRawMerraiClient, loadMerraiCredentials, resolveBaseURL, resolveMerraiClientOptions, resolveMerraiConfigPaths, saveMerraiCredentials };
136
288
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/client.ts","../src/config.ts"],"sourcesContent":["import { createORPCClient, createSafeClient } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\n\nexport type RpcProcedure<Input = unknown, Output = unknown> = (\n input?: Input\n) => Promise<readonly [unknown, Output, ...unknown[]]>;\n\nexport type ThrowingRpcProcedure<Input = unknown, Output = unknown> = (\n input?: Input\n) => Promise<Output>;\n\nexport type EntityType =\n | \"person\"\n | \"event\"\n | \"action\"\n | \"knowledge\"\n | \"document\";\n\nexport type JsonValue =\n | boolean\n | number\n | string\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport interface AddMemoryInput {\n memory: string;\n observationDate?: string;\n source?: string;\n lobeKey?: string;\n}\n\nexport interface AddMemoryOutput {\n queued: boolean;\n workflowId: string;\n}\n\nexport interface AddMemoryRecallInput {\n memory: string;\n observationDate?: string;\n}\n\nexport interface AddMemoryRecallOutput {\n processing: true;\n status: \"enqueued\";\n}\n\nexport interface AddMemoriesInput {\n memories: {\n memory: string;\n observationDate?: string;\n source?: string;\n lobeKey?: string;\n }[];\n}\n\nexport interface AddMemoriesOutput {\n failures: { error: string; groupKey: string | null }[];\n queued: number;\n workflowId: string;\n}\n\nexport interface FindMemoryEntitiesInput {\n name: string;\n type?: EntityType;\n limit?: number;\n}\n\nexport interface MemoriesByEntityInput {\n entityId: string;\n limit?: number;\n}\n\nexport interface MemoriesByDateInput {\n start?: string;\n end?: string;\n limit?: number;\n}\n\nexport interface MemoryRecallResult {\n category: string | null;\n content: string;\n id: string;\n lobeKey: string;\n recordedAt: string;\n}\n\nexport interface FindMemoryEntitiesOutput {\n entities: {\n displayName: string;\n id: string;\n memoryCount: number;\n name: string;\n type: EntityType;\n }[];\n suggestedNextAction: {\n entityIds: string[];\n tool: \"search_memories_by_entity\";\n when: string;\n } | null;\n}\n\nexport interface SearchMemoryRecallInput {\n limit?: number;\n query: string;\n}\n\nexport interface SearchMemoryRecallOutput {\n memories: MemoryRecallResult[];\n suggestedNextAction: {\n consentRequired: true;\n tool: \"add_memory\";\n when: string;\n } | null;\n}\n\nexport interface MemoriesByEntityOutput {\n entity: {\n displayName: string;\n id: string;\n type: EntityType;\n };\n memories: MemoryRecallResult[];\n}\n\nexport interface MemoriesByDateOutput {\n memories: MemoryRecallResult[];\n range: {\n end: string | null;\n start: string | null;\n };\n}\n\nexport interface MemoryOverviewOutput {\n account: {\n name: string;\n numberOfAiTools: number | null;\n preferredMessagingChannel: string | null;\n primaryRole: string | null;\n workplace: string | null;\n };\n profile: {\n facts: Omit<MemoryRecallResult, \"id\">[];\n ongoingContext: Omit<MemoryRecallResult, \"id\">[];\n scope: string;\n suggestions: {\n expiresAt: string | null;\n text: string;\n }[];\n updatedAt: string;\n } | null;\n suggestedNextAction: {\n tool: \"search_memory\";\n when: string;\n };\n}\n\nexport interface ListLivingDocumentsInput {\n status?: (\"enabled\" | \"disabled\" | \"archived\")[];\n}\n\nexport type LivingDocumentStatus = \"enabled\" | \"disabled\" | \"archived\";\n\nexport interface LivingDocument {\n autoPublish: boolean;\n createdAt: string;\n currentApprovedVersionId: string | null;\n currentVersionId: string | null;\n description: string | null;\n entities: string[];\n extractionPrompt: string;\n id: string;\n patchFailureCount: number;\n routingSummary: string | null;\n routingSummaryDirty: boolean;\n status: LivingDocumentStatus;\n title: string;\n triggerKeywords: string[];\n updatedAt: string;\n}\n\nexport interface LivingDocumentVersion {\n causedByMemoryIds: string[];\n causedByRunId: string | null;\n contentMd: string;\n contentMdSummary: string | null;\n createdAt: string;\n documentId: string;\n extractorModel: string | null;\n id: string;\n parentVersionId: string | null;\n patch: JsonValue;\n updatedAt: string;\n versionNumber: number;\n}\n\nexport interface LivingDocumentShare {\n createdAt: string;\n documentId: string;\n expiresAt: string | null;\n id: string;\n mode: \"pinned\" | \"live\";\n permissions: \"view\" | \"view+comment\";\n revokedAt: string | null;\n shareToken: string;\n updatedAt: string;\n versionId: string | null;\n}\n\nexport interface ListLivingDocumentsOutput {\n documents: LivingDocument[];\n slots: {\n limit: number;\n plan: string;\n remaining: number;\n used: number;\n };\n}\n\nexport interface ListLivingDocumentsRecallOutput {\n documents: {\n autoPublish: boolean;\n currentVersion: { createdAt: string; number: number } | null;\n id: string;\n status: string;\n summary: string;\n title: string;\n }[];\n}\n\nexport interface ReadLivingDocumentRecallInput {\n documentId: string;\n}\n\nexport interface ReadLivingDocumentRecallOutput {\n document: {\n activeShares: {\n expiresAt: string | null;\n mode: string;\n permissions: string;\n url: string;\n versionId: string | null;\n }[];\n autoPublish: boolean;\n currentVersion: {\n contentMarkdown: string;\n createdAt: string;\n id: string;\n number: number;\n } | null;\n description: string | null;\n entities: string[];\n headings: string[];\n id: string;\n status: string;\n summary: string;\n title: string;\n triggerKeywords: string[];\n };\n}\n\nexport interface GetLivingDocumentOutput {\n currentVersion: LivingDocumentVersion | null;\n document: LivingDocument;\n}\n\nexport interface ListLivingDocumentSharesOutput {\n shares: LivingDocumentShare[];\n}\n\nexport interface GetLivingDocumentInput {\n id: string;\n}\n\nexport interface ListLivingDocumentSharesInput {\n documentId: string;\n}\n\nexport interface AddChatSessionInput {\n memories: {\n memory: string;\n source?: string;\n }[];\n lobeKey?: string;\n source?: string;\n sessionMetadata?: Record<string, unknown>;\n}\n\nexport interface AddChatSessionOutput {\n queued: number;\n workflowId: string;\n}\n\nexport interface AddChatSessionsInput {\n lobeKey?: string;\n source?: string;\n questionMetadata?: Record<string, unknown>;\n /**\n * Override the V3 extractor's prompt profile.\n * - `general` — default chat-ingest extraction.\n * - `agent` — agent-scoped ingests (no user, only agent_id).\n * - `code-personal` — coding-session bias (developer intent over\n * assistant scaffolding, code-specific entities).\n * When omitted, the server resolves a profile from `source`\n * (e.g. `claude-code` → `code-personal`); use this only to override\n * that mapping or for sources the server hasn't pre-mapped.\n */\n extractionProfile?: \"general\" | \"agent\" | \"code-personal\";\n /**\n * Optional idempotency key (1-64 chars, [A-Za-z0-9_-]). When supplied,\n * retries with the same key short-circuit on the server instead of\n * re-running the ingest pipeline. Derive deterministically from\n * (sessionId, turnRange) so retries collide but distinct flushes do not.\n */\n idempotencyKey?: string;\n sessions: {\n sessionId: string;\n metadata?: Record<string, unknown>;\n turns: {\n content: string;\n role: \"user\" | \"assistant\";\n speaker?: string;\n turnIndex: number;\n }[];\n }[];\n}\n\nexport interface AddChatSessionsOutput {\n queuedSessions: number;\n workflowId: string;\n}\n\nexport interface SearchMemoriesInput {\n query: string;\n lobeKey?: string;\n limit?: number;\n threshold?: number;\n mode?: \"fast\" | \"adaptive\" | \"reflective\";\n graph?: {\n enabled?: boolean;\n maxNeighborsPerSeed?: number;\n maxTotalNeighbors?: number;\n };\n}\n\nexport interface SearchMemoryHit {\n category: string | null;\n content: string;\n id: string;\n memoryDate: string;\n score: number;\n summary: string | null;\n}\n\nexport interface MemoryStatusInput {\n lobeKey?: string;\n}\n\nexport interface MemoryStatusOutput {\n count: number;\n}\n\nexport interface ClearLobeInput {\n lobeKey: string;\n}\n\nexport interface ClearLobeOutput {\n deleted: number;\n}\n\nexport interface MemoryListItem {\n category: string | null;\n content: string;\n createdAt: string;\n expiresAt: string | null;\n id: string;\n isCurrent: string;\n lobeKey: string;\n memoryAt: string | null;\n memoryKind: string;\n metadata: JsonValue | null;\n summary: string | null;\n supersededByMemoryId: string | null;\n updatedAt: string;\n}\n\nexport interface AuthSessionOutput {\n session: {\n createdAt: string | null;\n expiresAt: string | null;\n id: string;\n ipAddress: string | null;\n token: string;\n updatedAt: string | null;\n userAgent: string | null;\n userId: string;\n };\n user: {\n createdAt: string | null;\n email: string;\n emailVerified: boolean;\n id: string;\n image: string | null;\n name: string;\n onboardingComplete: boolean;\n updatedAt: string | null;\n };\n}\n\nexport type UsagePlan = \"free\" | \"beta\";\nexport type UsageMeter =\n | \"assistant_messages\"\n | \"automation_executions\"\n | \"llm_tokens\"\n | \"memory_processed\";\n\nexport interface UsageMeterSummary {\n allowed: boolean;\n current: number;\n limit: number | null;\n meter: UsageMeter;\n periodKey: string;\n plan: UsagePlan;\n remaining: number | null;\n userId: string;\n}\n\nexport interface UsageSummaryOutput {\n billing: {\n hasPaidPlan: boolean;\n plan: UsagePlan;\n scheduledDowngradeAt: string | null;\n };\n llm: {\n byModel: {\n inputTokens: number;\n model: string;\n outputTokens: number;\n provider: string;\n requests: number;\n totalTokens: number;\n }[];\n bySurface: {\n inputTokens: number;\n outputTokens: number;\n requests: number;\n surface: string;\n totalTokens: number;\n }[];\n recentRequests: {\n cachedInputTokens: number;\n createdAt: string;\n id: string;\n inputTokens: number;\n model: string;\n outputTokens: number;\n provider: string;\n reasoningTokens: number;\n requestId: string | null;\n surface: string;\n totalTokens: number;\n }[];\n totals: {\n cachedInputTokens: number;\n inputTokens: number;\n outputTokens: number;\n reasoningTokens: number;\n requests: number;\n totalTokens: number;\n };\n };\n meters: {\n automationExecutions: UsageMeterSummary;\n llmTokens: UsageMeterSummary;\n memoryProcessed: UsageMeterSummary;\n };\n periodStart: string;\n plan: UsagePlan;\n plans: {\n automations: number | null;\n id: UsagePlan;\n memories: number | null;\n tokens: number | null;\n }[];\n}\n\nexport interface GetSessionStartContextInput {\n /**\n * Restrict to a single lobe. Plugin callers pass `cc:<repo-slug>` so memory\n * is scoped to the active project. Omit to read across every lobe.\n */\n lobeKey?: string;\n /**\n * Short retrieval hints biased toward what the caller is about to do\n * (e.g. current git branch name, last commit subject, cwd basename).\n * Cap: 5 hints × 200 chars.\n */\n recentHints?: string[];\n /**\n * Caller-side budget. Server hard caps both numbers regardless.\n */\n budget?: {\n /** Default 15, hard cap 30. */\n maxMemories?: number;\n /** Default 2000, hard cap 4000. Char-based estimate (chars / 4). */\n maxTokens?: number;\n };\n}\n\nexport interface GetSessionStartContextOutput {\n /** Markdown block ready to drop into a hook's `additionalContext`. */\n markdown: string;\n /** IDs of every memory referenced in the markdown. */\n memoryIds: string[];\n /** True when the response was truncated by the budget. */\n hasMore: boolean;\n /** Server-side ISO 8601 timestamp the context was generated. */\n generatedAt: string;\n}\n\ninterface MerraiProcedureContract {\n addChatSession: {\n input: AddChatSessionInput;\n output: AddChatSessionOutput;\n };\n addChatSessions: {\n input: AddChatSessionsInput;\n output: AddChatSessionsOutput;\n };\n addMemories: { input: AddMemoriesInput; output: AddMemoriesOutput };\n addMemory: { input: AddMemoryInput; output: AddMemoryOutput };\n clearLobe: { input: ClearLobeInput; output: ClearLobeOutput };\n findMemoryEntities: {\n input: FindMemoryEntitiesInput;\n output: FindMemoryEntitiesOutput;\n };\n getLivingDocument: {\n input: GetLivingDocumentInput;\n output: GetLivingDocumentOutput;\n };\n getSessionStartContext: {\n input: GetSessionStartContextInput;\n output: GetSessionStartContextOutput;\n };\n healthCheck: { input: undefined; output: \"OK\" };\n listLivingDocuments: {\n input: ListLivingDocumentsInput;\n output: ListLivingDocumentsOutput;\n };\n listLivingDocumentShares: {\n input: ListLivingDocumentSharesInput;\n output: ListLivingDocumentSharesOutput;\n };\n memories: { input: undefined; output: MemoryListItem[] };\n memoriesByDate: {\n input: MemoriesByDateInput;\n output: MemoriesByDateOutput;\n };\n memoriesByEntity: {\n input: MemoriesByEntityInput;\n output: MemoriesByEntityOutput;\n };\n memoryOverview: { input: undefined; output: MemoryOverviewOutput };\n memoryStatus: { input: MemoryStatusInput; output: MemoryStatusOutput };\n searchMemories: { input: SearchMemoriesInput; output: SearchMemoryHit[] };\n session: { input: undefined; output: AuthSessionOutput | null };\n usageSummary: { input: undefined; output: UsageSummaryOutput };\n}\n\ninterface MerraiRecallProcedureContract {\n addMemory: {\n input: AddMemoryRecallInput;\n output: AddMemoryRecallOutput;\n };\n listLivingDocuments: {\n input: undefined;\n output: ListLivingDocumentsRecallOutput;\n };\n readLivingDocument: {\n input: ReadLivingDocumentRecallInput;\n output: ReadLivingDocumentRecallOutput;\n };\n searchMemory: {\n input: SearchMemoryRecallInput;\n output: SearchMemoryRecallOutput;\n };\n}\n\ntype SafeProcedureClient<Contract> = {\n [ProcedureName in keyof Contract]: Contract[ProcedureName] extends {\n input: infer Input;\n output: infer Output;\n }\n ? RpcProcedure<Input, Output>\n : never;\n};\n\ntype ThrowingProcedureClient<Contract> = {\n [ProcedureName in keyof Contract]: Contract[ProcedureName] extends {\n input: infer Input;\n output: infer Output;\n }\n ? ThrowingRpcProcedure<Input, Output>\n : never;\n};\n\nexport type MerraiClient = SafeProcedureClient<MerraiProcedureContract> & {\n recall: SafeProcedureClient<MerraiRecallProcedureContract>;\n};\n\nexport type MerraiThrowingClient =\n ThrowingProcedureClient<MerraiProcedureContract> & {\n recall: ThrowingProcedureClient<MerraiRecallProcedureContract>;\n };\n\nexport interface MerraiClientOptions {\n baseURL?: string;\n apiKey?: string;\n cookie?: string;\n fetch?: typeof fetch;\n headers?: HeadersInit;\n}\n\nexport const resolveBaseURL = (baseURL?: string) => {\n const resolved = baseURL?.trim();\n\n if (!resolved) {\n throw new Error(\n \"baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials\"\n );\n }\n\n return resolved.endsWith(\"/\") ? resolved.slice(0, -1) : resolved;\n};\n\nconst resolveHeaders = (\n headers?: HeadersInit,\n apiKey?: string,\n cookie?: string\n): Record<string, string> => {\n const resolvedHeaders = new Headers(headers);\n\n if (apiKey) {\n resolvedHeaders.set(\"x-api-key\", apiKey);\n }\n\n if (cookie) {\n resolvedHeaders.set(\"Cookie\", cookie);\n }\n\n return Object.fromEntries(resolvedHeaders.entries());\n};\n\nexport const createRawMerraiClient = (options: MerraiClientOptions = {}) => {\n const link = new RPCLink({\n fetch: options.fetch,\n headers: () =>\n resolveHeaders(options.headers, options.apiKey, options.cookie),\n url: `${resolveBaseURL(options.baseURL)}/rpc`,\n });\n\n return createORPCClient(link);\n};\n\nexport const createMerraiClient = (options: MerraiClientOptions = {}) =>\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Legacy cast requires typed boundary validation.\n createSafeClient(createRawMerraiClient(options)) as unknown as MerraiClient;\n\nexport const createMerraiThrowingClient = (\n options: MerraiClientOptions = {}\n): MerraiThrowingClient =>\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- oRPC is dynamic without the server contract package; keep the cast at this construction seam.\n createRawMerraiClient(options) as unknown as MerraiThrowingClient;\n","import fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nimport type { MerraiClientOptions } from \"./client\";\n\nexport const DEFAULT_MERRAI_BASE_URL = \"https://api.merrai.app\";\nconst CREDENTIALS_VERSION = 1;\n\nexport type MerraiCliEnvironment = Readonly<Record<string, string | undefined>>;\n\nexport interface MerraiCliConnectionOverrides {\n apiKey?: string;\n baseURL?: string;\n cookie?: string;\n}\n\nexport interface MerraiCredentials {\n apiKey: string;\n baseURL?: string;\n savedAt: string;\n version: typeof CREDENTIALS_VERSION;\n}\n\nexport interface MerraiConfigPaths {\n credentials: string;\n directory: string;\n legacyClaudeCredentials: string;\n}\n\nconst trimmed = (value: string | undefined): string | undefined => {\n const result = value?.trim();\n return result === undefined || result.length === 0 ? undefined : result;\n};\n\nconst isUnknownRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst resolveHomeDirectory = (env: MerraiCliEnvironment): string =>\n trimmed(env.HOME) ?? trimmed(env.USERPROFILE) ?? os.homedir();\n\nexport const resolveMerraiConfigPaths = (\n env: MerraiCliEnvironment\n): MerraiConfigPaths => {\n const home = resolveHomeDirectory(env);\n const xdgConfigHome = trimmed(env.XDG_CONFIG_HOME);\n const windowsAppData = trimmed(env.APPDATA);\n const directory = xdgConfigHome\n ? path.join(xdgConfigHome, \"merrai\")\n : process.platform === \"win32\" && windowsAppData\n ? path.join(windowsAppData, \"Merrai\")\n : path.join(home, \".config\", \"merrai\");\n\n return {\n credentials: path.join(directory, \"credentials.json\"),\n directory,\n legacyClaudeCredentials: path.join(\n home,\n \".merrai-claude-code\",\n \"credentials.json\"\n ),\n };\n};\n\nconst parseCredentials = (\n raw: string,\n options: { requireVersion: boolean }\n): MerraiCredentials | null => {\n try {\n const value: unknown = JSON.parse(raw);\n if (!isUnknownRecord(value)) {\n return null;\n }\n\n if (options.requireVersion && value.version !== CREDENTIALS_VERSION) {\n return null;\n }\n const apiKey =\n typeof value.apiKey === \"string\" ? trimmed(value.apiKey) : undefined;\n const baseURL =\n typeof value.baseURL === \"string\" ? trimmed(value.baseURL) : undefined;\n if (apiKey === undefined) {\n return null;\n }\n\n return {\n apiKey,\n ...(baseURL === undefined ? {} : { baseURL }),\n savedAt:\n typeof value.savedAt === \"string\"\n ? value.savedAt\n : new Date(0).toISOString(),\n version: CREDENTIALS_VERSION,\n };\n } catch {\n return null;\n }\n};\n\nconst readCredentialsFile = (\n file: string,\n options: { requireVersion: boolean; strict: boolean }\n): MerraiCredentials | null => {\n if (!fs.existsSync(file)) {\n return null;\n }\n try {\n const credentials = parseCredentials(fs.readFileSync(file, \"utf8\"), {\n requireVersion: options.requireVersion,\n });\n if (credentials === null && options.strict) {\n throw new Error(\n `Invalid Merrai credentials file at ${file}. Run 'merrai auth set-key' to replace it.`\n );\n }\n return credentials;\n } catch (error) {\n if (options.strict) {\n throw error;\n }\n return null;\n }\n};\n\nexport const loadMerraiCredentials = (\n env: MerraiCliEnvironment,\n options: { strict?: boolean } = {}\n): MerraiCredentials | null => {\n const paths = resolveMerraiConfigPaths(env);\n return (\n readCredentialsFile(paths.credentials, {\n requireVersion: true,\n strict: options.strict === true,\n }) ??\n readCredentialsFile(paths.legacyClaudeCredentials, {\n requireVersion: false,\n strict: options.strict === true,\n })\n );\n};\n\nexport const saveMerraiCredentials = (\n env: MerraiCliEnvironment,\n input: { apiKey: string; baseURL?: string }\n): MerraiCredentials => {\n const apiKey = trimmed(input.apiKey);\n if (apiKey === undefined) {\n throw new Error(\"API key cannot be empty\");\n }\n\n const paths = resolveMerraiConfigPaths(env);\n fs.mkdirSync(paths.directory, { mode: 0o700, recursive: true });\n fs.chmodSync(paths.directory, 0o700);\n const credentials: MerraiCredentials = {\n apiKey,\n baseURL: trimmed(input.baseURL) ?? DEFAULT_MERRAI_BASE_URL,\n savedAt: new Date().toISOString(),\n version: CREDENTIALS_VERSION,\n };\n fs.writeFileSync(paths.credentials, JSON.stringify(credentials, null, 2), {\n mode: 0o600,\n });\n fs.chmodSync(paths.credentials, 0o600);\n return credentials;\n};\n\nconst removeFileIfPresent = (file: string): boolean => {\n try {\n fs.unlinkSync(file);\n return true;\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n};\n\nexport const clearMerraiCredentials = (\n env: MerraiCliEnvironment,\n options: { includeLegacy?: boolean } = {}\n): boolean => {\n const paths = resolveMerraiConfigPaths(env);\n const removedShared = removeFileIfPresent(paths.credentials);\n const removedLegacy =\n options.includeLegacy === true\n ? removeFileIfPresent(paths.legacyClaudeCredentials)\n : false;\n return removedShared || removedLegacy;\n};\n\nexport const resolveMerraiClientOptions = (\n env: MerraiCliEnvironment,\n overrides: MerraiCliConnectionOverrides,\n options: { strictCredentials?: boolean } = {}\n): MerraiClientOptions => {\n const apiKeyOverride =\n trimmed(overrides.apiKey) ?? trimmed(env.MERRAI_API_KEY);\n const baseURLOverride =\n trimmed(overrides.baseURL) ?? trimmed(env.MERRAI_BASE_URL);\n const credentials =\n apiKeyOverride !== undefined && baseURLOverride !== undefined\n ? null\n : loadMerraiCredentials(env, {\n strict: options.strictCredentials !== false,\n });\n return {\n apiKey: apiKeyOverride ?? credentials?.apiKey,\n baseURL: baseURLOverride ?? credentials?.baseURL ?? DEFAULT_MERRAI_BASE_URL,\n cookie: trimmed(overrides.cookie) ?? trimmed(env.MERRAI_COOKIE),\n };\n};\n"],"mappings":";;;;;;;AAgnBA,MAAa,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C,CAAC;AACR,QAAO;EACL,QAAQ,kBAAkB,aAAa;EACvC,SAAS,mBAAmB,aAAa,WAAW;EACpD,QAAQ,QAAQ,UAAU,OAAO,IAAI,QAAQ,IAAI,cAAc;EAChE"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/client.ts","../src/errors.ts","../src/memory-replacement.ts","../src/idempotency.ts","../src/config.ts"],"sourcesContent":["import { createORPCClient, createSafeClient } from \"@orpc/client\";\nimport type { Client, ClientContext, SafeClient } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\n\nexport type ThrowingRpcProcedure<Input = unknown, Output = unknown> = Client<\n ClientContext,\n Input | undefined,\n Output,\n unknown\n>;\nexport type RpcProcedure<Input = unknown, Output = unknown> = SafeClient<\n ThrowingRpcProcedure<Input, Output>\n>;\n\nexport type EntityType =\n | \"person\"\n | \"event\"\n | \"action\"\n | \"knowledge\"\n | \"document\";\n\nexport type JsonValue =\n | boolean\n | number\n | string\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport interface AddMemoryInput {\n idempotencyKey: string;\n memory: string;\n observationDate?: string;\n source?: string;\n lobeKey?: string;\n}\n\nexport interface AddMemoryOutput {\n /** Poll `ingestionStatus` with this ID to follow processing. */\n ingestionId: string;\n queued: boolean;\n}\n\nexport interface AddMemoryRecallInput {\n idempotencyKey: string;\n /** An existing lobe of the account; the main lobe when omitted. */\n lobeKey?: string;\n memory: string;\n observationDate?: string;\n}\n\nexport interface AddMemoryRecallOutput {\n ingestionId: string;\n processing: true;\n status: \"enqueued\";\n}\n\nexport interface AddMemoriesInput {\n idempotencyKey: string;\n memories: {\n memory: string;\n observationDate?: string;\n source?: string;\n lobeKey?: string;\n }[];\n}\n\nexport interface AddMemoriesOutput {\n ingestionId: string;\n queued: number;\n}\n\nexport interface FindMemoryEntitiesInput {\n name: string;\n type?: EntityType;\n limit?: number;\n}\n\n/**\n * How a known time relates to what it dates: it took place then, it is\n * planned for then, or it is due then (a deadline). Absent or null on times\n * recorded before roles existed: unspecified.\n */\nexport type EventTimeRole = \"happened\" | \"planned\" | \"due\";\n\nexport type EventTime =\n | {\n precision: \"day\" | \"week\" | \"month\" | \"year\";\n value: string;\n phrase: string | null;\n role?: EventTimeRole | null;\n }\n | {\n /** A span of calendar days, both ends included. */\n precision: \"range\";\n start: string;\n end: string;\n phrase: string | null;\n role?: EventTimeRole | null;\n }\n | {\n precision: \"unknown\";\n value: null;\n phrase: string | null;\n role?: null;\n };\nexport type MemoryEventTime =\n | EventTime\n | { precision: \"multiple\"; alternatives: EventTime[] };\n\nexport interface MemoryRecallResult {\n eventTime: MemoryEventTime | null;\n category: string | null;\n content: string;\n id: string;\n lobeKey: string;\n recordedAt: string | null;\n}\n\n/** The earlier value a Memory replaced: the latest Memory it supersedes. */\nexport interface MemoryReplacement {\n content: string;\n eventTime: MemoryEventTime | null;\n}\n\n/**\n * A current memory an update mark ties to a search result. A later value\n * never retires the earlier one: both stay current.\n */\nexport interface MemoryUpdateMark {\n /**\n * updated_by: the linked memory is a newer value of something the result\n * states, shown under it as \"↳ updated by: …\". updates: the result is a\n * newer value of something the linked memory states, shown as\n * \"replaces: …\".\n */\n relation: \"updated_by\" | \"updates\";\n id: string;\n content: string;\n eventTime: MemoryEventTime | null;\n /** The day the linked memory was last said (YYYY-MM-DD); null when unknown. */\n said: string | null;\n}\n\n/** A search result: a recall result plus what it replaced. */\nexport interface SearchMemoryRecallResult extends MemoryRecallResult {\n /**\n * Shown under it as \"replaces: …\" (renderMemoryReplacement). Null when it\n * replaced none; absent from servers that predate it.\n */\n replaces?: MemoryReplacement | null;\n /**\n * The current memories update marks tie to it, newer values first\n * (renderMemoryUpdateMarks). Absent from servers that predate it.\n */\n linked?: MemoryUpdateMark[];\n /** True for a guess from what the user asked, which no source states. */\n inferred?: boolean;\n}\n\nexport interface FindMemoryEntitiesOutput {\n entities: {\n displayName: string;\n id: string;\n memoryCount: number;\n name: string;\n type: EntityType;\n }[];\n}\n\n/**\n * MCP search_memories' selectors: at least one of query, an entity (id, or\n * name with an optional type), start or end. Date bounds are inclusive ISO\n * 8601 bounds on when a memory was recorded.\n */\nexport interface SearchMemoriesRecallInput {\n end?: string;\n entityId?: string;\n entityName?: string;\n entityType?: EntityType;\n /** 1-25; defaults to 10. */\n limit?: number;\n /** One of the caller's lobes to search instead of the owner-recall lobes. */\n lobeKey?: string;\n query?: string;\n start?: string;\n /** Memories carrying at least one of these topic keys. */\n topics?: string[];\n about?: MemoryAbout;\n /** Memories with one of these stances. */\n stance?: MemoryStance[];\n}\n\n/** Who a memory is about: the account owner, someone else, or no one. */\nexport type MemoryAbout = \"none\" | \"other\" | \"owner\";\n/** A stated fact, someone's view, or a decision. */\nexport type MemoryStance = \"decision\" | \"inferred\" | \"reported\" | \"view\";\n\n/** MCP search_memories' reply. */\nexport interface SearchMemoriesRecallOutput {\n appliedFilters: {\n end: string | null;\n entityId: string | null;\n entityName: string | null;\n entityType: EntityType | null;\n query: string | null;\n start: string | null;\n /** Absent from servers that predate label filters. */\n lobeKey?: string | null;\n topics?: string[];\n about?: MemoryAbout | null;\n stance?: MemoryStance[];\n };\n /** Several entries with status needs_disambiguation: choose one by id. */\n matchedEntities: {\n displayName: string;\n id: string;\n memoryCount: number;\n name: string;\n type: EntityType;\n }[];\n memories: SearchMemoryRecallResult[];\n status: \"complete\" | \"needs_disambiguation\";\n /** Undated memories a start/end bound could not include. */\n undatedExcludedCount: number;\n}\n\nexport interface MemoryOverviewOutput {\n account: {\n name: string;\n numberOfAiTools: number | null;\n preferredMessagingChannel: string | null;\n primaryRole: string | null;\n workplace: string | null;\n };\n profile: {\n dynamicContext: (Omit<MemoryRecallResult, \"id\"> & {\n profileExpiresAt: string;\n })[];\n facts: Omit<MemoryRecallResult, \"id\">[];\n ongoingContext: Omit<MemoryRecallResult, \"id\">[];\n scope: string;\n updatedAt: string;\n } | null;\n refresh: {\n candidateMemoryCount: number;\n status: \"current\" | \"failed\" | \"queued\";\n };\n}\n\nexport interface ListLivingDocumentsInput {\n status?: (\"enabled\" | \"disabled\" | \"archived\")[];\n}\n\nexport type LivingDocumentStatus = \"enabled\" | \"disabled\" | \"archived\";\n\n/**\n * Which of the user's lobes a document takes Memories from: every lobe\n * (including ones created later) or only the listed ones.\n */\nexport type LivingDocumentLobeScope =\n | { kind: \"all\" }\n | { kind: \"selected\"; lobeKeys: string[] };\n\nexport interface LivingDocument {\n autoPublish: boolean;\n createdAt: string;\n currentApprovedVersionId: string | null;\n currentVersionId: string | null;\n description: string | null;\n entities: string[];\n extractionPrompt: string;\n id: string;\n /**\n * Set while saved Memories of newly added lobes are brought in: `pending`\n * while running, `failed` if unfinished (`retryLivingDocumentLobeBackfill`).\n * Absent from servers before lobe scopes; `status` is absent from servers\n * before backfill failures, where every backfill is pending.\n */\n lobeBackfill?: {\n lobeKeys: string[];\n requestedAt: string;\n status?: \"failed\" | \"pending\";\n } | null;\n lobeScope?: LivingDocumentLobeScope;\n patchFailureCount: number;\n /**\n * Set while the document is rebuilt without Memories from deleted sources\n * (`memory_removed`, also when `reason` is absent) or removed lobes\n * (`lobe_scope_narrowed`). `pending`/`failed` as for `lobeBackfill` (retry\n * with `retryLivingDocumentRebuild`); content is withheld meanwhile.\n */\n rebuild: {\n reason?: \"lobe_scope_narrowed\" | \"memory_removed\";\n requestedAt: string | null;\n status: \"failed\" | \"pending\";\n } | null;\n routingSummary: string | null;\n routingSummaryDirty: boolean;\n status: LivingDocumentStatus;\n title: string;\n triggerKeywords: string[];\n updatedAt: string;\n}\n\nexport interface LivingDocumentVersion {\n causedByMemoryIds: string[];\n causedByRunId: string | null;\n contentMd: string;\n contentMdSummary: string | null;\n createdAt: string;\n documentId: string;\n extractorModel: string | null;\n id: string;\n parentVersionId: string | null;\n patch: JsonValue;\n updatedAt: string;\n versionNumber: number;\n}\n\nexport interface LivingDocumentShare {\n createdAt: string;\n documentId: string;\n expiresAt: string | null;\n id: string;\n mode: \"pinned\" | \"live\";\n permissions: \"view\" | \"view+comment\";\n revokedAt: string | null;\n shareToken: string;\n updatedAt: string;\n versionId: string | null;\n}\n\nexport interface ListLivingDocumentsOutput {\n documents: LivingDocument[];\n slots: {\n limit: number;\n plan: string;\n remaining: number;\n used: number;\n };\n}\n\nexport interface ListLivingDocumentsRecallOutput {\n documents: {\n currentVersion: { createdAt: string; number: number } | null;\n id: string;\n /** Absent from a server that predates lobe scopes. */\n lobeScope?: LivingDocumentLobeScope;\n status: string;\n summary: string;\n title: string;\n }[];\n pagination: {\n limit: number;\n nextOffset: number | null;\n offset: number;\n };\n}\n\nexport interface ListLivingDocumentsRecallInput {\n limit?: number;\n offset?: number;\n}\n\nexport interface ReadLivingDocumentRecallInput {\n contentOffset?: number;\n documentId: string;\n maxCharacters?: number;\n}\n\nexport interface ReadLivingDocumentRecallOutput {\n document: {\n currentVersion: {\n contentMarkdown: string;\n contentOffset: number;\n createdAt: string;\n nextContentOffset: number | null;\n number: number;\n returnedCharacters: number;\n totalCharacters: number;\n } | null;\n description: string | null;\n headings: string[];\n id: string;\n /** Absent from a server that predates lobe scopes. */\n lobeScope?: LivingDocumentLobeScope;\n status: string;\n summary: string;\n title: string;\n };\n}\n\nexport interface GetLivingDocumentOutput {\n currentVersion: LivingDocumentVersion | null;\n document: LivingDocument;\n}\n\nexport interface ListLivingDocumentSharesOutput {\n shares: LivingDocumentShare[];\n}\n\nexport interface GetLivingDocumentInput {\n id: string;\n}\n\nexport interface ListLivingDocumentSharesInput {\n documentId: string;\n}\n\nexport interface AddChatSessionInput {\n idempotencyKey: string;\n memories: {\n memory: string;\n observationDate?: string;\n source?: string;\n }[];\n lobeKey?: string;\n source?: string;\n sessionMetadata?: Record<string, JsonValue>;\n}\n\nexport interface AddChatSessionOutput {\n ingestionId: string;\n queued: number;\n}\n\nexport interface AddChatSessionsInput {\n lobeKey?: string;\n source?: string;\n questionMetadata?: Record<string, JsonValue>;\n /**\n * Idempotency key (1-64 chars, [A-Za-z0-9_-]). A retry with the same key and\n * payload joins the first ingestion; reusing a key with other content is\n * refused with CONFLICT (`IDEMPOTENCY_KEY_REUSED`), so derive it from content.\n */\n idempotencyKey: string;\n sessions: {\n sessionId: string;\n /**\n * Opaque session metadata. `date` is the session's source time, in the\n * same format as a turn's `sourceTime`; it dates every turn without its\n * own time and cannot change once stored.\n */\n metadata?: Record<string, JsonValue>;\n turns: {\n content: string;\n role: \"user\" | \"assistant\";\n /**\n * When the turn was said: an ISO 8601 instant with an offset\n * (`2026-03-04T09:30:00Z`) or a local calendar date (`2026-03-04`).\n * Part of the turn's identity: a resent turn must repeat it exactly.\n */\n sourceTime?: string;\n speaker?: string;\n turnIndex: number;\n }[];\n }[];\n}\n\nexport interface AddChatSessionsOutput {\n ingestionId: string;\n queuedSessions: number;\n}\n\nexport interface MemoryStatusInput {\n lobeKey?: string;\n}\n\nexport interface MemoryStatusOutput {\n count: number;\n}\n\nexport interface ClearLobeInput {\n lobeKey: string;\n}\n\n/**\n * A lobe clear runs as durable server work. `clearLobe` starts it (or joins\n * the clear already running for the lobe); `clearLobeStatus` follows it.\n */\nexport interface ClearLobeOutput {\n clearId: string;\n completedAt: string | null;\n /** Memories removed so far; final once `status` is `complete`. */\n deleted: number;\n deletedSources: number;\n lobeKey: string;\n remainingSources: number;\n startedAt: string;\n status: \"complete\" | \"failed\" | \"running\";\n}\n\n/** Omitted `lobeKey` means every lobe of the caller. */\nexport interface MemoryBackfillInput {\n lobeKey?: string;\n}\n\n/** A label backfill: the caller's run and each requested lobe's progress. */\nexport interface MemoryBackfillStatusOutput {\n /** Why deciding views' bases last failed: retried while running, kept once given up. */\n lastError: string | null;\n lobes: {\n completedAt: string | null;\n /** Observations the current or last pass labelled. */\n labelled: number;\n lastError: string | null;\n lobeKey: string;\n /** `failed` is retried by the next start. */\n state: \"complete\" | \"failed\" | \"queued\" | \"running\";\n /** Observations that needed labels when that pass began. */\n total: number;\n updatedAt: string;\n }[];\n status: \"complete\" | \"never\" | \"running\";\n}\n\n/** Omitted `lobeKey` means every lobe of the caller. */\nexport interface MemorySynthesisInput {\n lobeKey?: string;\n}\n\n/** The caller's pattern and style synthesis and each requested lobe's state. */\nexport interface MemorySynthesisStatusOutput {\n lobes: {\n lastError: string | null;\n lobeKey: string;\n /** The pass waits until this time; a start runs it now. */\n notBefore: string;\n patternCount: number;\n patternsBuiltAt: string | null;\n /** `failed` is retried by the next start or ingestion. */\n state: \"complete\" | \"failed\" | \"pending\";\n styleBuiltAt: string | null;\n }[];\n status: \"complete\" | \"never\" | \"running\";\n}\n\n/** Omitted `lobeKey` reads main, where the owner's own chats and notes are kept. */\nexport interface GetStyleProfileInput {\n /** Omit or true for the passages' text; false reads the summary only. */\n includeExemplars?: boolean;\n lobeKey?: string;\n}\n\n/** How the owner writes, built only from their own words. */\nexport interface GetStyleProfileOutput {\n lobeKey: string;\n style: {\n builtAt: string;\n /** Passages shown as exemplars, whether or not their text was read. */\n exemplarCount: number;\n exemplars: { id: string; recordedAt: string | null; text: string }[];\n sampleSize: number;\n summary: {\n aspect: \"length\" | \"structure\" | \"tone\" | \"vocabulary\";\n exemplarIds: string[];\n text: string;\n }[];\n } | null;\n}\n\nexport interface ClearLobeStatusInput {\n clearId: string;\n}\n\nexport interface RetryLivingDocumentRebuildInput {\n id: string;\n}\n\nexport interface RetryLivingDocumentRebuildOutput {\n document: LivingDocument;\n}\n\nexport interface RetryLivingDocumentLobeBackfillInput {\n id: string;\n}\n\nexport interface RetryLivingDocumentLobeBackfillOutput {\n document: LivingDocument;\n}\n\nexport interface CreateLobeInput {\n lobeKey: string;\n}\n\nexport interface CreateLobeOutput {\n lobeKey: string;\n}\n\nexport interface ListLobesOutput {\n createdAt: string;\n lobeKey: string;\n /** What the lobe is called wherever it is shown. */\n name: string;\n /** Whether the owner's agent and default recall read this lobe. */\n ownerRecall: boolean;\n /** What this lobe is for, given to extraction as focus. */\n purpose: string | null;\n updatedAt: string;\n}\n\n/** Where a page of lobes ended; pass it back unchanged. */\nexport interface LobesCursor {\n createdAt: string;\n lobeKey: string;\n}\n\nexport interface ListLobesPageInput {\n cursor?: LobesCursor;\n /** 1-50; defaults to 20. */\n limit?: number;\n}\n\n/** One of the caller's lobes as a page lists it, oldest first. */\nexport interface LobePageItem {\n lobeKey: string;\n /** What the lobe is called wherever it is shown. */\n name: string;\n /** Whether the owner's agent and default recall read this lobe. */\n ownerRecall: boolean;\n purpose: string | null;\n}\n\nexport interface ListLobesPageOutput {\n lobes: LobePageItem[];\n nextCursor: LobesCursor | null;\n}\n\nexport interface UpdateLobeInput {\n lobeKey: string;\n ownerRecall?: boolean;\n /** Null clears the purpose. */\n purpose?: string | null;\n}\n\n/** Omitted `lobeKey` means every lobe of the user. */\nexport interface MemoryTopicScopeInput {\n lobeKey?: string;\n}\n\nexport interface SetMemoryTopicInput extends MemoryTopicScopeInput {\n description: string;\n key: string;\n}\n\nexport interface RetireMemoryTopicInput extends MemoryTopicScopeInput {\n key: string;\n}\n\n/** A lobe's topic catalogue: built-ins, then the user's and the lobe's changes. */\nexport interface MemoryTopicCatalogueOutput {\n topics: {\n description: string;\n key: string;\n origin: \"core\" | \"lobe\" | \"user\";\n }[];\n lobeKey: string | null;\n}\n\n/** Where a page of open items ended; pass it back unchanged. */\nexport interface OpenItemsCursor {\n /** The first page's day; later pages keep counting from it. */\n asOf: string;\n id: string;\n startsOn: string;\n}\n\n/** Omitted `lobeKey` reads the owner-recall lobes; `asOf` defaults to today in UTC. */\nexport interface ListOpenItemsInput {\n asOf?: string;\n cursor?: OpenItemsCursor;\n /** 1-50; defaults to 20. */\n limit?: number;\n lobeKey?: string;\n until?: string;\n}\n\n/** A current memory planned or due ahead, or a decision still ahead. */\nexport interface OpenItem {\n category: string | null;\n content: string;\n eventTime: MemoryEventTime;\n id: string;\n lobeKey: string;\n recordedAt: string | null;\n role: \"due\" | \"planned\" | null;\n stance: MemoryStance | null;\n /** First day of its earliest time still ahead (YYYY-MM-DD). */\n startsOn: string;\n topics: string[];\n}\n\nexport interface ListOpenItemsOutput {\n asOf: string;\n items: OpenItem[];\n nextCursor: OpenItemsCursor | null;\n}\n\n/** Where a page of judgments ended; pass it back unchanged. */\nexport interface JudgmentsCursor {\n createdAt: string;\n id: string;\n}\n\nexport interface ListJudgmentsInput {\n cursor?: JudgmentsCursor;\n /** 1-50; defaults to 20. */\n limit?: number;\n lobeKey?: string;\n reviewState?: \"evidence_changed\";\n stance?: \"decision\" | \"view\";\n}\n\n/** A current view or decision with the facts it was formed on. */\nexport interface Judgment {\n basis: {\n content: string;\n /** False once the fact was replaced or expired. */\n current: boolean;\n id: string;\n link: \"rests_on\" | \"weighs_against\";\n }[];\n content: string;\n eventTime: MemoryEventTime | null;\n holder: string | null;\n id: string;\n lobeKey: string;\n recordedAt: string | null;\n reviewState: \"evidence_changed\" | null;\n stance: \"decision\" | \"view\";\n topics: string[];\n}\n\nexport interface ListJudgmentsOutput {\n items: Judgment[];\n nextCursor: JudgmentsCursor | null;\n}\n\n/** A current memory as `memories` lists it, with its update marks. */\nexport interface MemoryListItem {\n eventTime: MemoryEventTime | null;\n category: string | null;\n content: string;\n createdAt: string;\n expiresAt: string | null;\n id: string;\n /** Current memories an update mark ties to this one. */\n linked: MemoryUpdateMark[];\n lobeKey: string;\n memoryAt: string | null;\n memoryKind: string;\n /** When its source recorded it; null when unknown. */\n recordedAt: string | null;\n /** The earlier value this memory replaced. */\n replaces: MemoryReplacement | null;\n summary: string | null;\n updatedAt: string;\n}\n\n/** Where a `memories` page ended; pass it back unchanged. */\nexport interface MemoriesCursor {\n createdAt: string;\n id: string;\n}\n\nexport interface MemoriesInput {\n cursor?: MemoriesCursor | null;\n /** 1-100; the server's default is 50. */\n limit?: number;\n lobeKey?: string;\n}\n\nexport interface MemoriesOutput {\n items: MemoryListItem[];\n nextCursor: MemoriesCursor | null;\n}\n\nexport interface AuthSessionOutput {\n session: {\n createdAt: string | null;\n expiresAt: string | null;\n id: string;\n ipAddress: string | null;\n token: string;\n updatedAt: string | null;\n userAgent: string | null;\n userId: string;\n };\n user: {\n createdAt: string | null;\n email: string;\n emailVerified: boolean;\n id: string;\n image: string | null;\n name: string;\n onboardingComplete: boolean;\n updatedAt: string | null;\n };\n}\n\nexport type UsagePlan = \"free\" | \"beta\";\nexport type UsageMeter =\n | \"assistant_messages\"\n | \"automation_executions\"\n | \"llm_tokens\"\n | \"memory_processed\";\n\nexport interface UsageMeterSummary {\n allowed: boolean;\n current: number;\n limit: number | null;\n meter: UsageMeter;\n periodKey: string;\n plan: UsagePlan;\n remaining: number | null;\n userId: string;\n}\n\nexport interface UsageSummaryOutput {\n billing: {\n hasPaidPlan: boolean;\n plan: UsagePlan;\n /** A personal subscription or an organisation seat; null on the free plan. */\n planSource: \"personal\" | \"organisation\" | null;\n scheduledDowngradeAt: string | null;\n };\n llm: {\n byModel: {\n inputTokens: number;\n model: string;\n outputTokens: number;\n provider: string;\n requests: number;\n totalTokens: number;\n }[];\n bySurface: {\n inputTokens: number;\n outputTokens: number;\n requests: number;\n surface: string;\n totalTokens: number;\n }[];\n recentRequests: {\n cachedInputTokens: number;\n createdAt: string;\n id: string;\n inputTokens: number;\n model: string;\n outputTokens: number;\n provider: string;\n reasoningTokens: number;\n requestId: string | null;\n surface: string;\n totalTokens: number;\n }[];\n totals: {\n cachedInputTokens: number;\n inputTokens: number;\n outputTokens: number;\n reasoningTokens: number;\n requests: number;\n totalTokens: number;\n };\n };\n meters: {\n automationExecutions: UsageMeterSummary;\n llmTokens: UsageMeterSummary;\n memoryProcessed: UsageMeterSummary;\n };\n periodStart: string;\n plan: UsagePlan;\n plans: {\n automations: number | null;\n id: UsagePlan;\n memories: number | null;\n tokens: number | null;\n }[];\n}\n\nexport interface GetSessionStartContextInput {\n /**\n * Restrict to a single lobe. Plugin callers pass `cc:<repo-slug>` so memory\n * is scoped to the active project. Omit to read across every lobe.\n */\n lobeKey?: string;\n /**\n * Short retrieval hints biased toward what the caller is about to do\n * (e.g. current git branch name, last commit subject, cwd basename).\n * Cap: 5 hints × 200 chars.\n */\n recentHints?: string[];\n /**\n * Caller-side budget. Server hard caps both numbers regardless.\n */\n budget?: {\n /** Default 15, hard cap 30. */\n maxMemories?: number;\n /** Default 2000, hard cap 4000. Char-based estimate (chars / 4). */\n maxTokens?: number;\n };\n}\n\nexport interface GetSessionStartContextOutput {\n /** Markdown block ready to drop into a hook's `additionalContext`. */\n markdown: string;\n /** IDs of every memory referenced in the markdown. */\n memoryIds: string[];\n /** True when the response was truncated by the budget. */\n hasMore: boolean;\n /** Server-side ISO 8601 timestamp the context was generated. */\n generatedAt: string;\n}\n\nexport type SourceKind =\n | \"agent_conversation\"\n | \"external_chat\"\n | \"imported_chat\"\n | \"manual_entry\"\n | \"memory_source\"\n | \"upload\";\n\n/**\n * pending: stored, awaiting extraction. processing: extraction or memory\n * creation is running or will resume. partial: some windows failed, the rest\n * created memories. failed: not fetched, converted or processed. complete:\n * extraction finished and its memories were created. deleted: deleted.\n */\nexport type SourceProcessingStatus =\n | \"complete\"\n | \"deleted\"\n | \"failed\"\n | \"partial\"\n | \"pending\"\n | \"processing\";\n\nexport type SourceAction = \"delete\" | \"reprocess\" | \"retry_blocked_windows\";\n\n/**\n * Where a source came from. Agent chat: app (web, desktop or mobile), voice,\n * telegram, whatsapp, slack, discord or linear. Synced or plugin-imported chat:\n * its provider. Also granola and upload. Saved entry: app, mcp, api (an API\n * key: this CLI, the Claude Code plugin or a script) or onboarding.\n */\nexport type SourceOrigin = string;\n\nexport type SourceDetailRoute =\n | { entryId: string; kind: \"manual_entry\" }\n | {\n connectionId: string;\n conversationId: string;\n kind: \"external_chat\";\n provider: string;\n }\n | { kind: \"imported_chat\"; sessionKey: string; source: string }\n | {\n connectionId: string;\n itemId: string;\n kind: \"memory_source\";\n provider: string;\n }\n | { conversationKey: string; kind: \"agent_conversation\"; lobeKey: string }\n | { kind: \"upload\"; uploadId: string };\n\nexport interface SourceArtifact {\n artifactId: string;\n artifactType: string;\n availableActions: SourceAction[];\n blockedWindows: number;\n createdAt: string;\n detailRoute: SourceDetailRoute | null;\n lastActivityAt: string;\n lobeKey: string;\n memoryCount: number;\n /** Null when Merrai did not record it (some older sources) and once deleted. */\n origin: SourceOrigin | null;\n pausedReason: \"quota_exceeded\" | null;\n retryableBlockedWindows: number;\n sourceId: string;\n sourceKind: SourceKind;\n sourceProvider: string | null;\n status: SourceProcessingStatus;\n title: string;\n updatedAt: string;\n}\n\nexport interface SourceArtifactCursor {\n createdAt: string;\n id: string;\n}\n\nexport interface SourceArtifactListInput {\n cursor?: SourceArtifactCursor;\n limit?: number;\n lobeKey?: string;\n providers?: string[];\n sourceKinds?: SourceKind[];\n statuses?: SourceProcessingStatus[];\n}\n\nexport interface SourceArtifactListOutput {\n items: SourceArtifact[];\n /** A status-filtered page may be short while more remain. */\n nextCursor: SourceArtifactCursor | null;\n}\n\nexport interface SourceArtifactReferenceInput {\n artifactId: string;\n}\n\nexport interface SourceArtifactDeleteOutput {\n ok: true;\n sourceKind: SourceKind;\n}\n\nexport interface IngestionReferenceInput {\n ingestionId: string;\n}\n\nexport interface IngestionEnqueuedOutput {\n /** Poll `ingestionStatus` with this ID to follow processing. */\n ingestionId: string;\n status: \"enqueued\";\n}\n\nexport type IngestionRuntimeStatus =\n | \"complete\"\n | \"errored\"\n | \"paused\"\n | \"queued\"\n | \"running\"\n | \"terminated\"\n | \"unknown\"\n | \"waiting\"\n | \"waitingForEvent\"\n | \"waitingForPause\";\n\nexport type IngestionMemoryResult =\n | {\n created: number;\n reinforced: number;\n status: \"completed\";\n updated: number;\n }\n | { reason: \"source_deleted\" | \"source_policy\"; status: \"skipped\" }\n | {\n reason: \"bootstrap_required\" | \"incomplete_observations\";\n status: \"deferred\";\n }\n | {\n created: number;\n reason: \"repair_scheduled\";\n reinforced: number;\n status: \"deferred\";\n updated: number;\n };\n\nexport interface IngestionResult {\n artifacts: { artifactId: string; lobeKey: string; sourceEntryId: string }[];\n memory: IngestionMemoryResult;\n observation: {\n blockedWindows?: number;\n retryableBlockedWindows?: number;\n status: \"completed\" | \"deferred\" | \"partial\" | \"skipped\";\n };\n status: \"completed\";\n}\n\nexport interface IngestionStatusOutput {\n attempt: number;\n error: \"INGESTION_FAILED\" | null;\n ingestionId: string;\n pausedReason: \"quota_exceeded\" | null;\n result: IngestionResult | null;\n status: IngestionRuntimeStatus;\n}\n\ninterface MerraiProcedureContract {\n addChatSession: {\n input: AddChatSessionInput;\n output: AddChatSessionOutput;\n };\n addChatSessions: {\n input: AddChatSessionsInput;\n output: AddChatSessionsOutput;\n };\n addMemories: { input: AddMemoriesInput; output: AddMemoriesOutput };\n addMemory: { input: AddMemoryInput; output: AddMemoryOutput };\n clearLobe: { input: ClearLobeInput; output: ClearLobeOutput };\n clearLobeStatus: { input: ClearLobeStatusInput; output: ClearLobeOutput };\n createLobe: { input: CreateLobeInput; output: CreateLobeOutput };\n findMemoryEntities: {\n input: FindMemoryEntitiesInput;\n output: FindMemoryEntitiesOutput;\n };\n getLivingDocument: {\n input: GetLivingDocumentInput;\n output: GetLivingDocumentOutput;\n };\n getStyleProfile: {\n input: GetStyleProfileInput;\n output: GetStyleProfileOutput;\n };\n getSessionStartContext: {\n input: GetSessionStartContextInput;\n output: GetSessionStartContextOutput;\n };\n healthCheck: { input: undefined; output: \"OK\" };\n ingestionStatus: {\n input: IngestionReferenceInput;\n output: IngestionStatusOutput;\n };\n listLivingDocuments: {\n input: ListLivingDocumentsInput;\n output: ListLivingDocumentsOutput;\n };\n listTopics: {\n input: MemoryTopicScopeInput;\n output: MemoryTopicCatalogueOutput;\n };\n listLobes: { input: undefined; output: ListLobesOutput[] };\n listLobesPage: { input: ListLobesPageInput; output: ListLobesPageOutput };\n listJudgments: { input: ListJudgmentsInput; output: ListJudgmentsOutput };\n listOpenItems: { input: ListOpenItemsInput; output: ListOpenItemsOutput };\n listLivingDocumentShares: {\n input: ListLivingDocumentSharesInput;\n output: ListLivingDocumentSharesOutput;\n };\n memories: { input: MemoriesInput | undefined; output: MemoriesOutput };\n memoryOverview: {\n input: { lobeKey?: string } | undefined;\n output: MemoryOverviewOutput;\n };\n memoryBackfillStatus: {\n input: MemoryBackfillInput;\n output: MemoryBackfillStatusOutput;\n };\n memoryStatus: { input: MemoryStatusInput; output: MemoryStatusOutput };\n memorySynthesisStatus: {\n input: MemorySynthesisInput;\n output: MemorySynthesisStatusOutput;\n };\n retireTopic: {\n input: RetireMemoryTopicInput;\n output: MemoryTopicCatalogueOutput;\n };\n retryIngestionBlockedWindows: {\n input: IngestionReferenceInput;\n output: IngestionEnqueuedOutput;\n };\n retryLivingDocumentLobeBackfill: {\n input: RetryLivingDocumentLobeBackfillInput;\n output: RetryLivingDocumentLobeBackfillOutput;\n };\n retryLivingDocumentRebuild: {\n input: RetryLivingDocumentRebuildInput;\n output: RetryLivingDocumentRebuildOutput;\n };\n session: { input: undefined; output: AuthSessionOutput | null };\n setTopic: {\n input: SetMemoryTopicInput;\n output: MemoryTopicCatalogueOutput;\n };\n startMemoryBackfill: {\n input: MemoryBackfillInput;\n output: MemoryBackfillStatusOutput;\n };\n startMemorySynthesis: {\n input: MemorySynthesisInput;\n output: MemorySynthesisStatusOutput;\n };\n sourceArtifactDelete: {\n input: SourceArtifactReferenceInput;\n output: SourceArtifactDeleteOutput;\n };\n sourceArtifactGet: {\n input: SourceArtifactReferenceInput;\n output: SourceArtifact;\n };\n sourceArtifactList: {\n input: SourceArtifactListInput;\n output: SourceArtifactListOutput;\n };\n sourceArtifactReprocess: {\n input: SourceArtifactReferenceInput;\n output: IngestionEnqueuedOutput;\n };\n sourceArtifactRetry: {\n input: SourceArtifactReferenceInput;\n output: IngestionEnqueuedOutput;\n };\n updateLobe: { input: UpdateLobeInput; output: ListLobesOutput };\n usageSummary: { input: undefined; output: UsageSummaryOutput };\n}\n\n/** JSON an App Artifact handler takes or returns. */\nexport type AppArtifactJson =\n | null\n | boolean\n | number\n | string\n | AppArtifactJson[]\n | { [key: string]: AppArtifactJson };\n\nexport type AppArtifactCallKind = \"query\" | \"mutation\" | \"action\";\n\n/** One query, mutation or action a Version declares. */\nexport interface AppArtifactHandler {\n name: string;\n description: string;\n /** Callable only from the App Artifact's own UI, not the CLI. */\n internal: boolean;\n input: Record<string, AppArtifactJson>;\n}\n\nexport type AppArtifactSampleDataState = \"valid\" | \"missing\" | \"invalid\";\n\nexport interface AppArtifactVersion {\n id: string;\n number: number;\n commitOid: string;\n manifest: {\n name: string;\n description: string;\n accountSlots: { name: string; toolkit: string; tools: string[] }[];\n sync: boolean;\n };\n api: {\n tables: string[];\n queries: AppArtifactHandler[];\n mutations: AppArtifactHandler[];\n actions: AppArtifactHandler[];\n hasSync: boolean;\n };\n allowedTools: string[];\n /** Whether its `sample-data.json` loaded into a throwaway copy when published. */\n sampleData: AppArtifactSampleDataState;\n createdAt: string;\n}\n\nexport interface AppArtifact {\n id: string;\n name: string;\n status: \"active\" | \"archived\";\n currentVersion: AppArtifactVersion | null;\n /** Tools the Current Version uses that the owner has not allowed yet. */\n pendingTools: string[];\n slotAccounts: Record<string, { connectedAccountId: string; toolkit: string }>;\n sync: {\n state: \"off\" | \"never\" | \"ok\" | \"failing\" | \"paused\";\n lastSuccessAt: string | null;\n failingSince: string | null;\n lastError: string | null;\n consecutiveFailures: number;\n nextSyncAt: string | null;\n };\n recentErrors: { source: \"ui\" | \"server\"; message: string; at: string }[];\n createdAt: string;\n updatedAt: string;\n}\n\n/** A handler's result; App Artifact failures are values, not errors. */\nexport type AppArtifactCallResult =\n | { ok: true; value: AppArtifactJson; dataVersion?: number }\n | {\n ok: false;\n error: string;\n dataVersion?: number;\n /** `app`: the App Artifact's code failed; `refused`: Merrai refused the call. */\n fault?: \"app\" | \"refused\";\n /** A share level stopped a tool: it cannot act, or it now waits for the owner. */\n code?: \"needs_act\" | \"needs_approval\";\n tool?: string;\n requestId?: string;\n };\n\n/** An App Artifact someone else owns and shared with the caller (ADR 0009). */\nexport interface SharedAppArtifact {\n id: string;\n name: string;\n description: string;\n owner: { id: string; name: string };\n level: \"use\" | \"ask\" | \"act\";\n via: (\"user\" | \"organization\" | \"link\")[];\n api: AppArtifactVersion[\"api\"] | null;\n}\n\n/** One action the caller asked the owner to approve, and what became of it. */\nexport interface AppArtifactActionRequest {\n id: string;\n appArtifactId: string;\n action: string;\n tool: string;\n status:\n | \"pending\"\n | \"approved\"\n | \"denied\"\n | \"cancelled\"\n | \"withdrawn\"\n | \"done\"\n | \"failed\";\n error: string | null;\n createdAt: string;\n resolvedAt: string | null;\n}\n\n/** Working source: path → UTF-8 text. */\nexport type AppArtifactSourceFiles = Record<string, string>;\n\nexport type AppArtifactBuildingGuideTopic = \"authoring\" | \"design\";\n\n/** How to build an app from a folder; MCP and the public agent skill serve the same text. */\nexport interface AppArtifactBuildingGuide {\n topic: AppArtifactBuildingGuideTopic;\n text: string;\n}\n\n/** An archived app deleted for good; its stored data may still be on its way out. */\nexport interface AppArtifactDeleted {\n appArtifactId: string;\n dataRemoved: boolean;\n}\n\nexport interface PublishedAppArtifact {\n artifact: AppArtifact;\n version: AppArtifactVersion;\n pendingTools: string[];\n smokeRender: { ok: boolean; detail: string };\n /** Reported, never blocking: why sample data is missing or did not load. */\n sampleData: { state: AppArtifactSampleDataState; detail: string };\n}\n\ninterface MerraiAppArtifactProcedureContract {\n list: {\n input: { status?: \"active\" | \"archived\" } | undefined;\n output: AppArtifact[];\n };\n get: { input: { appArtifactId: string }; output: AppArtifact };\n /** Archived apps only; the server refuses an active one. */\n delete: { input: { appArtifactId: string }; output: AppArtifactDeleted };\n call: {\n input: {\n appArtifactId: string;\n kind: AppArtifactCallKind;\n name: string;\n input?: AppArtifactJson;\n };\n output: AppArtifactCallResult;\n };\n openUrl: {\n input: { appArtifactId: string; mode?: \"window\" | \"embed\" };\n output: { url: string };\n };\n create: {\n input: { name: string; creationKey?: string };\n output: AppArtifact;\n };\n buildingGuide: {\n input: { topic?: AppArtifactBuildingGuideTopic };\n output: AppArtifactBuildingGuide;\n };\n source: {\n input: { appArtifactId: string };\n output: { files: AppArtifactSourceFiles; revision: string };\n };\n saveSource: {\n input: {\n appArtifactId: string;\n files: AppArtifactSourceFiles;\n message: string;\n /** Refused when the Working source moved on since this revision. */\n expectedRevision?: string;\n };\n output: { ok: true; revision: string };\n };\n publish: {\n input: {\n appArtifactId: string;\n message: string;\n publishKey?: string;\n expectedRevision?: string;\n };\n output: PublishedAppArtifact;\n };\n sharedWithMe: { input: undefined; output: SharedAppArtifact[] };\n getShared: { input: { appArtifactId: string }; output: SharedAppArtifact };\n actionRequests: {\n input: { appArtifactId: string };\n output: AppArtifactActionRequest[];\n };\n cancelActionRequest: {\n input: { appArtifactId: string; requestId: string };\n output: AppArtifactActionRequest;\n };\n}\n\ninterface MerraiRecallProcedureContract {\n addMemory: {\n input: AddMemoryRecallInput;\n output: AddMemoryRecallOutput;\n };\n listLivingDocuments: {\n input: ListLivingDocumentsRecallInput;\n output: ListLivingDocumentsRecallOutput;\n };\n readLivingDocument: {\n input: ReadLivingDocumentRecallInput;\n output: ReadLivingDocumentRecallOutput;\n };\n /** MCP search_memories over oRPC; no model call. */\n searchMemories: {\n input: SearchMemoriesRecallInput;\n output: SearchMemoriesRecallOutput;\n };\n}\n\ntype ThrowingProcedureClient<Contract> = {\n [ProcedureName in keyof Contract]: Contract[ProcedureName] extends {\n input: infer Input;\n output: infer Output;\n }\n ? ThrowingRpcProcedure<Input, Output>\n : never;\n};\n\nexport type MerraiClient = SafeClient<MerraiThrowingClient>;\n\nexport type MerraiThrowingClient =\n ThrowingProcedureClient<MerraiProcedureContract> & {\n recall: ThrowingProcedureClient<MerraiRecallProcedureContract>;\n appArtifacts: ThrowingProcedureClient<MerraiAppArtifactProcedureContract>;\n };\n\nexport interface MerraiClientOptions {\n baseURL?: string;\n apiKey?: string;\n cookie?: string;\n fetch?: ConstructorParameters<typeof RPCLink>[0][\"fetch\"];\n headers?: HeadersInit;\n}\n\nexport const resolveBaseURL = (baseURL?: string): string => {\n const resolved = baseURL?.trim();\n\n if (resolved === undefined || resolved === \"\") {\n throw new Error(\n \"baseURL is required. Set --base-url, MERRAI_BASE_URL, or saved credentials\"\n );\n }\n\n return resolved.endsWith(\"/\") ? resolved.slice(0, -1) : resolved;\n};\n\nconst resolveHeaders = (\n headers?: HeadersInit,\n apiKey?: string,\n cookie?: string\n): Record<string, string> => {\n const resolvedHeaders = new Headers(headers);\n // Merrai omits fields older clients cannot decode unless told they are dropped;\n // this client keeps no strict copies, so it takes every field.\n resolvedHeaders.set(\"x-merrai-unknown-fields\", \"strip\");\n\n if (apiKey !== undefined && apiKey !== \"\") {\n resolvedHeaders.set(\"x-api-key\", apiKey);\n }\n\n if (cookie !== undefined && cookie !== \"\") {\n resolvedHeaders.set(\"Cookie\", cookie);\n }\n\n return Object.fromEntries(resolvedHeaders.entries());\n};\n\nconst createMerraiRpcLink = (options: MerraiClientOptions) =>\n new RPCLink({\n fetch: options.fetch,\n headers: () =>\n resolveHeaders(options.headers, options.apiKey, options.cookie),\n url: `${resolveBaseURL(options.baseURL)}/rpc`,\n });\n\nexport const createRawMerraiClient = (\n options: MerraiClientOptions = {}\n): MerraiThrowingClient =>\n createORPCClient<MerraiThrowingClient>(createMerraiRpcLink(options));\n\n/** Debug names address the remote router independently of the published client mirror. */\nexport const createMerraiDebugProcedure = (\n options: MerraiClientOptions,\n procedureName: string\n): ThrowingRpcProcedure<JsonValue, JsonValue> =>\n createORPCClient<ThrowingRpcProcedure<JsonValue, JsonValue>>(\n createMerraiRpcLink(options),\n { path: [procedureName] }\n );\n\nexport const createMerraiClient = (\n options: MerraiClientOptions = {}\n): MerraiClient => {\n const client = createSafeClient(createRawMerraiClient(options));\n return client;\n};\n\nexport const createMerraiThrowingClient = (\n options: MerraiClientOptions = {}\n): MerraiThrowingClient => createRawMerraiClient(options);\n","import { CommanderError } from \"commander\";\nimport { z } from \"zod\";\n\nimport type { JsonValue } from \"./client\";\n\nexport const MERRAI_CLI_EXIT_CODES = {\n /** An App Artifact handler ran and failed: its own error, not Merrai's. */\n appFailed: 6,\n auth: 3,\n network: 10,\n notFound: 4,\n rateLimit: 5,\n success: 0,\n usage: 2,\n} as const;\n\n/**\n * An App Artifact call that answered with a failure. Handler failures are\n * values on the wire; the CLI still exits non-zero so scripts notice.\n */\nexport class MerraiCliAppArtifactCallError extends Error {\n public constructor(\n message: string,\n readonly fault: \"app\" | \"refused\" | undefined\n ) {\n super(message);\n this.name = \"MerraiCliAppArtifactCallError\";\n }\n}\n\nexport class MerraiCliUsageError extends Error {\n public constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"MerraiCliUsageError\";\n }\n}\n\n/** Nothing of the caller's matched; exits as the server's not found does. */\nexport class MerraiCliNotFoundError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = \"MerraiCliNotFoundError\";\n }\n}\n\nexport interface MerraiCliErrorResult {\n exitCode: number;\n message: string;\n shouldRender: boolean;\n}\n\ninterface MerraiCliErrorMetadata {\n code?: string;\n data?: JsonValue;\n status?: number;\n}\n\nconst orpcErrorSchema = z.object({\n code: z.string(),\n data: z.unknown().optional(),\n message: z.string(),\n status: z.number(),\n});\ntype ParsedOrpcError = z.infer<typeof orpcErrorSchema>;\n\nexport const INVALID_API_KEY_CLI_MESSAGE =\n \"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.\";\n\nconst invalidApiKeyErrorSchema = z.object({\n code: z.literal(\"UNAUTHORIZED\"),\n // The server's `data.reason` for a key that authenticates no one.\n data: z.object({ reason: z.literal(\"INVALID_API_KEY\") }),\n});\n\n/**\n * True when the server refused the request's API key as unknown, malformed,\n * revoked or expired. That key will not work again.\n */\nexport const isInvalidApiKeyError = (\n // Callers pass caught values; the schema narrows them.\n error: unknown\n): error is z.infer<typeof invalidApiKeyErrorSchema> =>\n invalidApiKeyErrorSchema.safeParse(error).success;\n\n/** True when Merrai answered that nothing of the caller's has that id. */\nexport const isMerraiNotFoundError = (\n // Callers pass caught values; the schema narrows them.\n error: unknown\n): boolean => orpcErrorSchema.safeParse(error).data?.code === \"NOT_FOUND\";\n\nconst refusalReasonSchema = z.object({\n code: z.literal(\"NOT_FOUND\"),\n data: z.object({ reason: z.string() }),\n});\n\n/** The server's `data.reason` on a NOT_FOUND refusal, such as `archived`. */\nexport const merraiNotFoundReason = (\n // Callers pass caught values; the schema narrows them.\n error: unknown\n): string | undefined => refusalReasonSchema.safeParse(error).data?.data.reason;\n\nconst renderJsonError = (\n message: string,\n metadata: Readonly<MerraiCliErrorMetadata> = {}\n): string => JSON.stringify({ error: { ...metadata, message } }, null, 2);\n\nconst renderOrpcError = (error: ParsedOrpcError): string => {\n const metadata: MerraiCliErrorMetadata = {\n code: error.code,\n status: error.status,\n };\n const data = z.json().safeParse(error.data);\n if (data.success) {\n metadata.data = data.data;\n }\n return renderJsonError(error.message, metadata);\n};\n\nexport const classifyMerraiCliError = (\n // This is the CLI process boundary that normalizes all thrown values before rendering.\n error: unknown\n): MerraiCliErrorResult => {\n if (error instanceof CommanderError) {\n const isSuccessfulControlFlow =\n error.code === \"commander.helpDisplayed\" ||\n error.code === \"commander.version\";\n return {\n exitCode: isSuccessfulControlFlow\n ? MERRAI_CLI_EXIT_CODES.success\n : MERRAI_CLI_EXIT_CODES.usage,\n message: error.message,\n shouldRender: false,\n };\n }\n\n if (error instanceof MerraiCliAppArtifactCallError) {\n return {\n // Merrai refusing the call (not allowed, archived) is a permission\n // problem; anything else is the App Artifact's own failure.\n exitCode:\n error.fault === \"refused\"\n ? MERRAI_CLI_EXIT_CODES.auth\n : MERRAI_CLI_EXIT_CODES.appFailed,\n message: renderJsonError(error.message, {\n code: error.fault === \"refused\" ? \"CALL_REFUSED\" : \"CALL_FAILED\",\n }),\n shouldRender: true,\n };\n }\n\n if (error instanceof MerraiCliUsageError) {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.usage,\n message: renderJsonError(error.message, { code: \"USAGE_ERROR\" }),\n shouldRender: true,\n };\n }\n\n if (error instanceof MerraiCliNotFoundError) {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.notFound,\n message: renderJsonError(error.message, { code: \"NOT_FOUND\" }),\n shouldRender: true,\n };\n }\n\n const orpcError = orpcErrorSchema.safeParse(error);\n if (orpcError.success) {\n const code = orpcError.data.code;\n if (code === \"BAD_REQUEST\" || code === \"UNPROCESSABLE_CONTENT\") {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.usage,\n message: renderOrpcError(orpcError.data),\n shouldRender: true,\n };\n }\n if (code === \"UNAUTHORIZED\" || code === \"FORBIDDEN\") {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.auth,\n message: renderOrpcError(\n isInvalidApiKeyError(orpcError.data)\n ? { ...orpcError.data, message: INVALID_API_KEY_CLI_MESSAGE }\n : orpcError.data\n ),\n shouldRender: true,\n };\n }\n if (code === \"NOT_FOUND\" || code === \"CONFLICT\") {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.notFound,\n message: renderOrpcError(orpcError.data),\n shouldRender: true,\n };\n }\n if (\n code === \"RATE_LIMITED\" ||\n code === \"TOO_MANY_REQUESTS\" ||\n code === \"PAYLOAD_TOO_LARGE\" ||\n code === \"RESOURCE_EXHAUSTED\" ||\n orpcError.data.status === 429\n ) {\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.rateLimit,\n message: renderOrpcError(orpcError.data),\n shouldRender: true,\n };\n }\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.network,\n message: renderOrpcError(orpcError.data),\n shouldRender: true,\n };\n }\n\n const nativeError = z.instanceof(Error).safeParse(error);\n const stringError = z.string().safeParse(error);\n return {\n exitCode: MERRAI_CLI_EXIT_CODES.network,\n message: renderJsonError(\n nativeError.success\n ? nativeError.data.message\n : stringError.success\n ? stringError.data\n : \"Unexpected CLI failure\",\n { code: \"NETWORK_ERROR\" }\n ),\n shouldRender: true,\n };\n};\n","import type {\n EventTime,\n MemoryEventTime,\n MemoryReplacement,\n MemoryUpdateMark,\n} from \"./client\";\n\n// Mirrors the reader lines of Merrai's Search (packages/api search-render:\n// replacesText and memoryLinkLines) for a published client that does not\n// depend on the server packages.\n\n/**\n * Exhaustive at compile time; a precision this client does not know reads as\n * unknown rather than failing the output.\n */\nconst unsupportedPrecision = (_time: never): string => \"unknown\";\n\n/**\n * The calendar reading alone: \"2024-04-05\", \"week of 2024-04-01\",\n * \"2024-04-20 to 2024-04-21\".\n */\nconst calendarText = (time: EventTime): string => {\n switch (time.precision) {\n case \"week\":\n return `week of ${time.value}`;\n case \"day\":\n case \"month\":\n case \"year\":\n return time.value;\n case \"range\":\n return `${time.start} to ${time.end}`;\n case \"unknown\":\n return \"unknown\";\n default:\n return unsupportedPrecision(time);\n }\n};\n\n/** A plan's or deadline's role; null for what happened or an unstated role. */\nconst forwardRole = (time: EventTime): \"planned\" | \"due\" | null => {\n const role = time.precision === \"unknown\" ? null : time.role;\n return role === \"planned\" || role === \"due\" ? role : null;\n};\n\n/**\n * An event time as the server words it: a plan or a deadline names its role\n * (\"due 2024-04-20\"); what happened is the calendar reading alone.\n */\nexport const describeEventTime = (time: MemoryEventTime): string => {\n if (time.precision === \"multiple\")\n return time.alternatives.map(describeEventTime).join(\" or \");\n const role = forwardRole(time);\n return role === null ? calendarText(time) : `${role} ${calendarText(time)}`;\n};\n\n/** Whether any reading of the time is a plan or a deadline. */\nconst hasForwardRole = (time: MemoryEventTime): boolean =>\n (time.precision === \"multiple\" ? time.alternatives : [time]).some(\n (reading) => forwardRole(reading) !== null\n );\n\n/**\n * \"replaces: <earlier text> (due 2024-04-20)\": the line Merrai's Search and\n * recall evidence show under a Memory that replaced an earlier value (the\n * latest Memory it supersedes), so a terse update keeps its subject and the\n * old value. Null when it replaced none.\n */\nexport const renderMemoryReplacement = (\n replaced: MemoryReplacement | null | undefined\n): string | null => {\n if (replaced === null || replaced === undefined) return null;\n const time =\n replaced.eventTime === null || replaced.eventTime.precision === \"unknown\"\n ? null\n : describeEventTime(replaced.eventTime);\n return time === null\n ? `replaces: ${replaced.content}`\n : `replaces: ${replaced.content} (${time})`;\n};\n\nconst UPDATE_MARK_LABELS = {\n updated_by: \"↳ updated by\",\n updates: \"replaces\",\n} as const satisfies Record<MemoryUpdateMark[\"relation\"], string>;\n\n/**\n * A linked memory as a mark names it: by its id when the reader is shown it\n * too, otherwise its text with when it happened or is planned or due and the\n * day it was said: \"Budget is now $4,000. (said 2024-03-16)\".\n */\nconst linkedMemoryText = (\n mark: MemoryUpdateMark,\n shownIds: ReadonlySet<string>\n): string => {\n if (shownIds.has(mark.id)) return mark.id;\n const time = mark.eventTime;\n const notes = [\n time === null || time.precision === \"unknown\"\n ? null\n : hasForwardRole(time)\n ? describeEventTime(time)\n : `happened ${describeEventTime(time)}`,\n mark.said === null ? null : `said ${mark.said}`,\n ].filter((note) => note !== null);\n return notes.length === 0\n ? mark.content\n : `${mark.content} (${notes.join(\"; \")})`;\n};\n\n/**\n * \"↳ updated by: …\" and \"replaces: …\": the update marks Merrai's Search shows\n * under a memory, newer values first, one line per relation. A later value\n * never retires the earlier one; both stay current. A relation this client\n * does not know is left out rather than failing the output.\n */\nexport const renderMemoryUpdateMarks = (\n marks: readonly MemoryUpdateMark[] | undefined,\n shownIds: ReadonlySet<string>\n): string[] =>\n ([\"updated_by\", \"updates\"] as const).flatMap((relation) => {\n const members = (marks ?? []).filter((mark) => mark.relation === relation);\n return members.length === 0\n ? []\n : [\n `${UPDATE_MARK_LABELS[relation]}: ${members\n .map((mark) => linkedMemoryText(mark, shownIds))\n .join(\"; \")}`,\n ];\n });\n\n/**\n * Each search result's lines as Merrai's Search shows them: its own line\n * (`renderLine`), labelled with its id when another result's mark names it,\n * then what it replaced and its update marks.\n */\nexport const searchResultLines = <\n Result extends {\n id: string;\n linked?: readonly MemoryUpdateMark[];\n replaces?: MemoryReplacement | null;\n },\n>(\n results: readonly Result[],\n renderLine: (result: Result) => string\n): string[][] => {\n const shownIds = new Set(results.map((result) => result.id));\n const named = new Set(\n results.flatMap((result) =>\n (result.linked ?? []).flatMap((mark) =>\n shownIds.has(mark.id) ? [mark.id] : []\n )\n )\n );\n return results.map((result) => {\n const line = renderLine(result);\n const replaced = renderMemoryReplacement(result.replaces);\n return [\n named.has(result.id) ? `${line} [${result.id}]` : line,\n ...(replaced === null ? [] : [replaced]),\n ...renderMemoryUpdateMarks(result.linked, shownIds),\n ];\n });\n};\n","import * as NodeCrypto from \"node:crypto\";\n\n/** Accepted by every write API's `idempotencyKey`, including `addChatSessions`. */\nconst IDEMPOTENCY_KEY_HEX_LENGTH = 48;\n\n/** JSON-shaped request content; `undefined` object fields are omitted. */\nexport type IdempotencyKeyMaterial =\n | boolean\n | number\n | string\n | null\n | undefined\n | readonly IdempotencyKeyMaterial[]\n | { readonly [key: string]: IdempotencyKeyMaterial };\n\ntype IdempotencyKeyRecord = {\n readonly [key: string]: IdempotencyKeyMaterial;\n};\n\nconst isKeyMaterialRecord = (\n value: IdempotencyKeyMaterial\n): value is IdempotencyKeyRecord =>\n value !== null &&\n !Array.isArray(value) &&\n Object.prototype.toString.call(value) === \"[object Object]\";\n\n// Sorted keys, so the same content always serializes to the same bytes.\nconst canonicalJson = (value: IdempotencyKeyMaterial): string => {\n if (value === undefined) {\n return \"null\";\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(\",\")}]`;\n }\n if (isKeyMaterialRecord(value)) {\n return `{${Object.entries(value)\n .filter(([, entry]) => entry !== undefined)\n .toSorted(([left], [right]) => (left < right ? -1 : 1))\n .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value);\n};\n\n/**\n * A stable idempotency key derived from what one write sends, so a rerun joins\n * the existing ingestion; any change to content, source, lobe or dates changes\n * it. `operation` namespaces keys by API shape. Undefined fields are omitted,\n * so an absent option and an explicit `undefined` produce the same key.\n */\nexport const deriveIdempotencyKey = (\n operation: string,\n payload: { readonly [key: string]: IdempotencyKeyMaterial }\n): string =>\n NodeCrypto.createHash(\"sha256\")\n .update(canonicalJson({ operation, payload, version: 1 }))\n .digest(\"hex\")\n .slice(0, IDEMPOTENCY_KEY_HEX_LENGTH);\n\n/**\n * The key for saving one memory (CLI `memory add`, the plugin's\n * `/merrai:save`). Without a supplied observation time, the same sentence\n * saved on a later day is a new occurrence (\"went running\"), not a retry, so\n * the UTC day joins the key; same-day reruns still collapse into one save.\n */\nexport const deriveMemorySaveIdempotencyKey = (input: {\n lobeKey?: string;\n memory: string;\n now: Date;\n observationDate?: string;\n source?: string;\n}): string =>\n deriveIdempotencyKey(\"memory-save\", {\n lobeKey: input.lobeKey,\n memory: input.memory,\n observationDate: input.observationDate,\n occurrenceDay:\n input.observationDate === undefined\n ? input.now.toISOString().slice(0, 10)\n : undefined,\n source: input.source,\n });\n","import * as NodeFS from \"node:fs\";\nimport * as NodeOS from \"node:os\";\nimport * as NodePath from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport type { MerraiClientOptions } from \"./client\";\n\nexport const DEFAULT_MERRAI_BASE_URL = \"https://api.merrai.app\";\nconst CREDENTIALS_VERSION = 1;\n\nexport type MerraiCliEnvironment = Readonly<Record<string, string | undefined>>;\n\nexport interface MerraiCliConnectionOverrides {\n apiKey?: string;\n baseURL?: string;\n cookie?: string;\n}\n\nexport interface MerraiCredentials {\n apiKey: string;\n baseURL?: string;\n savedAt: string;\n version: typeof CREDENTIALS_VERSION;\n}\n\nexport interface MerraiConfigPaths {\n credentials: string;\n directory: string;\n legacyClaudeCredentials: string;\n}\n\nconst trimmed = (value: string | undefined): string | undefined => {\n const result = value?.trim();\n return result === undefined || result.length === 0 ? undefined : result;\n};\n\nconst credentialsValueSchema = z.object({\n apiKey: z.string().trim().min(1),\n baseURL: z.string().trim().min(1).nullish(),\n savedAt: z.string().optional(),\n version: z.literal(CREDENTIALS_VERSION).optional(),\n});\n\nconst systemErrorSchema = z.object({ code: z.string() });\n\nconst resolveHomeDirectory = (env: MerraiCliEnvironment): string =>\n trimmed(env.HOME) ?? trimmed(env.USERPROFILE) ?? NodeOS.homedir();\n\nexport const resolveMerraiConfigPaths = (\n env: MerraiCliEnvironment\n): MerraiConfigPaths => {\n const home = resolveHomeDirectory(env);\n const xdgConfigHome = trimmed(env.XDG_CONFIG_HOME);\n const windowsAppData = trimmed(env.APPDATA);\n const directory =\n xdgConfigHome !== undefined\n ? NodePath.join(xdgConfigHome, \"merrai\")\n : process.platform === \"win32\" && windowsAppData !== undefined\n ? NodePath.join(windowsAppData, \"Merrai\")\n : NodePath.join(home, \".config\", \"merrai\");\n\n return {\n credentials: NodePath.join(directory, \"credentials.json\"),\n directory,\n legacyClaudeCredentials: NodePath.join(\n home,\n \".merrai-claude-code\",\n \"credentials.json\"\n ),\n };\n};\n\nconst parseCredentials = (\n raw: string,\n options: { requireVersion: boolean }\n): MerraiCredentials | null => {\n try {\n const parsed = credentialsValueSchema.safeParse(JSON.parse(raw));\n if (!parsed.success) {\n return null;\n }\n const value = parsed.data;\n\n if (options.requireVersion && value.version !== CREDENTIALS_VERSION) {\n return null;\n }\n\n const credentials: MerraiCredentials = {\n apiKey: value.apiKey,\n savedAt: value.savedAt ?? new Date(0).toISOString(),\n version: CREDENTIALS_VERSION,\n };\n if (value.baseURL !== undefined && value.baseURL !== null) {\n credentials.baseURL = value.baseURL;\n }\n return credentials;\n } catch {\n return null;\n }\n};\n\nconst readCredentialsFile = (\n file: string,\n options: { requireVersion: boolean; strict: boolean }\n): MerraiCredentials | null => {\n if (!NodeFS.existsSync(file)) {\n return null;\n }\n try {\n const credentials = parseCredentials(NodeFS.readFileSync(file, \"utf8\"), {\n requireVersion: options.requireVersion,\n });\n if (credentials === null && options.strict) {\n throw new Error(\n `Invalid Merrai credentials file at ${file}. Run 'merrai auth set-key' to replace it.`\n );\n }\n return credentials;\n } catch (error) {\n if (options.strict) {\n throw error;\n }\n return null;\n }\n};\n\nexport const loadMerraiCredentials = (\n env: MerraiCliEnvironment,\n options: { strict?: boolean } = {}\n): MerraiCredentials | null => {\n const paths = resolveMerraiConfigPaths(env);\n return (\n readCredentialsFile(paths.credentials, {\n requireVersion: true,\n strict: options.strict === true,\n }) ??\n readCredentialsFile(paths.legacyClaudeCredentials, {\n requireVersion: false,\n strict: options.strict === true,\n })\n );\n};\n\nexport const saveMerraiCredentials = (\n env: MerraiCliEnvironment,\n input: { apiKey: string; baseURL?: string }\n): MerraiCredentials => {\n const apiKey = trimmed(input.apiKey);\n if (apiKey === undefined) {\n throw new Error(\"API key cannot be empty\");\n }\n\n const paths = resolveMerraiConfigPaths(env);\n NodeFS.mkdirSync(paths.directory, { mode: 0o700, recursive: true });\n NodeFS.chmodSync(paths.directory, 0o700);\n const credentials: MerraiCredentials = {\n apiKey,\n baseURL: trimmed(input.baseURL) ?? DEFAULT_MERRAI_BASE_URL,\n savedAt: new Date().toISOString(),\n version: CREDENTIALS_VERSION,\n };\n NodeFS.writeFileSync(\n paths.credentials,\n JSON.stringify(credentials, null, 2),\n {\n mode: 0o600,\n }\n );\n NodeFS.chmodSync(paths.credentials, 0o600);\n return credentials;\n};\n\nconst removeFileIfPresent = (file: string): boolean => {\n try {\n NodeFS.unlinkSync(file);\n return true;\n } catch (error) {\n const systemError = systemErrorSchema.safeParse(error);\n if (systemError.success && systemError.data.code === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n};\n\nexport const clearMerraiCredentials = (\n env: MerraiCliEnvironment,\n options: { includeLegacy?: boolean } = {}\n): boolean => {\n const paths = resolveMerraiConfigPaths(env);\n const removedShared = removeFileIfPresent(paths.credentials);\n const removedLegacy =\n options.includeLegacy === true\n ? removeFileIfPresent(paths.legacyClaudeCredentials)\n : false;\n return removedShared || removedLegacy;\n};\n\nexport const resolveMerraiClientOptions = (\n env: MerraiCliEnvironment,\n overrides: MerraiCliConnectionOverrides,\n options: { strictCredentials?: boolean } = {}\n): MerraiClientOptions => {\n const apiKeyOverride =\n trimmed(overrides.apiKey) ?? trimmed(env.MERRAI_API_KEY);\n const baseURLOverride =\n trimmed(overrides.baseURL) ?? trimmed(env.MERRAI_BASE_URL);\n const credentials =\n apiKeyOverride !== undefined && baseURLOverride !== undefined\n ? null\n : loadMerraiCredentials(env, {\n strict: options.strictCredentials !== false,\n });\n return {\n apiKey: apiKeyOverride ?? credentials?.apiKey,\n baseURL: baseURLOverride ?? credentials?.baseURL ?? DEFAULT_MERRAI_BASE_URL,\n cookie: trimmed(overrides.cookie) ?? trimmed(env.MERRAI_COOKIE),\n };\n};\n"],"mappings":";;;;;;;;;AAi6CA,MAAa,kBAAkB,YAA6B;CAC1D,MAAM,WAAW,SAAS,KAAK;CAE/B,IAAI,aAAa,KAAA,KAAa,aAAa,IACzC,MAAM,IAAI,MACR,4EACF;CAGF,OAAO,SAAS,SAAS,GAAG,IAAI,SAAS,MAAM,GAAG,EAAE,IAAI;AAC1D;AAEA,MAAM,kBACJ,SACA,QACA,WAC2B;CAC3B,MAAM,kBAAkB,IAAI,QAAQ,OAAO;CAG3C,gBAAgB,IAAI,2BAA2B,OAAO;CAEtD,IAAI,WAAW,KAAA,KAAa,WAAW,IACrC,gBAAgB,IAAI,aAAa,MAAM;CAGzC,IAAI,WAAW,KAAA,KAAa,WAAW,IACrC,gBAAgB,IAAI,UAAU,MAAM;CAGtC,OAAO,OAAO,YAAY,gBAAgB,QAAQ,CAAC;AACrD;AAEA,MAAM,uBAAuB,YAC3B,IAAI,QAAQ;CACV,OAAO,QAAQ;CACf,eACE,eAAe,QAAQ,SAAS,QAAQ,QAAQ,QAAQ,MAAM;CAChE,KAAK,GAAG,eAAe,QAAQ,OAAO,EAAE;AAC1C,CAAC;AAEH,MAAa,yBACX,UAA+B,CAAC,MAEhC,iBAAuC,oBAAoB,OAAO,CAAC;AAYrE,MAAa,sBACX,UAA+B,CAAC,MACf;CAEjB,OADe,iBAAiB,sBAAsB,OAAO,CACjD;AACd;AAEA,MAAa,8BACX,UAA+B,CAAC,MACP,sBAAsB,OAAO;ACz6ChC,EAAE,OAAO;CAC/B,MAAM,EAAE,OAAO;CACf,MAAM,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO;CAClB,QAAQ,EAAE,OAAO;AACnB,CAAC;AAGD,MAAa,8BACX;AAEF,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