@localmem/memory 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ localmem Memory API SDK
2
+ Copyright 2026 Vijay Yadav, doing business as localmem.org.
3
+
4
+ Licensed under the Apache License, Version 2.0 (LICENSE). "localmem" is a
5
+ name of localmem.org; the licence grants no right to use it (section 6).
package/README.md CHANGED
@@ -1,3 +1,20 @@
1
- # Temporary Holding Version
1
+ # @localmem/memory
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The localmem Memory API from TypeScript: memory of each of your customers,
4
+ with the source and date of every fact. Server-side only.
5
+
6
+ ```sh
7
+ npx @localmem/memory login # pair this terminal: approve the code in the browser
8
+ npm install @localmem/memory
9
+ ```
10
+
11
+ ```ts
12
+ import { Memory } from "@localmem/memory";
13
+
14
+ const lm = new Memory(); // reads LOCALMEM_PROJECT, LOCALMEM_KEY_ID, LOCALMEM_KEY_SECRET
15
+ const { tenant } = await lm.customers.create("cust-42");
16
+ await lm.documents.send(tenant, { text: "Ada Byron joined Acme on 3 March." });
17
+ console.log((await lm.recall(tenant, { entity: "Ada Byron" })).facts);
18
+ ```
19
+
20
+ Docs: https://localmem.org/docs/memory-api/sdks · Support: support@localmem.org
package/dist/bin.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ // The `npx @localmem/memory` entry point (specs/037 R53).
3
+ import { main } from "./cli.js";
4
+ main().catch((e) => {
5
+ console.error(e instanceof Error ? e.message : e);
6
+ process.exit(1);
7
+ });
package/dist/cli.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ export interface Args {
2
+ command: string | undefined;
3
+ envFile: string;
4
+ device: string;
5
+ api: string;
6
+ browser: boolean;
7
+ }
8
+ export declare function parse(argv: string[]): Args;
9
+ /** `text` with each of `vars` set: an existing line replaced, a new one appended. */
10
+ export declare function withVars(text: string, vars: Record<string, string>): string;
11
+ /**
12
+ * Keeps `file` out of git: nothing when git already ignores it, else its
13
+ * name added to the .gitignore beside it. Answers what it did.
14
+ */
15
+ export declare function keepOutOfGit(file: string): string;
16
+ export interface Io {
17
+ log: (line: string) => void;
18
+ fetch: typeof fetch;
19
+ sleep: (ms: number) => Promise<void>;
20
+ open: (url: string) => void;
21
+ }
22
+ /** The login flow; the exit code. */
23
+ export declare function login(a: Args, io: Io): Promise<number>;
24
+ /** The command line: `login`, or this help. */
25
+ export declare function main(): Promise<void>;
package/dist/cli.js ADDED
@@ -0,0 +1,186 @@
1
+ /**
2
+ * `npx @localmem/memory login` (specs/037 R53): pairs this terminal with a
3
+ * project. It asks for a pairing, prints the code, opens the approval page,
4
+ * and polls with its device secret until the key is handed to it once; then
5
+ * writes the three variables into .env (or --env-file) and keeps that file
6
+ * out of git. The secret is never printed.
7
+ */
8
+ import { spawn, spawnSync } from "node:child_process";
9
+ import { existsSync, readFileSync, writeFileSync, appendFileSync, chmodSync } from "node:fs";
10
+ import { hostname } from "node:os";
11
+ import { basename, dirname, resolve } from "node:path";
12
+ import { DEFAULT_API } from "./index.js";
13
+ const HELP = `Usage: npx @localmem/memory login [--env-file .env] [--device NAME] [--api URL] [--no-browser]
14
+
15
+ Pairs this terminal with a localmem project: approve the code it prints in
16
+ the browser, and a test key is written to your .env file.`;
17
+ export function parse(argv) {
18
+ const a = {
19
+ command: undefined,
20
+ envFile: ".env",
21
+ device: hostname().slice(0, 60) || "a terminal",
22
+ api: (process.env.LOCALMEM_API_URL ?? DEFAULT_API).replace(/\/+$/, ""),
23
+ browser: true,
24
+ };
25
+ for (let i = 0; i < argv.length; i++) {
26
+ const v = argv[i];
27
+ const next = () => {
28
+ const n = argv[++i];
29
+ if (n === undefined)
30
+ throw new Error(`${v} needs a value`);
31
+ return n;
32
+ };
33
+ if (v === "--env-file")
34
+ a.envFile = next();
35
+ else if (v === "--device")
36
+ a.device = next();
37
+ else if (v === "--api")
38
+ a.api = next().replace(/\/+$/, "");
39
+ else if (v === "--no-browser")
40
+ a.browser = false;
41
+ else if (v === "-h" || v === "--help")
42
+ a.command = "help";
43
+ else if (!a.command)
44
+ a.command = v;
45
+ else
46
+ throw new Error(`unknown argument ${v}`);
47
+ }
48
+ return a;
49
+ }
50
+ /** `text` with each of `vars` set: an existing line replaced, a new one appended. */
51
+ export function withVars(text, vars) {
52
+ const lines = text.length ? text.replace(/\n$/, "").split("\n") : [];
53
+ for (const [k, v] of Object.entries(vars)) {
54
+ const at = lines.findIndex((l) => new RegExp(`^\\s*(export\\s+)?${k}\\s*=`).test(l));
55
+ if (at >= 0)
56
+ lines[at] = `${k}=${v}`;
57
+ else
58
+ lines.push(`${k}=${v}`);
59
+ }
60
+ return `${lines.join("\n")}\n`;
61
+ }
62
+ /**
63
+ * Keeps `file` out of git: nothing when git already ignores it, else its
64
+ * name added to the .gitignore beside it. Answers what it did.
65
+ */
66
+ export function keepOutOfGit(file) {
67
+ const dir = dirname(file);
68
+ const name = basename(file);
69
+ const checked = spawnSync("git", ["check-ignore", "-q", name], { cwd: dir });
70
+ if (checked.status === 0)
71
+ return `${name} is already ignored by git.`;
72
+ const ignore = resolve(dir, ".gitignore");
73
+ const have = existsSync(ignore) ? readFileSync(ignore, "utf8") : "";
74
+ if (checked.status !== 1 && have.split("\n").some((l) => l.trim() === name || l.trim() === `/${name}`)) {
75
+ return `${name} is already in .gitignore.`;
76
+ }
77
+ appendFileSync(ignore, `${have && !have.endsWith("\n") ? "\n" : ""}${name}\n`);
78
+ return `Added ${name} to .gitignore, so the secret is never committed.`;
79
+ }
80
+ function open(url) {
81
+ const [cmd, args] = process.platform === "darwin"
82
+ ? ["open", [url]]
83
+ : process.platform === "win32"
84
+ ? ["cmd", ["/c", "start", "", url]]
85
+ : ["xdg-open", [url]];
86
+ try {
87
+ spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => { }).unref();
88
+ }
89
+ catch {
90
+ // The link is printed; opening it is a courtesy.
91
+ }
92
+ }
93
+ async function post(url, body, f) {
94
+ const res = await f(url, {
95
+ method: "POST",
96
+ headers: { "content-type": "application/json" },
97
+ body: JSON.stringify(body),
98
+ signal: AbortSignal.timeout(30_000),
99
+ });
100
+ const text = await res.text();
101
+ let parsed = {};
102
+ try {
103
+ parsed = text ? JSON.parse(text) : {};
104
+ }
105
+ catch {
106
+ parsed = { message: text.slice(0, 200) };
107
+ }
108
+ return { status: res.status, body: parsed };
109
+ }
110
+ /** The login flow; the exit code. */
111
+ export async function login(a, io) {
112
+ const opened = await post(`${a.api}/v1/pair`, { device: a.device }, io.fetch);
113
+ if (opened.status !== 201) {
114
+ io.log(`Could not start pairing: ${opened.body.message ?? `localmem answered ${opened.status}`}`);
115
+ return 1;
116
+ }
117
+ const { pairing, device_secret, code, url } = opened.body;
118
+ const interval = Number(opened.body.interval ?? 3) * 1000;
119
+ const until = Date.now() + Number(opened.body.expires_in ?? 600) * 1000;
120
+ io.log(`Your code: ${code}`);
121
+ io.log(`Approve it at ${url}`);
122
+ if (a.browser)
123
+ io.open(url);
124
+ io.log("Waiting for approval…");
125
+ for (;;) {
126
+ await io.sleep(interval);
127
+ if (Date.now() > until) {
128
+ io.log("The code expired before it was approved. Run `npx @localmem/memory login` again.");
129
+ return 1;
130
+ }
131
+ let said;
132
+ try {
133
+ said = await post(`${a.api}/v1/pair/${encodeURIComponent(pairing)}/token`, { device_secret }, io.fetch);
134
+ }
135
+ catch {
136
+ continue;
137
+ }
138
+ if (said.status === 202)
139
+ continue;
140
+ if (said.status === 429 || said.status >= 500)
141
+ continue;
142
+ if (said.status !== 200) {
143
+ io.log(String(said.body.message ?? "This pairing has ended. Run `npx @localmem/memory login` again."));
144
+ return 1;
145
+ }
146
+ const { project, key_id, secret } = said.body;
147
+ const file = resolve(a.envFile);
148
+ const vars = {
149
+ LOCALMEM_PROJECT: project,
150
+ LOCALMEM_KEY_ID: key_id,
151
+ LOCALMEM_KEY_SECRET: secret,
152
+ };
153
+ if (a.api !== DEFAULT_API)
154
+ vars.LOCALMEM_API_URL = a.api;
155
+ const existed = existsSync(file);
156
+ writeFileSync(file, withVars(existed ? readFileSync(file, "utf8") : "", vars));
157
+ if (!existed)
158
+ chmodSync(file, 0o600);
159
+ io.log(`Paired with project ${project}: a test key, ${key_id}.`);
160
+ io.log(`Wrote ${Object.keys(vars).join(", ")} to ${a.envFile}. The secret is not shown here.`);
161
+ io.log(keepOutOfGit(file));
162
+ return 0;
163
+ }
164
+ }
165
+ /** The command line: `login`, or this help. */
166
+ export async function main() {
167
+ let a;
168
+ try {
169
+ a = parse(process.argv.slice(2));
170
+ }
171
+ catch (e) {
172
+ console.error(`${e.message}\n\n${HELP}`);
173
+ process.exit(2);
174
+ }
175
+ if (a.command !== "login") {
176
+ console.log(HELP);
177
+ process.exit(a.command === "help" || a.command === undefined ? 0 : 2);
178
+ }
179
+ const code = await login(a, {
180
+ log: (l) => console.log(l),
181
+ fetch,
182
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
183
+ open,
184
+ });
185
+ process.exit(code);
186
+ }
@@ -0,0 +1,125 @@
1
+ export declare const DEFAULT_API = "https://api.localmem.org";
2
+ /** The longest Retry-After waited for; past it the error is raised at once. */
3
+ export declare const MAX_WAIT_MS = 60000;
4
+ export interface Options {
5
+ project?: string;
6
+ keyId?: string;
7
+ secret?: string;
8
+ /** Default LOCALMEM_API_URL, else https://api.localmem.org. */
9
+ baseUrl?: string;
10
+ /** Per attempt. Default 120 s: an inline document may take 90 s. */
11
+ timeoutMs?: number;
12
+ /** Retries after the first attempt. Default 3. */
13
+ maxRetries?: number;
14
+ fetch?: typeof fetch;
15
+ /** For tests: how a retry waits. */
16
+ sleep?: (ms: number) => Promise<void>;
17
+ }
18
+ /** An answer that is not a success: the gateway's code and its words. */
19
+ export declare class LocalmemError extends Error {
20
+ readonly status: number;
21
+ /** The gateway's code to act on, e.g. `monthly_limit`, `no_tenant`. */
22
+ readonly error: string;
23
+ readonly requestId: string | null;
24
+ /** Seconds, when the gateway said when to try again. */
25
+ readonly retryAfter: number | null;
26
+ /** The whole answer, with fields such as `resets_at`. */
27
+ readonly body: Record<string, unknown>;
28
+ constructor(status: number, body: Record<string, unknown>, requestId: string | null, retryAfter: number | null);
29
+ }
30
+ type Json = Record<string, unknown>;
31
+ export interface Customer {
32
+ tenant: string;
33
+ external_ref: string;
34
+ phi: boolean;
35
+ status: string;
36
+ created_at: string;
37
+ [k: string]: unknown;
38
+ }
39
+ export interface DocumentIn {
40
+ text: string;
41
+ title?: string;
42
+ /** RFC 3339: when the document was true. */
43
+ as_of?: string;
44
+ tags?: Record<string, string>;
45
+ external_ref?: string;
46
+ }
47
+ /** The hex HMAC-SHA256 the gateway checks: `timestamp.METHOD.path.body`, the path without its query. */
48
+ export declare function sign(secret: string, timestamp: string, method: string, path: string, body: string): string;
49
+ export declare class Memory {
50
+ #private;
51
+ readonly project: string;
52
+ readonly keyId: string;
53
+ readonly baseUrl: string;
54
+ constructor(options?: Options);
55
+ /** Your customers: each its own memory (033 Part A). */
56
+ readonly customers: {
57
+ /** Made once per `external_ref`: the same one again answers the same customer. */
58
+ create: (externalRef: string, options?: {
59
+ phi?: boolean;
60
+ }) => Promise<Customer>;
61
+ list: () => Promise<{
62
+ tenants: Customer[];
63
+ }>;
64
+ get: (tenant: string) => Promise<Customer>;
65
+ /** Access stops at once; see the data contract for what follows. */
66
+ delete: (tenant: string) => Promise<Json>;
67
+ };
68
+ /** Documents, read by a model into facts (033 R15). */
69
+ readonly documents: {
70
+ /**
71
+ * Sends a document, with an Idempotency-Key (yours, or one made here)
72
+ * so a retry never reads it twice. Answers the written facts, or
73
+ * `{ status, follow }` when it is read in the background: pass that to
74
+ * `documents.wait`.
75
+ */
76
+ send: (tenant: string, doc: DocumentIn, options?: {
77
+ idempotencyKey?: string;
78
+ }) => Promise<Json>;
79
+ get: (tenant: string, documentId: string) => Promise<Json>;
80
+ /** Polls a background document until it is written or failed. */
81
+ wait: (tenant: string, documentId: string, options?: {
82
+ timeoutMs?: number;
83
+ everyMs?: number;
84
+ }) => Promise<Json>;
85
+ };
86
+ /** Facts you extracted yourself: nothing goes to a model. */
87
+ facts(tenant: string, body: Json): Promise<Json>;
88
+ write(tenant: string, body: {
89
+ content: string;
90
+ [k: string]: unknown;
91
+ }): Promise<Json>;
92
+ search(tenant: string, body: {
93
+ query: string;
94
+ k?: number;
95
+ at_time?: string;
96
+ [k: string]: unknown;
97
+ }): Promise<Json>;
98
+ /** What is known about `entity`, now or at `at_time`. */
99
+ recall(tenant: string, body: {
100
+ entity: string;
101
+ at_time?: string;
102
+ [k: string]: unknown;
103
+ }): Promise<Json>;
104
+ get(tenant: string, body: {
105
+ event_id: string;
106
+ }): Promise<Json>;
107
+ profile(tenant: string, body?: {
108
+ scope?: string;
109
+ tags?: Record<string, string>;
110
+ }): Promise<Json>;
111
+ /** Hides it from answers from now on; it does not destroy it. */
112
+ forget(tenant: string, body: {
113
+ target_id: string;
114
+ }): Promise<Json>;
115
+ /** One entry per customer and day, both dates included (YYYY-MM-DD). */
116
+ usage(range?: {
117
+ from?: string;
118
+ to?: string;
119
+ }): Promise<{
120
+ from: string;
121
+ to: string;
122
+ usage: Json[];
123
+ }>;
124
+ }
125
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * @localmem/memory: the localmem Memory API from TypeScript (specs/037 R55).
3
+ *
4
+ * Reads LOCALMEM_PROJECT, LOCALMEM_KEY_ID and LOCALMEM_KEY_SECRET (written by
5
+ * `npx @localmem/memory login`), signs every request as the gateway checks
6
+ * it (033 R2), sends an Idempotency-Key with every document and retries it
7
+ * on a timeout or a 5xx, honours Retry-After, and raises LocalmemError with
8
+ * the gateway's { error, message }. It covers the Memory API and nothing
9
+ * else. Server-side only: the secret must never reach a browser.
10
+ */
11
+ import { createHmac, randomUUID } from "node:crypto";
12
+ export const DEFAULT_API = "https://api.localmem.org";
13
+ /** The longest Retry-After waited for; past it the error is raised at once. */
14
+ export const MAX_WAIT_MS = 60_000;
15
+ /** An answer that is not a success: the gateway's code and its words. */
16
+ export class LocalmemError extends Error {
17
+ status;
18
+ /** The gateway's code to act on, e.g. `monthly_limit`, `no_tenant`. */
19
+ error;
20
+ requestId;
21
+ /** Seconds, when the gateway said when to try again. */
22
+ retryAfter;
23
+ /** The whole answer, with fields such as `resets_at`. */
24
+ body;
25
+ constructor(status, body, requestId, retryAfter) {
26
+ const code = typeof body.error === "string" ? body.error : `http_${status}`;
27
+ super(typeof body.message === "string" ? body.message : `localmem answered ${status}`);
28
+ this.name = "LocalmemError";
29
+ this.status = status;
30
+ this.error = code;
31
+ this.requestId = requestId;
32
+ this.retryAfter = retryAfter;
33
+ this.body = body;
34
+ }
35
+ }
36
+ /** The hex HMAC-SHA256 the gateway checks: `timestamp.METHOD.path.body`, the path without its query. */
37
+ export function sign(secret, timestamp, method, path, body) {
38
+ const bare = path.split("?")[0];
39
+ return createHmac("sha256", secret).update(`${timestamp}.${method}.${bare}.${body}`).digest("hex");
40
+ }
41
+ function env(name) {
42
+ const v = typeof process !== "undefined" ? process.env[name] : undefined;
43
+ return v && v.trim() ? v.trim() : undefined;
44
+ }
45
+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
46
+ export class Memory {
47
+ project;
48
+ keyId;
49
+ baseUrl;
50
+ #secret;
51
+ #timeoutMs;
52
+ #maxRetries;
53
+ #fetch;
54
+ #sleep;
55
+ constructor(options = {}) {
56
+ const project = options.project ?? env("LOCALMEM_PROJECT");
57
+ const keyId = options.keyId ?? env("LOCALMEM_KEY_ID");
58
+ const secret = options.secret ?? env("LOCALMEM_KEY_SECRET");
59
+ const missing = [
60
+ !project && "LOCALMEM_PROJECT",
61
+ !keyId && "LOCALMEM_KEY_ID",
62
+ !secret && "LOCALMEM_KEY_SECRET",
63
+ ].filter(Boolean);
64
+ if (missing.length) {
65
+ throw new Error(`Set ${missing.join(", ")}: run \`npx @localmem/memory login\`, or pass them to new Memory().`);
66
+ }
67
+ this.project = project;
68
+ this.keyId = keyId;
69
+ this.#secret = secret;
70
+ this.baseUrl = (options.baseUrl ?? env("LOCALMEM_API_URL") ?? DEFAULT_API).replace(/\/+$/, "");
71
+ this.#timeoutMs = options.timeoutMs ?? 120_000;
72
+ this.#maxRetries = options.maxRetries ?? 3;
73
+ this.#fetch = options.fetch ?? fetch;
74
+ this.#sleep = options.sleep ?? wait;
75
+ }
76
+ /** Your customers: each its own memory (033 Part A). */
77
+ customers = {
78
+ /** Made once per `external_ref`: the same one again answers the same customer. */
79
+ create: (externalRef, options = {}) => this.#call("POST", "/v1/partner/tenants", { body: { external_ref: externalRef, ...options } }),
80
+ list: () => this.#call("GET", "/v1/partner/tenants"),
81
+ get: (tenant) => this.#call("GET", `/v1/partner/tenants/${encodeURIComponent(tenant)}`),
82
+ /** Access stops at once; see the data contract for what follows. */
83
+ delete: (tenant) => this.#call("DELETE", `/v1/partner/tenants/${encodeURIComponent(tenant)}`),
84
+ };
85
+ /** Documents, read by a model into facts (033 R15). */
86
+ documents = {
87
+ /**
88
+ * Sends a document, with an Idempotency-Key (yours, or one made here)
89
+ * so a retry never reads it twice. Answers the written facts, or
90
+ * `{ status, follow }` when it is read in the background: pass that to
91
+ * `documents.wait`.
92
+ */
93
+ send: (tenant, doc, options = {}) => this.#call("POST", "/v1/memory/documents", {
94
+ body: { ...doc },
95
+ tenant,
96
+ headers: { "Idempotency-Key": options.idempotencyKey ?? randomUUID() },
97
+ repeatable: true,
98
+ }),
99
+ get: (tenant, documentId) => this.#call("GET", `/v1/memory/documents/${encodeURIComponent(documentId)}`, { tenant, repeatable: true }),
100
+ /** Polls a background document until it is written or failed. */
101
+ wait: async (tenant, documentId, options = {}) => {
102
+ const until = Date.now() + (options.timeoutMs ?? 600_000);
103
+ for (;;) {
104
+ const d = await this.documents.get(tenant, documentId);
105
+ if (d.status === "written" || d.status === "failed" || Date.now() > until)
106
+ return d;
107
+ await this.#sleep(options.everyMs ?? 5_000);
108
+ }
109
+ },
110
+ };
111
+ /** Facts you extracted yourself: nothing goes to a model. */
112
+ facts(tenant, body) {
113
+ return this.#memory("facts", tenant, body);
114
+ }
115
+ write(tenant, body) {
116
+ return this.#memory("write", tenant, body);
117
+ }
118
+ search(tenant, body) {
119
+ return this.#memory("search", tenant, body);
120
+ }
121
+ /** What is known about `entity`, now or at `at_time`. */
122
+ recall(tenant, body) {
123
+ return this.#memory("recall", tenant, body);
124
+ }
125
+ get(tenant, body) {
126
+ return this.#memory("get", tenant, body);
127
+ }
128
+ profile(tenant, body = {}) {
129
+ return this.#memory("profile", tenant, body);
130
+ }
131
+ /** Hides it from answers from now on; it does not destroy it. */
132
+ forget(tenant, body) {
133
+ return this.#memory("forget", tenant, body);
134
+ }
135
+ /** One entry per customer and day, both dates included (YYYY-MM-DD). */
136
+ usage(range = {}) {
137
+ const q = new URLSearchParams(Object.entries(range).filter(([, v]) => v)).toString();
138
+ return this.#call("GET", `/v1/partner/usage${q ? `?${q}` : ""}`, {
139
+ repeatable: true,
140
+ });
141
+ }
142
+ #memory(route, tenant, body) {
143
+ return this.#call("POST", `/v1/memory/${route}`, { body, tenant });
144
+ }
145
+ async #call(method, path, call = {}) {
146
+ const raw = call.body === undefined ? "" : JSON.stringify(call.body);
147
+ const repeatable = call.repeatable ?? method === "GET";
148
+ for (let attempt = 0;; attempt++) {
149
+ const ts = String(Math.floor(Date.now() / 1000));
150
+ const headers = {
151
+ "x-partner-id": this.project,
152
+ "x-localmem-key": this.keyId,
153
+ "x-localmem-timestamp": ts,
154
+ "x-localmem-signature": sign(this.#secret, ts, method, path, raw),
155
+ ...(raw ? { "content-type": "application/json" } : {}),
156
+ ...(call.tenant ? { "x-tenant-id": call.tenant } : {}),
157
+ ...call.headers,
158
+ };
159
+ let res;
160
+ try {
161
+ res = await this.#fetch(`${this.baseUrl}${path}`, {
162
+ method,
163
+ headers,
164
+ body: raw || undefined,
165
+ signal: AbortSignal.timeout(this.#timeoutMs),
166
+ });
167
+ }
168
+ catch (e) {
169
+ // No answer: sent again only when that cannot do it twice.
170
+ if (repeatable && attempt < this.#maxRetries) {
171
+ await this.#sleep(backoff(attempt));
172
+ continue;
173
+ }
174
+ throw e;
175
+ }
176
+ const text = await res.text();
177
+ let body = {};
178
+ try {
179
+ body = text ? JSON.parse(text) : {};
180
+ }
181
+ catch {
182
+ body = { error: "not_json", message: text.slice(0, 200) };
183
+ }
184
+ if (res.ok)
185
+ return body;
186
+ const after = res.headers.get("retry-after");
187
+ const retryAfter = after !== null && /^\d+$/.test(after) ? Number(after) : null;
188
+ const err = new LocalmemError(res.status, body, res.headers.get("x-request-id"), retryAfter);
189
+ if (attempt < this.#maxRetries) {
190
+ // A 429, and a 503 server_busy, were refused before any work, so any
191
+ // request may go again when the wait is short; a monthly limit's wait
192
+ // is days, so it is raised. Any other 503 (a timeout) may have done
193
+ // the work, so only a repeatable request goes again.
194
+ const notDone = res.status === 429 || (res.status === 503 && body.error === "server_busy");
195
+ if ((notDone || (res.status === 503 && repeatable)) && (retryAfter ?? 1) * 1000 <= MAX_WAIT_MS) {
196
+ await this.#sleep(retryAfter !== null ? retryAfter * 1000 : backoff(attempt));
197
+ continue;
198
+ }
199
+ // A document whose first send is still being read: its answer comes
200
+ // to the same Idempotency-Key shortly.
201
+ if ((res.status >= 500 || (res.status === 409 && body.error === "idempotency_key_in_use")) && repeatable) {
202
+ await this.#sleep(backoff(attempt));
203
+ continue;
204
+ }
205
+ }
206
+ throw err;
207
+ }
208
+ }
209
+ }
210
+ /** 0.5 s, 1 s, 2 s … with jitter, at most 8 s. */
211
+ function backoff(attempt) {
212
+ return Math.min(8_000, 500 * 2 ** attempt) * (0.5 + Math.random() / 2);
213
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@localmem/memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The localmem Memory API: memory of each of your customers, with the source and date of every fact. Server-side TypeScript, and `npx @localmem/memory login` to pair a terminal with a project.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://localmem.org/docs/memory-api/sdks",
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "bin": {
17
+ "memory": "./dist/bin.js"
18
+ },
19
+ "files": [
20
+ "dist/index.js",
21
+ "dist/index.d.ts",
22
+ "dist/cli.js",
23
+ "dist/cli.d.ts",
24
+ "dist/bin.js",
25
+ "README.md",
26
+ "LICENSE",
27
+ "NOTICE"
28
+ ],
29
+ "engines": {
30
+ "node": ">=18.17"
31
+ },
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.json",
34
+ "test": "tsc -p tsconfig.json && node --test test/*.test.mjs"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "24.19.2",
38
+ "typescript": "5.9.3"
39
+ }
40
+ }