@1mbrain/sdk 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ AGENT_SYSTEM_PROMPT: () => AGENT_SYSTEM_PROMPT,
24
+ OneMBrainClient: () => OneMBrainClient,
25
+ OneMBrainError: () => OneMBrainError
26
+ });
27
+ module.exports = __toCommonJS(src_exports);
28
+
29
+ // src/prompts.ts
30
+ var AGENT_SYSTEM_PROMPT = `You are equipped with 1MBrain, a highly advanced long-term memory engine.
31
+ You have access to memory tools (e.g., \`remember\` and \`recall\`) to store and retrieve information across sessions.
32
+
33
+ CRITICAL INSTRUCTIONS FOR USING YOUR MEMORY:
34
+
35
+ 1. ALWAYS SEARCH FIRST: Before asking the user for information you might already know, or before making assumptions, ALWAYS use the \`recall\` tool to search your memory.
36
+ 2. PREFER SPECIFIC QUERIES: When using \`recall\`, use specific conceptual queries rather than vague keywords. (e.g., "user dietary restrictions" instead of "food").
37
+ 3. RECORD NEW FACTS ACTIVELY: Whenever the user provides new, durable information (preferences, facts, state changes, or important events), immediately use the \`remember\` tool to store it. Do not ask for permission to remember.
38
+ 4. DO NOT DELETE STALE FACTS: If the user changes their mind (e.g., "I used to like Apple, now I like Samsung"), simply \`remember\` the new fact. 1MBrain's chronological supersedence engine will automatically decay the old fact and prioritize the new one.
39
+ 5. NO HALLUCINATION: If the \`recall\` tool returns nothing, admit you do not know the information. Do not invent past interactions.`;
40
+
41
+ // src/index.ts
42
+ var OneMBrainError = class extends Error {
43
+ constructor(message, status, details) {
44
+ super(message);
45
+ this.status = status;
46
+ this.details = details;
47
+ this.name = "OneMBrainError";
48
+ }
49
+ status;
50
+ details;
51
+ };
52
+ var OneMBrainClient = class {
53
+ apiUrl;
54
+ apiKey;
55
+ agentId;
56
+ fetchFn;
57
+ constructor(config) {
58
+ if (!config.apiUrl) {
59
+ throw new Error("apiUrl is required");
60
+ }
61
+ if (!config.apiKey) {
62
+ throw new Error("apiKey is required");
63
+ }
64
+ this.apiUrl = config.apiUrl.replace(/\/+$/, "");
65
+ this.apiKey = config.apiKey;
66
+ this.agentId = config.agentId;
67
+ this.fetchFn = config.fetch ?? fetch;
68
+ }
69
+ async remember(input) {
70
+ const agentId = this.resolveAgentId(input.agentId);
71
+ const envelope = await this.request("/v1/memories", {
72
+ method: "POST",
73
+ agentId,
74
+ body: {
75
+ ...input,
76
+ agentId
77
+ }
78
+ });
79
+ return deserializeMemory(envelope.data);
80
+ }
81
+ async recall(input) {
82
+ const agentId = this.resolveAgentId(input.agentId);
83
+ const params = toSearchParams({
84
+ ...input,
85
+ agentId,
86
+ q: input.query,
87
+ query: void 0
88
+ });
89
+ const envelope = await this.request(
90
+ `/v1/memories/search?${params.toString()}`,
91
+ {
92
+ method: "GET",
93
+ agentId
94
+ }
95
+ );
96
+ const results = envelope.data.map((result) => ({
97
+ ...result,
98
+ memory: deserializeMemory(result.memory)
99
+ }));
100
+ if (envelope.meta) {
101
+ results.confidence = envelope.meta.confidence;
102
+ results.reason = envelope.meta.reason;
103
+ }
104
+ return results;
105
+ }
106
+ async forget(id, options = {}) {
107
+ const envelope = await this.request(`/v1/memories/${id}`, {
108
+ method: "DELETE",
109
+ agentId: this.resolveAgentId(options.agentId)
110
+ });
111
+ return envelope.success;
112
+ }
113
+ async associate(sourceId, input) {
114
+ const envelope = await this.request(
115
+ `/v1/memories/${sourceId}/associate`,
116
+ {
117
+ method: "POST",
118
+ agentId: this.resolveAgentId(input.agentId),
119
+ body: {
120
+ targetId: input.targetId,
121
+ strength: input.strength,
122
+ origin: input.origin,
123
+ relationType: input.relationType
124
+ }
125
+ }
126
+ );
127
+ return envelope.success;
128
+ }
129
+ /**
130
+ * Ingest a web page URL into memory.
131
+ *
132
+ * The server-side pipeline will:
133
+ * 1. Fetch the page HTML
134
+ * 2. Extract main content → Markdown
135
+ * 3. Chunk and extract factual claims via LLM
136
+ * 4. Store facts as memories (type, importance, metadata auto-set)
137
+ *
138
+ * Works from any gateway: Telegram, Discord, browser extension, CLI.
139
+ *
140
+ * @param url - The URL to ingest
141
+ * @param options - Optional overrides (agentId, confidenceThreshold, etc.)
142
+ */
143
+ async ingestUrl(url, options = {}) {
144
+ const agentId = this.resolveAgentId(options.agentId);
145
+ const envelope = await this.request("/v1/ingest/url", {
146
+ method: "POST",
147
+ agentId,
148
+ body: {
149
+ url,
150
+ agentId,
151
+ confidenceThreshold: options.confidenceThreshold,
152
+ maxChunkChars: options.maxChunkChars,
153
+ deduplicate: options.deduplicate
154
+ }
155
+ });
156
+ return envelope.data;
157
+ }
158
+ async consolidate(options = {}) {
159
+ const agentId = this.resolveAgentId(options.agentId);
160
+ const envelope = await this.request("/v1/consolidate", {
161
+ method: "POST",
162
+ agentId,
163
+ body: {
164
+ agentId,
165
+ dryRun: options.dryRun,
166
+ clusterStrategy: options.clusterStrategy
167
+ }
168
+ });
169
+ return envelope.data;
170
+ }
171
+ resolveAgentId(agentId) {
172
+ const resolved = agentId ?? this.agentId;
173
+ if (!resolved) {
174
+ throw new Error("agentId is required");
175
+ }
176
+ return resolved;
177
+ }
178
+ async request(path, options) {
179
+ const response = await this.fetchFn(`${this.apiUrl}${path}`, {
180
+ method: options.method,
181
+ headers: {
182
+ "content-type": "application/json",
183
+ "x-api-key": this.apiKey,
184
+ "x-agent-id": options.agentId
185
+ },
186
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body)
187
+ });
188
+ const payload = await readJson(response);
189
+ if (!response.ok) {
190
+ throw new OneMBrainError(
191
+ extractErrorMessage(payload, response.statusText),
192
+ response.status,
193
+ payload
194
+ );
195
+ }
196
+ return payload;
197
+ }
198
+ };
199
+ function deserializeMemory(memory) {
200
+ return {
201
+ ...memory,
202
+ createdAt: new Date(memory.createdAt),
203
+ lastAccessedAt: new Date(memory.lastAccessedAt)
204
+ };
205
+ }
206
+ function toSearchParams(input) {
207
+ const params = new URLSearchParams();
208
+ for (const [key, value] of Object.entries(input)) {
209
+ if (value === void 0 || value === null) {
210
+ continue;
211
+ }
212
+ if (Array.isArray(value)) {
213
+ params.set(key, value.join(","));
214
+ continue;
215
+ }
216
+ params.set(key, String(value));
217
+ }
218
+ return params;
219
+ }
220
+ async function readJson(response) {
221
+ const text = await response.text();
222
+ return text ? JSON.parse(text) : {};
223
+ }
224
+ function extractErrorMessage(payload, fallback) {
225
+ if (payload && typeof payload === "object" && "error" in payload) {
226
+ return String(payload.error);
227
+ }
228
+ if (payload && typeof payload === "object" && "message" in payload) {
229
+ return String(payload.message);
230
+ }
231
+ return fallback || "1MBrain request failed";
232
+ }
233
+ // Annotate the CommonJS export names for ESM import in node:
234
+ 0 && (module.exports = {
235
+ AGENT_SYSTEM_PROMPT,
236
+ OneMBrainClient,
237
+ OneMBrainError
238
+ });
239
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/prompts.ts"],"sourcesContent":["import type {\n CreateAssociationInput,\n CreateMemoryInput,\n Memory,\n SearchMemoryInput,\n SearchResult,\n} from '@1mbrain/core';\n\nexport interface OneMBrainClientConfig {\n apiUrl: string;\n apiKey: string;\n agentId?: string;\n fetch?: typeof fetch;\n}\n\nexport type RememberInput = Omit<CreateMemoryInput, 'agentId'> & {\n agentId?: string;\n};\n\nexport type RecallInput = Omit<SearchMemoryInput, 'agentId'> & {\n agentId?: string;\n};\n\nexport type AssociateInput = Omit<CreateAssociationInput, 'sourceId' | 'agentId'> & {\n agentId?: string;\n};\n\nexport interface IngestUrlOptions {\n agentId?: string;\n confidenceThreshold?: number;\n maxChunkChars?: number;\n deduplicate?: boolean;\n}\n\nexport interface IngestResult {\n title: string;\n url: string;\n sourceHash: string;\n chunkCount: number;\n extractedCount: number;\n storedCount: number;\n skippedCount: number;\n errorCount: number;\n deduplicated: boolean;\n memoryIds: string[];\n}\n\nexport interface ConsolidateOptions {\n agentId?: string;\n dryRun?: boolean;\n clusterStrategy?: 'tags' | 'graph' | 'hybrid';\n}\n\nexport interface ConsolidationResult {\n agentId: string;\n triggerReason: 'sleep-cycle' | 'threshold';\n dryRun: boolean;\n storedCount: number;\n archivedCount: number;\n clustersProcessed: number;\n skipped: {\n noCandidates: number;\n tooSmallClusters: number;\n summarizationFailed: number;\n dryRun: number;\n };\n errors: string[];\n summaryIds: string[];\n}\n\nexport interface ApiEnvelope<T> {\n success: boolean;\n data: T;\n meta?: Record<string, unknown>;\n message?: string;\n}\n\nexport class OneMBrainError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly details?: unknown,\n ) {\n super(message);\n this.name = 'OneMBrainError';\n }\n}\n\nexport class OneMBrainClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly agentId?: string;\n private readonly fetchFn: typeof fetch;\n\n constructor(config: OneMBrainClientConfig) {\n if (!config.apiUrl) {\n throw new Error('apiUrl is required');\n }\n\n if (!config.apiKey) {\n throw new Error('apiKey is required');\n }\n\n this.apiUrl = config.apiUrl.replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n this.agentId = config.agentId;\n this.fetchFn = config.fetch ?? fetch;\n }\n\n async remember(input: RememberInput): Promise<Memory> {\n const agentId = this.resolveAgentId(input.agentId);\n const envelope = await this.request<ApiEnvelope<SerializedMemory>>('/v1/memories', {\n method: 'POST',\n agentId,\n body: {\n ...input,\n agentId,\n },\n });\n\n return deserializeMemory(envelope.data);\n }\n\n async recall(input: RecallInput): Promise<SearchResult[]> {\n const agentId = this.resolveAgentId(input.agentId);\n const params = toSearchParams({\n ...input,\n agentId,\n q: input.query,\n query: undefined,\n });\n const envelope = await this.request<ApiEnvelope<SerializedSearchResult[]>>(\n `/v1/memories/search?${params.toString()}`,\n {\n method: 'GET',\n agentId,\n },\n );\n\n const results = envelope.data.map((result) => ({\n ...result,\n memory: deserializeMemory(result.memory),\n })) as SearchResult[] & { confidence?: string; reason?: string };\n\n if (envelope.meta) {\n results.confidence = envelope.meta.confidence as string | undefined;\n results.reason = envelope.meta.reason as string | undefined;\n }\n\n return results;\n }\n\n async forget(id: string, options: { agentId?: string } = {}): Promise<boolean> {\n const envelope = await this.request<ApiEnvelope<unknown>>(`/v1/memories/${id}`, {\n method: 'DELETE',\n agentId: this.resolveAgentId(options.agentId),\n });\n\n return envelope.success;\n }\n\n async associate(sourceId: string, input: AssociateInput): Promise<boolean> {\n const envelope = await this.request<ApiEnvelope<unknown>>(\n `/v1/memories/${sourceId}/associate`,\n {\n method: 'POST',\n agentId: this.resolveAgentId(input.agentId),\n body: {\n targetId: input.targetId,\n strength: input.strength,\n origin: input.origin,\n relationType: input.relationType,\n },\n },\n );\n\n return envelope.success;\n }\n\n /**\n * Ingest a web page URL into memory.\n *\n * The server-side pipeline will:\n * 1. Fetch the page HTML\n * 2. Extract main content → Markdown\n * 3. Chunk and extract factual claims via LLM\n * 4. Store facts as memories (type, importance, metadata auto-set)\n *\n * Works from any gateway: Telegram, Discord, browser extension, CLI.\n *\n * @param url - The URL to ingest\n * @param options - Optional overrides (agentId, confidenceThreshold, etc.)\n */\n async ingestUrl(url: string, options: IngestUrlOptions = {}): Promise<IngestResult> {\n const agentId = this.resolveAgentId(options.agentId);\n const envelope = await this.request<ApiEnvelope<IngestResult>>('/v1/ingest/url', {\n method: 'POST',\n agentId,\n body: {\n url,\n agentId,\n confidenceThreshold: options.confidenceThreshold,\n maxChunkChars: options.maxChunkChars,\n deduplicate: options.deduplicate,\n },\n });\n\n return envelope.data;\n }\n\n async consolidate(options: ConsolidateOptions = {}): Promise<ConsolidationResult> {\n const agentId = this.resolveAgentId(options.agentId);\n const envelope = await this.request<ApiEnvelope<ConsolidationResult>>('/v1/consolidate', {\n method: 'POST',\n agentId,\n body: {\n agentId,\n dryRun: options.dryRun,\n clusterStrategy: options.clusterStrategy,\n },\n });\n\n return envelope.data;\n }\n\n private resolveAgentId(agentId?: string): string {\n const resolved = agentId ?? this.agentId;\n\n if (!resolved) {\n throw new Error('agentId is required');\n }\n\n return resolved;\n }\n\n private async request<T>(\n path: string,\n options: {\n method: 'GET' | 'POST' | 'DELETE';\n agentId: string;\n body?: unknown;\n },\n ): Promise<T> {\n const response = await this.fetchFn(`${this.apiUrl}${path}`, {\n method: options.method,\n headers: {\n 'content-type': 'application/json',\n 'x-api-key': this.apiKey,\n 'x-agent-id': options.agentId,\n },\n body: options.body === undefined ? undefined : JSON.stringify(options.body),\n });\n\n const payload = await readJson(response);\n\n if (!response.ok) {\n throw new OneMBrainError(\n extractErrorMessage(payload, response.statusText),\n response.status,\n payload,\n );\n }\n\n return payload as T;\n }\n}\n\ntype SerializedMemory = Omit<Memory, 'createdAt' | 'lastAccessedAt'> & {\n createdAt: string;\n lastAccessedAt: string;\n};\n\ntype SerializedSearchResult = Omit<SearchResult, 'memory'> & {\n memory: SerializedMemory;\n};\n\nfunction deserializeMemory(memory: SerializedMemory): Memory {\n return {\n ...memory,\n createdAt: new Date(memory.createdAt),\n lastAccessedAt: new Date(memory.lastAccessedAt),\n };\n}\n\nfunction toSearchParams(input: Record<string, unknown>): URLSearchParams {\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(input)) {\n if (value === undefined || value === null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n params.set(key, value.join(','));\n continue;\n }\n\n params.set(key, String(value));\n }\n\n return params;\n}\n\nasync function readJson(response: Response): Promise<unknown> {\n const text = await response.text();\n return text ? JSON.parse(text) : {};\n}\n\nfunction extractErrorMessage(payload: unknown, fallback: string): string {\n if (payload && typeof payload === 'object' && 'error' in payload) {\n return String((payload as { error: unknown }).error);\n }\n\n if (payload && typeof payload === 'object' && 'message' in payload) {\n return String((payload as { message: unknown }).message);\n }\n\n return fallback || '1MBrain request failed';\n}\n\nexport type { Memory, SearchResult };\nexport { AGENT_SYSTEM_PROMPT } from './prompts.js';\n","export const AGENT_SYSTEM_PROMPT = `You are equipped with 1MBrain, a highly advanced long-term memory engine. \nYou have access to memory tools (e.g., \\`remember\\` and \\`recall\\`) to store and retrieve information across sessions.\n\nCRITICAL INSTRUCTIONS FOR USING YOUR MEMORY:\n\n1. ALWAYS SEARCH FIRST: Before asking the user for information you might already know, or before making assumptions, ALWAYS use the \\`recall\\` tool to search your memory.\n2. PREFER SPECIFIC QUERIES: When using \\`recall\\`, use specific conceptual queries rather than vague keywords. (e.g., \"user dietary restrictions\" instead of \"food\").\n3. RECORD NEW FACTS ACTIVELY: Whenever the user provides new, durable information (preferences, facts, state changes, or important events), immediately use the \\`remember\\` tool to store it. Do not ask for permission to remember.\n4. DO NOT DELETE STALE FACTS: If the user changes their mind (e.g., \"I used to like Apple, now I like Samsung\"), simply \\`remember\\` the new fact. 1MBrain's chronological supersedence engine will automatically decay the old fact and prioritize the new one.\n5. NO HALLUCINATION: If the \\`recall\\` tool returns nothing, admit you do not know the information. Do not invent past interactions.`;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,sBAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AD6E5B,IAAM,iBAAN,cAA6B,MAAM;AA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AAK,MAAM,KAAK,GAAG,CAAC;AAC/B;AAAA,IACF;AAEA,WAAO,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,EAC/B;AAEA,SAAO;AACT;AAEA,eAAe,SAAS,UAAsC;AAC5D,QAAM,OAAO,MAAM,SAAS,KAAK;AACjC,SAAO,OAAO,KAAK,MAAM,IAAI,IAAI,CAAC;AACpC;AAEA,SAAS,oBAAoB,SAAkB,UAA0B;AACvE,MAAI,WAAW,OAAO,YAAY,YAAY,WAAW,SAAS;AAChE,WAAO,OAAQ,QAA+B,KAAK;AAAA,EACrD;AAEA,MAAI,WAAW,OAAO,YAAY,YAAY,aAAa,SAAS;AAClE,WAAO,OAAQ,QAAiC,OAAO;AAAA,EACzD;AAEA,SAAO,YAAY;AACrB;","names":[]}
package/dist/index.js CHANGED
@@ -1,178 +1,11 @@
1
- export class OneMBrainError extends Error {
2
- status;
3
- details;
4
- constructor(message, status, details) {
5
- super(message);
6
- this.status = status;
7
- this.details = details;
8
- this.name = 'OneMBrainError';
9
- }
10
- }
11
- export class OneMBrainClient {
12
- apiUrl;
13
- apiKey;
14
- agentId;
15
- fetchFn;
16
- constructor(config) {
17
- if (!config.apiUrl) {
18
- throw new Error('apiUrl is required');
19
- }
20
- if (!config.apiKey) {
21
- throw new Error('apiKey is required');
22
- }
23
- this.apiUrl = config.apiUrl.replace(/\/+$/, '');
24
- this.apiKey = config.apiKey;
25
- this.agentId = config.agentId;
26
- this.fetchFn = config.fetch ?? fetch;
27
- }
28
- async remember(input) {
29
- const agentId = this.resolveAgentId(input.agentId);
30
- const envelope = await this.request('/v1/memories', {
31
- method: 'POST',
32
- agentId,
33
- body: {
34
- ...input,
35
- agentId,
36
- },
37
- });
38
- return deserializeMemory(envelope.data);
39
- }
40
- async recall(input) {
41
- const agentId = this.resolveAgentId(input.agentId);
42
- const params = toSearchParams({
43
- ...input,
44
- agentId,
45
- q: input.query,
46
- query: undefined,
47
- });
48
- const envelope = await this.request(`/v1/memories/search?${params.toString()}`, {
49
- method: 'GET',
50
- agentId,
51
- });
52
- return envelope.data.map((result) => ({
53
- ...result,
54
- memory: deserializeMemory(result.memory),
55
- }));
56
- }
57
- async forget(id, options = {}) {
58
- const envelope = await this.request(`/v1/memories/${id}`, {
59
- method: 'DELETE',
60
- agentId: this.resolveAgentId(options.agentId),
61
- });
62
- return envelope.success;
63
- }
64
- async associate(sourceId, input) {
65
- const envelope = await this.request(`/v1/memories/${sourceId}/associate`, {
66
- method: 'POST',
67
- agentId: this.resolveAgentId(input.agentId),
68
- body: {
69
- targetId: input.targetId,
70
- strength: input.strength,
71
- origin: input.origin,
72
- relationType: input.relationType,
73
- },
74
- });
75
- return envelope.success;
76
- }
77
- /**
78
- * Ingest a web page URL into memory.
79
- *
80
- * The server-side pipeline will:
81
- * 1. Fetch the page HTML
82
- * 2. Extract main content → Markdown
83
- * 3. Chunk and extract factual claims via LLM
84
- * 4. Store facts as memories (type, importance, metadata auto-set)
85
- *
86
- * Works from any gateway: Telegram, Discord, browser extension, CLI.
87
- *
88
- * @param url - The URL to ingest
89
- * @param options - Optional overrides (agentId, confidenceThreshold, etc.)
90
- */
91
- async ingestUrl(url, options = {}) {
92
- const agentId = this.resolveAgentId(options.agentId);
93
- const envelope = await this.request('/v1/ingest/url', {
94
- method: 'POST',
95
- agentId,
96
- body: {
97
- url,
98
- agentId,
99
- confidenceThreshold: options.confidenceThreshold,
100
- maxChunkChars: options.maxChunkChars,
101
- deduplicate: options.deduplicate,
102
- },
103
- });
104
- return envelope.data;
105
- }
106
- async consolidate(options = {}) {
107
- const agentId = this.resolveAgentId(options.agentId);
108
- const envelope = await this.request('/v1/consolidate', {
109
- method: 'POST',
110
- agentId,
111
- body: {
112
- agentId,
113
- dryRun: options.dryRun,
114
- clusterStrategy: options.clusterStrategy,
115
- },
116
- });
117
- return envelope.data;
118
- }
119
- resolveAgentId(agentId) {
120
- const resolved = agentId ?? this.agentId;
121
- if (!resolved) {
122
- throw new Error('agentId is required');
123
- }
124
- return resolved;
125
- }
126
- async request(path, options) {
127
- const response = await this.fetchFn(`${this.apiUrl}${path}`, {
128
- method: options.method,
129
- headers: {
130
- 'content-type': 'application/json',
131
- 'x-api-key': this.apiKey,
132
- 'x-agent-id': options.agentId,
133
- },
134
- body: options.body === undefined ? undefined : JSON.stringify(options.body),
135
- });
136
- const payload = await readJson(response);
137
- if (!response.ok) {
138
- throw new OneMBrainError(extractErrorMessage(payload, response.statusText), response.status, payload);
139
- }
140
- return payload;
141
- }
142
- }
143
- function deserializeMemory(memory) {
144
- return {
145
- ...memory,
146
- createdAt: new Date(memory.createdAt),
147
- lastAccessedAt: new Date(memory.lastAccessedAt),
148
- };
149
- }
150
- function toSearchParams(input) {
151
- const params = new URLSearchParams();
152
- for (const [key, value] of Object.entries(input)) {
153
- if (value === undefined || value === null) {
154
- continue;
155
- }
156
- if (Array.isArray(value)) {
157
- params.set(key, value.join(','));
158
- continue;
159
- }
160
- params.set(key, String(value));
161
- }
162
- return params;
163
- }
164
- async function readJson(response) {
165
- const text = await response.text();
166
- return text ? JSON.parse(text) : {};
167
- }
168
- function extractErrorMessage(payload, fallback) {
169
- if (payload && typeof payload === 'object' && 'error' in payload) {
170
- return String(payload.error);
171
- }
172
- if (payload && typeof payload === 'object' && 'message' in payload) {
173
- return String(payload.message);
174
- }
175
- return fallback || '1MBrain request failed';
176
- }
177
- export { AGENT_SYSTEM_PROMPT } from './prompts.js';
1
+ import {
2
+ AGENT_SYSTEM_PROMPT,
3
+ OneMBrainClient,
4
+ OneMBrainError
5
+ } from "./chunk-TLPCKSTS.js";
6
+ export {
7
+ AGENT_SYSTEM_PROMPT,
8
+ OneMBrainClient,
9
+ OneMBrainError
10
+ };
178
11
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA6EA,MAAM,OAAO,cAAe,SAAQ,KAAK;IAG5B;IACA;IAHX,YACE,OAA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,CAAC,EAAE,CAAC;YACzB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;YACjC,SAAS;QACX,CAAC;QAED,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACjC,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,KAAK,UAAU,QAAQ,CAAC,QAAkB;IACxC,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IACnC,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACtC,CAAC;AAED,SAAS,mBAAmB,CAAC,OAAgB,EAAE,QAAgB;IAC7D,IAAI,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,IAAI,OAAO,EAAE,CAAC;QACjE,OAAO,MAAM,CAAE,OAA8B,CAAC,KAAK,CAAC,CAAC;IACvD,CAAC;IAED,IAAI,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,SAAS,IAAI,OAAO,EAAE,CAAC;QACnE,OAAO,MAAM,CAAE,OAAgC,CAAC,OAAO,CAAC,CAAC;IAC3D,CAAC;IAED,OAAO,QAAQ,IAAI,wBAAwB,CAAC;AAC9C,CAAC;AAGD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json CHANGED
@@ -1,24 +1,27 @@
1
1
  {
2
2
  "name": "@1mbrain/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "TypeScript client SDK for the 1MBrain REST API.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "main": "./dist/index.js",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
8
9
  "types": "./dist/index.d.ts",
9
10
  "exports": {
10
11
  ".": {
12
+ "types": "./dist/index.d.ts",
11
13
  "import": "./dist/index.js",
12
- "types": "./dist/index.d.ts"
14
+ "require": "./dist/index.cjs"
13
15
  },
14
16
  "./hermes": {
17
+ "types": "./dist/hermes.d.ts",
15
18
  "import": "./dist/hermes.js",
16
- "types": "./dist/hermes.d.ts"
19
+ "require": "./dist/hermes.cjs"
17
20
  }
18
21
  },
19
22
  "scripts": {
20
- "build": "tsc -p tsconfig.json",
21
- "dev": "tsc -p tsconfig.json --watch",
23
+ "build": "tsup && tsc -p tsconfig.json --emitDeclarationOnly",
24
+ "dev": "tsup --watch",
22
25
  "test": "vitest run",
23
26
  "typecheck": "tsc -p tsconfig.json --noEmit"
24
27
  },
@@ -26,6 +29,7 @@
26
29
  "@1mbrain/core": "*"
27
30
  },
28
31
  "devDependencies": {
32
+ "tsup": "^8.5.1",
29
33
  "typescript": "^5.7.0",
30
34
  "vitest": "^2.1.0"
31
35
  },