oortmem 0.0.0-stage → 0.1.1

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.
Files changed (77) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +21 -2
  3. package/dist/cloud-remote.d.ts +9 -0
  4. package/dist/cloud-remote.js +72 -0
  5. package/dist/cloud.d.ts +139 -0
  6. package/dist/cloud.js +223 -0
  7. package/dist/commands/cloud.d.ts +34 -0
  8. package/dist/commands/cloud.js +263 -0
  9. package/dist/commands/connect.d.ts +14 -0
  10. package/dist/commands/connect.js +99 -0
  11. package/dist/commands/consolidate.d.ts +3 -0
  12. package/dist/commands/consolidate.js +24 -0
  13. package/dist/commands/doctor.d.ts +15 -0
  14. package/dist/commands/doctor.js +482 -0
  15. package/dist/commands/explain.d.ts +5 -0
  16. package/dist/commands/explain.js +67 -0
  17. package/dist/commands/export.d.ts +22 -0
  18. package/dist/commands/export.js +83 -0
  19. package/dist/commands/forget.d.ts +5 -0
  20. package/dist/commands/forget.js +24 -0
  21. package/dist/commands/hook.d.ts +12 -0
  22. package/dist/commands/hook.js +169 -0
  23. package/dist/commands/import.d.ts +23 -0
  24. package/dist/commands/import.js +70 -0
  25. package/dist/commands/init.d.ts +9 -0
  26. package/dist/commands/init.js +86 -0
  27. package/dist/commands/inspect.d.ts +26 -0
  28. package/dist/commands/inspect.js +166 -0
  29. package/dist/commands/install.d.ts +28 -0
  30. package/dist/commands/install.js +122 -0
  31. package/dist/commands/keys.d.ts +16 -0
  32. package/dist/commands/keys.js +69 -0
  33. package/dist/commands/login.d.ts +74 -0
  34. package/dist/commands/login.js +326 -0
  35. package/dist/commands/mcp.d.ts +14 -0
  36. package/dist/commands/mcp.js +42 -0
  37. package/dist/commands/observe.d.ts +15 -0
  38. package/dist/commands/observe.js +88 -0
  39. package/dist/commands/pin.d.ts +3 -0
  40. package/dist/commands/pin.js +28 -0
  41. package/dist/commands/project.d.ts +15 -0
  42. package/dist/commands/project.js +60 -0
  43. package/dist/commands/recall.d.ts +11 -0
  44. package/dist/commands/recall.js +58 -0
  45. package/dist/commands/setup.d.ts +50 -0
  46. package/dist/commands/setup.js +532 -0
  47. package/dist/commands/stats.d.ts +25 -0
  48. package/dist/commands/stats.js +143 -0
  49. package/dist/connectors.d.ts +83 -0
  50. package/dist/connectors.js +615 -0
  51. package/dist/credentials-file.d.ts +37 -0
  52. package/dist/credentials-file.js +94 -0
  53. package/dist/credentials.d.ts +47 -0
  54. package/dist/credentials.js +46 -0
  55. package/dist/embed-cache-disk.d.ts +13 -0
  56. package/dist/embed-cache-disk.js +81 -0
  57. package/dist/io.d.ts +36 -0
  58. package/dist/io.js +117 -0
  59. package/dist/keychain.d.ts +70 -0
  60. package/dist/keychain.js +218 -0
  61. package/dist/main.d.ts +2 -0
  62. package/dist/main.js +28 -0
  63. package/dist/mcp.d.ts +26 -0
  64. package/dist/mcp.js +301 -0
  65. package/dist/program.d.ts +14 -0
  66. package/dist/program.js +250 -0
  67. package/dist/relay.d.ts +57 -0
  68. package/dist/relay.js +119 -0
  69. package/dist/remember.d.ts +27 -0
  70. package/dist/remember.js +42 -0
  71. package/dist/ui.d.ts +42 -0
  72. package/dist/ui.js +63 -0
  73. package/dist/util.d.ts +84 -0
  74. package/dist/util.js +213 -0
  75. package/dist/wire.d.ts +77 -0
  76. package/dist/wire.js +281 -0
  77. package/package.json +67 -3
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/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # oortmem
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 `oort` command line. It gives your coding agent a memory that stays correct as facts change.
4
+
5
+ ```sh
6
+ npm install -g oortmem
7
+ oort setup
8
+ ```
9
+
10
+ `oort setup` finds your agents (Claude Code, Claude Desktop, Codex, Cursor, VS Code, Gemini CLI), connects them and checks that recall works.
11
+
12
+ Other commands you will use:
13
+
14
+ - `oort doctor` checks keys, hooks, connectors and the store.
15
+ - `oort mcp` runs the local MCP server for any MCP client.
16
+ - `oort connect <host>` and `oort disconnect <host>` add or remove one agent.
17
+ - `oort login` uses Oort Pro, so you need no vendor keys.
18
+ - `oort keys set <provider>` stores your own Voyage, TypeSafe or Anthropic key.
19
+
20
+ Your memories stay on your machine, in `~/.oort`. Needs Node.js 22.15 or later.
21
+
22
+ Part of [Oort](https://github.com/oortmem/oort), open-source memory for AI agents. See the [main README](https://github.com/oortmem/oort#readme) for how the pieces fit. Apache-2.0.
@@ -0,0 +1,9 @@
1
+ import type { RemoteMemory } from '@oortmem/claude-code';
2
+ import { type CloudClient } from './cloud.js';
3
+ export declare function cloudTurnRef(ref: string): string;
4
+ /**
5
+ * The hooks' view of Oort Cloud. Recall and save go to the API; every failure rejects (the hooks
6
+ * then inject nothing, and the drain keeps account-level refusals queued). With no client (no Oort
7
+ * key, a bad URL), every call rejects the same way.
8
+ */
9
+ export declare function cloudRemote(client: CloudClient | undefined, problem?: string): RemoteMemory;
@@ -0,0 +1,72 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { OortCloudError } from './cloud.js';
3
+ /** The API's turnRef cap; a longer ref is replaced by its hash (still stable across retries). */
4
+ const TURN_REF_MAX = 128;
5
+ export function cloudTurnRef(ref) {
6
+ return ref.length <= TURN_REF_MAX && /^[\x20-\x7e]+$/.test(ref)
7
+ ? ref
8
+ : createHash('sha256').update(ref).digest('hex');
9
+ }
10
+ /** Pinned and hot memories SessionStart injects: at most this many of each from the API. */
11
+ const SESSION_LIMIT = 100;
12
+ /**
13
+ * The hooks' view of Oort Cloud. Recall and save go to the API; every failure rejects (the hooks
14
+ * then inject nothing, and the drain keeps account-level refusals queued). With no client (no Oort
15
+ * key, a bad URL), every call rejects the same way.
16
+ */
17
+ export function cloudRemote(client, problem) {
18
+ const missing = () => {
19
+ throw Object.assign(new Error(problem ?? 'Oort Cloud is not set up on this machine.'), {
20
+ holdQueue: true,
21
+ });
22
+ };
23
+ if (client === undefined) {
24
+ return {
25
+ recall: async () => missing(),
26
+ sessionMemories: async () => missing(),
27
+ observe: async () => missing(),
28
+ };
29
+ }
30
+ return {
31
+ recall: ({ text, projectId }) => client.recall({ text, ...(projectId !== undefined && { project: projectId }), k: 10 }),
32
+ sessionMemories: async ({ projectId }) => {
33
+ const project = projectId !== undefined && { project: projectId };
34
+ // Pinned first (any tier), then the hot tier; a memory in both appears once.
35
+ const [pinned, hot] = await Promise.all([
36
+ client.list({ ...project, pinned: true, limit: SESSION_LIMIT }),
37
+ client.list({ ...project, tier: 'hot', limit: SESSION_LIMIT }),
38
+ ]);
39
+ const seen = new Set();
40
+ const out = [];
41
+ for (const m of [...pinned.memories, ...hot.memories]) {
42
+ if (seen.has(m.id))
43
+ continue;
44
+ seen.add(m.id);
45
+ out.push(m);
46
+ }
47
+ return out;
48
+ },
49
+ observe: async (obs, projectId, turnRef) => {
50
+ try {
51
+ // A repeat of the same turnRef answers `duplicate: true`: already saved, so success.
52
+ await client.observe({
53
+ ...(projectId !== undefined && { project: projectId }),
54
+ ...(turnRef !== undefined && { turnRef: cloudTurnRef(turnRef) }),
55
+ observation: {
56
+ user: obs.userText,
57
+ assistant: obs.assistantText,
58
+ at: obs.at,
59
+ ...(obs.sessionId !== undefined && { session: obs.sessionId }),
60
+ ...(obs.toolSummaries.length > 0 && { tools: obs.toolSummaries }),
61
+ },
62
+ });
63
+ }
64
+ catch (e) {
65
+ if (e instanceof OortCloudError)
66
+ throw e; // carries holdQueue
67
+ throw Object.assign(new Error('Oort Cloud save failed.'), { holdQueue: true });
68
+ }
69
+ },
70
+ };
71
+ }
72
+ //# sourceMappingURL=cloud-remote.js.map
@@ -0,0 +1,139 @@
1
+ import type { Memory, RecallResult, Tier } from '@oortmem/core';
2
+ import type { Env } from './io.js';
3
+ import { Refusal } from './util.js';
4
+ /**
5
+ * Oort Cloud, as the CLI sees it: where the API is, which store this machine uses, and what the
6
+ * API's refusals mean. The API itself lives in the private oortcloud repo (apps/cloud); the routes
7
+ * and shapes the CLI relies on are pinned in `test/cloud-contract.json`.
8
+ */
9
+ export declare const DEFAULT_CLOUD_URL = "https://api.oortcloud.dev";
10
+ /**
11
+ * The API root: `OORT_CLOUD_URL` when set and non-empty (local dev against `wrangler dev`), else
12
+ * `DEFAULT_CLOUD_URL`. Only https, or http to a loopback host: the Oort key travels in every
13
+ * request.
14
+ */
15
+ export declare function cloudUrl(env: Env): {
16
+ url: string;
17
+ } | {
18
+ error: string;
19
+ };
20
+ export type StoreMode = 'local' | 'cloud';
21
+ export interface ImportProgress {
22
+ /** A fingerprint of the export being uploaded (count and first and last id). */
23
+ fingerprint: string;
24
+ /** Memory lines already accepted by the cloud. */
25
+ done: number;
26
+ total: number;
27
+ updatedAt: string;
28
+ }
29
+ export interface CloudSettings {
30
+ store: StoreMode;
31
+ import?: ImportProgress;
32
+ }
33
+ export declare const cloudSettingsPath: (home: string) => string;
34
+ export declare function readCloudSettings(home: string): CloudSettings;
35
+ export declare function writeCloudSettings(home: string, s: CloudSettings): void;
36
+ export type CloudErrorKind = 'unauthorized' | 'payment-required' | 'not-enabled' | 'rate-limit' | 'too-large' | 'not-found' | 'ambiguous-prefix' | 'bad-request' | 'busy' | 'network';
37
+ /**
38
+ * A refusal from Oort Cloud the user can act on: one line saying what happened and the fix. It
39
+ * never carries the key or the request. The API's own message is used where it explains a limit
40
+ * (the monthly cap says which and when it resets).
41
+ */
42
+ export declare class OortCloudError extends Refusal {
43
+ readonly kind: CloudErrorKind;
44
+ readonly status: number;
45
+ /** The drain keeps the line queued instead of counting an attempt. */
46
+ readonly holdQueue: boolean;
47
+ constructor(kind: CloudErrorKind, status: number, apiMessage?: string);
48
+ }
49
+ /** The kind an API status (and `{ error: { code } }`) stands for. */
50
+ export declare function cloudErrorKind(status: number, code?: string): CloudErrorKind;
51
+ export type CloudMemory = Omit<Memory, 'embedding'>;
52
+ export interface CloudStats {
53
+ tiers: Record<Tier, number>;
54
+ memories: number;
55
+ databaseBytes: number;
56
+ lastConsolidatedAt: string | null;
57
+ }
58
+ export interface CloudObservation {
59
+ user: string;
60
+ assistant: string;
61
+ at?: string;
62
+ session?: string;
63
+ tools?: string[];
64
+ }
65
+ export interface CloudObserveResult {
66
+ outcome: string;
67
+ memories: {
68
+ id?: string;
69
+ action: string;
70
+ }[];
71
+ counts: Record<string, number>;
72
+ /** The turnRef was seen before: the turn is already saved and nothing was done. */
73
+ duplicate?: true;
74
+ }
75
+ export interface CloudImportResult {
76
+ imported: number;
77
+ skipped: number;
78
+ reembedded: number;
79
+ next?: number;
80
+ }
81
+ export interface CloudClient {
82
+ readonly url: string;
83
+ whoami(): Promise<{
84
+ account: string;
85
+ plan: string;
86
+ via: string;
87
+ }>;
88
+ recall(q: {
89
+ text: string;
90
+ project?: string;
91
+ k?: number;
92
+ asOf?: string;
93
+ }): Promise<RecallResult>;
94
+ /** `turnRef` makes a retry safe: the API saves each turn once and answers `duplicate`. */
95
+ observe(b: {
96
+ project?: string;
97
+ observation: CloudObservation;
98
+ turnRef?: string;
99
+ }): Promise<CloudObserveResult>;
100
+ list(q?: {
101
+ project?: string;
102
+ tier?: Tier;
103
+ type?: string;
104
+ q?: string;
105
+ pinned?: boolean;
106
+ cursor?: string;
107
+ limit?: number;
108
+ }): Promise<{
109
+ memories: CloudMemory[];
110
+ next?: string;
111
+ }>;
112
+ /** By id, or by a unique prefix of at least 8 characters (409 `ambiguous` when several match). */
113
+ get(ref: string): Promise<CloudMemory>;
114
+ forget(id: string): Promise<void>;
115
+ pin(id: string, pinned: boolean): Promise<void>;
116
+ stats(): Promise<CloudStats>;
117
+ /** The v1 export, as JSON Lines text. */
118
+ exportText(): Promise<string>;
119
+ /**
120
+ * Posts export lines (the first is the manifest). One call imports at most 1,000 lines; when
121
+ * `next` is set, post the same lines again with `from = next` to continue.
122
+ */
123
+ importLines(lines: string[], from?: number): Promise<CloudImportResult>;
124
+ }
125
+ export interface CloudClientOptions {
126
+ url: string;
127
+ key: string;
128
+ fetch?: typeof fetch;
129
+ /** Per-request timeout; the hooks pass their own budget. */
130
+ timeoutMs?: number;
131
+ }
132
+ export declare function createCloudClient(opts: CloudClientOptions): CloudClient;
133
+ /** The shortest id prefix the API looks up (it answers 404 below this). */
134
+ export declare const MIN_ID_PREFIX = 8;
135
+ /**
136
+ * A memory by id or unique id prefix (what `oort inspect` prints), looked up by the API itself:
137
+ * a prefix that matches several memories is refused with a clear message.
138
+ */
139
+ export declare function findCloudMemory(client: CloudClient, ref: string): Promise<CloudMemory>;
package/dist/cloud.js ADDED
@@ -0,0 +1,223 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { ACCOUNT_URL } from './relay.js';
4
+ import { Refusal, writeOwnerOnly } from './util.js';
5
+ /**
6
+ * Oort Cloud, as the CLI sees it: where the API is, which store this machine uses, and what the
7
+ * API's refusals mean. The API itself lives in the private oortcloud repo (apps/cloud); the routes
8
+ * and shapes the CLI relies on are pinned in `test/cloud-contract.json`.
9
+ */
10
+ export const DEFAULT_CLOUD_URL = 'https://api.oortcloud.dev';
11
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
12
+ /**
13
+ * The API root: `OORT_CLOUD_URL` when set and non-empty (local dev against `wrangler dev`), else
14
+ * `DEFAULT_CLOUD_URL`. Only https, or http to a loopback host: the Oort key travels in every
15
+ * request.
16
+ */
17
+ export function cloudUrl(env) {
18
+ const raw = env['OORT_CLOUD_URL'];
19
+ if (raw === undefined || raw === '')
20
+ return { url: DEFAULT_CLOUD_URL };
21
+ let u;
22
+ try {
23
+ u = new URL(raw);
24
+ }
25
+ catch {
26
+ return { error: 'OORT_CLOUD_URL is not a URL; unset it to use Oort Cloud.' };
27
+ }
28
+ const ok = u.protocol === 'https:' || (u.protocol === 'http:' && LOOPBACK.has(u.hostname));
29
+ if (!ok || u.username !== '' || u.password !== '' || u.search !== '' || u.hash !== '') {
30
+ return {
31
+ error: 'OORT_CLOUD_URL must be an https URL (or http to localhost) with no credentials or query; unset it to use Oort Cloud.',
32
+ };
33
+ }
34
+ return { url: `${u.origin}${u.pathname.replace(/\/+$/, '')}` };
35
+ }
36
+ export const cloudSettingsPath = (home) => path.join(home, 'cloud.json');
37
+ export function readCloudSettings(home) {
38
+ let raw;
39
+ try {
40
+ raw = JSON.parse(fs.readFileSync(cloudSettingsPath(home), 'utf8'));
41
+ }
42
+ catch {
43
+ return { store: 'local' };
44
+ }
45
+ const r = raw;
46
+ const store = r?.store === 'cloud' ? 'cloud' : 'local';
47
+ const imp = r?.import;
48
+ const progress = imp !== undefined &&
49
+ typeof imp.fingerprint === 'string' &&
50
+ typeof imp.done === 'number' &&
51
+ typeof imp.total === 'number'
52
+ ? {
53
+ fingerprint: imp.fingerprint,
54
+ done: imp.done,
55
+ total: imp.total,
56
+ updatedAt: typeof imp.updatedAt === 'string' ? imp.updatedAt : '',
57
+ }
58
+ : undefined;
59
+ return { store, ...(progress !== undefined && { import: progress }) };
60
+ }
61
+ export function writeCloudSettings(home, s) {
62
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
63
+ writeOwnerOnly(cloudSettingsPath(home), `${JSON.stringify(s, null, 2)}\n`, true);
64
+ }
65
+ /** Kinds the account has to fix, or that pass with time: a hook's queue waits instead. */
66
+ const HOLD = new Set([
67
+ 'unauthorized',
68
+ 'payment-required',
69
+ 'not-enabled',
70
+ 'rate-limit',
71
+ 'busy',
72
+ 'network',
73
+ ]);
74
+ /**
75
+ * A refusal from Oort Cloud the user can act on: one line saying what happened and the fix. It
76
+ * never carries the key or the request. The API's own message is used where it explains a limit
77
+ * (the monthly cap says which and when it resets).
78
+ */
79
+ export class OortCloudError extends Refusal {
80
+ kind;
81
+ status;
82
+ /** The drain keeps the line queued instead of counting an attempt. */
83
+ holdQueue;
84
+ constructor(kind, status, apiMessage) {
85
+ super(messageFor(kind, status, apiMessage));
86
+ this.name = 'OortCloudError';
87
+ this.kind = kind;
88
+ this.status = status;
89
+ this.holdQueue = HOLD.has(kind);
90
+ }
91
+ }
92
+ function messageFor(kind, status, api) {
93
+ switch (kind) {
94
+ case 'unauthorized':
95
+ return `Oort Cloud rejected the Oort key (HTTP ${status}): it is unknown or revoked. Run \`oort login\` again.`;
96
+ case 'payment-required':
97
+ return `Oort Pro is not active on this account (HTTP 402). Subscribe or update billing at ${ACCOUNT_URL}, or run \`oort cloud use --local\`. \`oort cloud export\` still works.`;
98
+ case 'not-enabled':
99
+ return 'Oort Cloud is not enabled for this account yet (HTTP 403). Your memories stay on this machine; run `oort cloud use --local`.';
100
+ case 'rate-limit':
101
+ return `Oort Cloud limit reached (HTTP 429)${api !== undefined ? `: ${api}` : '.'} Usage is at ${ACCOUNT_URL}.`;
102
+ case 'too-large':
103
+ return `Oort Cloud refused a request that is too large (HTTP 413)${api !== undefined ? `: ${api}` : '.'}`;
104
+ case 'not-found':
105
+ return 'No such memory in Oort Cloud.';
106
+ case 'ambiguous-prefix':
107
+ return 'That id prefix matches more than one memory in Oort Cloud; give more of the id.';
108
+ case 'bad-request':
109
+ return `Oort Cloud refused the request (HTTP ${status})${api !== undefined ? `: ${api}` : '.'}`;
110
+ case 'busy':
111
+ return `Oort Cloud is busy or down, try again shortly (HTTP ${status}).`;
112
+ case 'network':
113
+ return 'Oort Cloud is unreachable: check your network, then try again.';
114
+ }
115
+ }
116
+ /** The kind an API status (and `{ error: { code } }`) stands for. */
117
+ export function cloudErrorKind(status, code) {
118
+ if (status === 401)
119
+ return 'unauthorized';
120
+ if (status === 402)
121
+ return 'payment-required';
122
+ if (status === 403)
123
+ return code === 'cloud_not_enabled' ? 'not-enabled' : 'unauthorized';
124
+ if (status === 404)
125
+ return 'not-found';
126
+ if (status === 409 && code === 'ambiguous')
127
+ return 'ambiguous-prefix';
128
+ if (status === 413)
129
+ return 'too-large';
130
+ if (status === 429)
131
+ return 'rate-limit';
132
+ if (status >= 500)
133
+ return 'busy';
134
+ return 'bad-request';
135
+ }
136
+ const DEFAULT_TIMEOUT_MS = 30_000;
137
+ export function createCloudClient(opts) {
138
+ const doFetch = opts.fetch ?? globalThis.fetch;
139
+ const timeout = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
140
+ async function call(method, route, body) {
141
+ const abort = new AbortController();
142
+ const timer = setTimeout(() => abort.abort(), timeout);
143
+ const headers = { authorization: `Bearer ${opts.key}` };
144
+ let payload;
145
+ if (body?.json !== undefined) {
146
+ headers['content-type'] = 'application/json';
147
+ payload = JSON.stringify(body.json);
148
+ }
149
+ else if (body?.text !== undefined) {
150
+ headers['content-type'] = 'application/x-ndjson';
151
+ payload = body.text;
152
+ }
153
+ let res;
154
+ try {
155
+ res = await doFetch(`${opts.url}${route}`, {
156
+ method,
157
+ headers,
158
+ ...(payload !== undefined && { body: payload }),
159
+ signal: abort.signal,
160
+ redirect: 'error',
161
+ });
162
+ }
163
+ catch {
164
+ throw new OortCloudError('network', 0);
165
+ }
166
+ finally {
167
+ clearTimeout(timer);
168
+ }
169
+ if (!res.ok) {
170
+ const err = (await res.json().catch(() => ({})));
171
+ const code = typeof err.error?.code === 'string' ? err.error.code : undefined;
172
+ const message = typeof err.error?.message === 'string' ? err.error.message : undefined;
173
+ throw new OortCloudError(cloudErrorKind(res.status, code), res.status, message);
174
+ }
175
+ return res;
176
+ }
177
+ const json = async (method, route, body) => (await (await call(method, route, body === undefined ? undefined : { json: body })).json());
178
+ const idPath = (id) => `/v1/memories/${encodeURIComponent(id)}`;
179
+ return {
180
+ url: opts.url,
181
+ whoami: () => json('GET', '/v1/whoami'),
182
+ recall: (q) => json('POST', '/v1/recall', q),
183
+ observe: (b) => json('POST', '/v1/observe', b),
184
+ list: (q = {}) => {
185
+ const p = new URLSearchParams();
186
+ for (const [k, v] of Object.entries(q))
187
+ if (v !== undefined)
188
+ p.set(k, String(v));
189
+ const qs = p.toString();
190
+ return json('GET', `/v1/memories${qs === '' ? '' : `?${qs}`}`);
191
+ },
192
+ get: (id) => json('GET', idPath(id)),
193
+ forget: async (id) => {
194
+ await call('DELETE', idPath(id));
195
+ },
196
+ pin: async (id, pinned) => {
197
+ await call('POST', `${idPath(id)}/${pinned ? 'pin' : 'unpin'}`);
198
+ },
199
+ stats: () => json('GET', '/v1/stats'),
200
+ exportText: async () => (await call('GET', '/v1/export')).text(),
201
+ importLines: async (lines, from = 0) => (await (await call('POST', `/v1/import?from=${from}`, {
202
+ text: lines.map((l) => `${l}\n`).join(''),
203
+ })).json()),
204
+ };
205
+ }
206
+ /** The shortest id prefix the API looks up (it answers 404 below this). */
207
+ export const MIN_ID_PREFIX = 8;
208
+ /**
209
+ * A memory by id or unique id prefix (what `oort inspect` prints), looked up by the API itself:
210
+ * a prefix that matches several memories is refused with a clear message.
211
+ */
212
+ export async function findCloudMemory(client, ref) {
213
+ try {
214
+ return await client.get(ref);
215
+ }
216
+ catch (e) {
217
+ if (e instanceof OortCloudError && e.kind === 'not-found' && ref.length < MIN_ID_PREFIX) {
218
+ throw new Refusal(`Give at least ${MIN_ID_PREFIX} characters of the memory id.`);
219
+ }
220
+ throw e;
221
+ }
222
+ }
223
+ //# sourceMappingURL=cloud.js.map