oortmem 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.
Files changed (71) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +21 -2
  3. package/dist/commands/connect.d.ts +14 -0
  4. package/dist/commands/connect.js +99 -0
  5. package/dist/commands/consolidate.d.ts +3 -0
  6. package/dist/commands/consolidate.js +21 -0
  7. package/dist/commands/doctor.d.ts +15 -0
  8. package/dist/commands/doctor.js +410 -0
  9. package/dist/commands/explain.d.ts +5 -0
  10. package/dist/commands/explain.js +67 -0
  11. package/dist/commands/export.d.ts +19 -0
  12. package/dist/commands/export.js +69 -0
  13. package/dist/commands/forget.d.ts +5 -0
  14. package/dist/commands/forget.js +17 -0
  15. package/dist/commands/hook.d.ts +12 -0
  16. package/dist/commands/hook.js +165 -0
  17. package/dist/commands/import.d.ts +23 -0
  18. package/dist/commands/import.js +67 -0
  19. package/dist/commands/init.d.ts +9 -0
  20. package/dist/commands/init.js +86 -0
  21. package/dist/commands/inspect.d.ts +26 -0
  22. package/dist/commands/inspect.js +126 -0
  23. package/dist/commands/install.d.ts +28 -0
  24. package/dist/commands/install.js +122 -0
  25. package/dist/commands/keys.d.ts +16 -0
  26. package/dist/commands/keys.js +69 -0
  27. package/dist/commands/login.d.ts +74 -0
  28. package/dist/commands/login.js +326 -0
  29. package/dist/commands/mcp.d.ts +14 -0
  30. package/dist/commands/mcp.js +42 -0
  31. package/dist/commands/observe.d.ts +15 -0
  32. package/dist/commands/observe.js +73 -0
  33. package/dist/commands/pin.d.ts +3 -0
  34. package/dist/commands/pin.js +16 -0
  35. package/dist/commands/project.d.ts +15 -0
  36. package/dist/commands/project.js +60 -0
  37. package/dist/commands/recall.d.ts +11 -0
  38. package/dist/commands/recall.js +46 -0
  39. package/dist/commands/setup.d.ts +50 -0
  40. package/dist/commands/setup.js +532 -0
  41. package/dist/commands/stats.d.ts +25 -0
  42. package/dist/commands/stats.js +113 -0
  43. package/dist/connectors.d.ts +83 -0
  44. package/dist/connectors.js +615 -0
  45. package/dist/credentials-file.d.ts +37 -0
  46. package/dist/credentials-file.js +94 -0
  47. package/dist/credentials.d.ts +47 -0
  48. package/dist/credentials.js +46 -0
  49. package/dist/embed-cache-disk.d.ts +13 -0
  50. package/dist/embed-cache-disk.js +81 -0
  51. package/dist/io.d.ts +36 -0
  52. package/dist/io.js +117 -0
  53. package/dist/keychain.d.ts +70 -0
  54. package/dist/keychain.js +218 -0
  55. package/dist/main.d.ts +2 -0
  56. package/dist/main.js +28 -0
  57. package/dist/mcp.d.ts +17 -0
  58. package/dist/mcp.js +168 -0
  59. package/dist/program.d.ts +14 -0
  60. package/dist/program.js +224 -0
  61. package/dist/relay.d.ts +57 -0
  62. package/dist/relay.js +119 -0
  63. package/dist/remember.d.ts +27 -0
  64. package/dist/remember.js +42 -0
  65. package/dist/ui.d.ts +42 -0
  66. package/dist/ui.js +63 -0
  67. package/dist/util.d.ts +78 -0
  68. package/dist/util.js +202 -0
  69. package/dist/wire.d.ts +65 -0
  70. package/dist/wire.js +257 -0
  71. package/package.json +67 -3
@@ -0,0 +1,69 @@
1
+ import { PROVIDERS, PROVIDER_ENV, isProvider } from '../keychain.js';
2
+ import { uiFor } from '../ui.js';
3
+ import { Refusal } from '../util.js';
4
+ function providerArg(arg, ctx) {
5
+ if (!isProvider(arg)) {
6
+ // The argument is not echoed: someone may have pasted a key here.
7
+ throw new Refusal(`unknown provider; expected one of ${PROVIDERS.join(', ')}.`);
8
+ }
9
+ if (ctx.io.env['OORT_NO_KEYCHAIN'] === '1') {
10
+ throw new Refusal('OORT_NO_KEYCHAIN=1 is set; unset it to use stored keys.');
11
+ }
12
+ if (!ctx.keychain.supported) {
13
+ throw new Refusal('this system has no place to keep keys (the Keychain is macOS, credentials.json is Linux and Windows); export the key as an environment variable instead.');
14
+ }
15
+ return arg;
16
+ }
17
+ /**
18
+ * `oort keys set <provider>`: the value is prompted for with the input hidden (by `security` on
19
+ * macOS, by us for credentials.json), so it never touches argv or the terminal history.
20
+ */
21
+ export async function keysSetCommand(arg, ctx) {
22
+ const provider = providerArg(arg, ctx);
23
+ const code = await ctx.keychain.set(provider);
24
+ if (code === 0) {
25
+ ctx.io.out(ctx.keychain.kind === 'file'
26
+ ? `Stored ${provider} in ${ctx.keychain.where(provider)} (mode 600).\n`
27
+ : `Stored ${provider} in the Keychain (oort.${provider}).\n`);
28
+ }
29
+ return code === 0 ? 0 : 1;
30
+ }
31
+ /** `oort keys rm <provider>`. */
32
+ export async function keysRmCommand(arg, ctx) {
33
+ const provider = providerArg(arg, ctx);
34
+ const code = await ctx.keychain.remove(provider);
35
+ if (code === 0)
36
+ ctx.io.out(`Removed ${provider} from ${ctx.keychain.label}.\n`);
37
+ return code === 0 ? 0 : 1;
38
+ }
39
+ /** Where `provider`'s key would come from (env first, then the Keychain); never the value. */
40
+ export async function keySource(provider, ctx) {
41
+ const fromEnv = ctx.io.env[PROVIDER_ENV[provider]];
42
+ if (fromEnv !== undefined && fromEnv !== '')
43
+ return 'env';
44
+ return (await ctx.keychain.read(provider)) !== undefined ? 'keychain' : 'missing';
45
+ }
46
+ /** `oort keys list [--json]`: where each key would come from; presence only, never a value or prefix. */
47
+ export async function keysListCommand(opts, ctx) {
48
+ const rows = [];
49
+ for (const provider of PROVIDERS) {
50
+ rows.push({ provider, envVar: PROVIDER_ENV[provider], source: await keySource(provider, ctx) });
51
+ }
52
+ if (opts.json === true) {
53
+ ctx.io.out(`${JSON.stringify(rows, null, 2)}\n`);
54
+ return 0;
55
+ }
56
+ const ui = uiFor(ctx.io);
57
+ const where = (r) => r.source === 'env'
58
+ ? r.envVar
59
+ : r.source === 'keychain'
60
+ ? `oort.${r.provider}`
61
+ : r.provider === 'oort'
62
+ ? 'oort login (Oort Pro)'
63
+ : `oort keys set ${r.provider}`;
64
+ const shown = (s) => (s === 'missing' ? ui.yellow : ui.green)(s.padEnd('keychain'.length));
65
+ ctx.io.out(ui.header('keys list'));
66
+ ctx.io.out(ui.kv(rows.map((r) => [r.provider, `${shown(r.source)} ${ui.dim(where(r))}`])));
67
+ return 0;
68
+ }
69
+ //# sourceMappingURL=keys.js.map
@@ -0,0 +1,74 @@
1
+ import type { Env } from '../io.js';
2
+ import { type Ui } from '../ui.js';
3
+ import { type Ctx } from '../util.js';
4
+ /**
5
+ * `oort login`: the browser sign-in that `apps/site` serves, RFC 8628 style.
6
+ * 1. A secret S (32 random bytes) stays in this process. `POST /api/cli/session` sends only
7
+ * h = base64url(SHA-256(S)), with this computer's OS and host name, and gets back a short
8
+ * user code.
9
+ * 2. The user opens `/account/cli` (no secret in the URL), types the code, checks the request's
10
+ * time, country, OS and host, and approves.
11
+ * 3. `POST /api/cli/session/poll` with S in the body answers 202 until approved, then 200
12
+ * `{ status, key, prefix }` once, and 410 `used` or `expired` (10 minutes after the session
13
+ * started) after that; 404 for a session the site does not know, 409 `key_limit` when the
14
+ * account already has its maximum of live keys.
15
+ * The key goes to Keychain item `oort.oort` (macOS) or `credentials.json` (Linux, Windows) and is
16
+ * never printed.
17
+ */
18
+ export declare const DEFAULT_SITE_URL = "https://oortcloud.dev";
19
+ /** The site's session lifetime (CLI_SESSION_TTL_MS in apps/site). */
20
+ export declare const SESSION_TTL_MS: number;
21
+ export interface LoginDeps {
22
+ fetch?: typeof fetch;
23
+ /** Opens `url` in the browser; resolves false when no opener could start. */
24
+ openBrowser?: (url: string) => Promise<boolean>;
25
+ /** Waits `ms`, or less when `signal` aborts. */
26
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
27
+ now?: () => number;
28
+ /** Aborts the wait (Ctrl-C). Default: SIGINT while polling. */
29
+ signal?: AbortSignal;
30
+ /** The 32 secret bytes S. */
31
+ secret?: () => Uint8Array;
32
+ /** What the approve page shows about this computer. */
33
+ system?: () => {
34
+ os: string;
35
+ host: string;
36
+ };
37
+ }
38
+ /** `OORT_SITE_URL` (https, or http to localhost, for local dev) or oortcloud.dev. */
39
+ export declare function siteUrl(env: Env): string;
40
+ /** S: 32 random bytes, kept in this process only. */
41
+ export declare const newSecret: () => Uint8Array;
42
+ /** h = base64url(SHA-256(S)), the only thing about S the site sees before the poll. */
43
+ export declare const challengeOf: (secret: Uint8Array) => string;
44
+ /** This computer, as the approve page shows it: OS and host name, nothing else. */
45
+ export declare function thisSystem(): {
46
+ os: string;
47
+ host: string;
48
+ };
49
+ /** The platform's opener, without a shell; false when it cannot start. */
50
+ export declare function platformOpener(platform?: NodeJS.Platform): (url: string) => Promise<boolean>;
51
+ /** Why no key store can hold the key here, or undefined when one can. */
52
+ export declare function keychainBlocker(ctx: Ctx): string | undefined;
53
+ export type LoginOutcome = {
54
+ ok: true;
55
+ } | {
56
+ ok: false;
57
+ reason: 'cancelled' | 'expired' | 'used' | 'failed';
58
+ message: string;
59
+ };
60
+ /**
61
+ * The sign-in itself, writing its lines through `say` (stdout for the
62
+ * command, the wizard's log for `oort setup`). It never prompts: on a
63
+ * terminal it opens the browser, otherwise it prints the URL, and either way
64
+ * it polls until approved, expired or cancelled.
65
+ */
66
+ export declare function runLogin(ctx: Ctx, say: (text: string) => void, ui: Ui, opts?: {
67
+ browser?: boolean;
68
+ }, deps?: LoginDeps): Promise<LoginOutcome>;
69
+ /** `oort login [--no-browser]` */
70
+ export declare function loginCommand(opts: {
71
+ browser?: boolean;
72
+ }, ctx: Ctx): Promise<number>;
73
+ /** `oort logout`: removes the stored Oort key (Keychain item `oort.oort`, or its credentials.json entry). It never revokes the key server-side. */
74
+ export declare function logoutCommand(ctx: Ctx): Promise<number>;
@@ -0,0 +1,326 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash, randomBytes } from 'node:crypto';
3
+ import * as os from 'node:os';
4
+ import { keyLookup, routeSummaries } from '../credentials.js';
5
+ import { ACCOUNT_URL, REVOKE_HINT } from '../relay.js';
6
+ import { uiFor } from '../ui.js';
7
+ import { Refusal } from '../util.js';
8
+ /**
9
+ * `oort login`: the browser sign-in that `apps/site` serves, RFC 8628 style.
10
+ * 1. A secret S (32 random bytes) stays in this process. `POST /api/cli/session` sends only
11
+ * h = base64url(SHA-256(S)), with this computer's OS and host name, and gets back a short
12
+ * user code.
13
+ * 2. The user opens `/account/cli` (no secret in the URL), types the code, checks the request's
14
+ * time, country, OS and host, and approves.
15
+ * 3. `POST /api/cli/session/poll` with S in the body answers 202 until approved, then 200
16
+ * `{ status, key, prefix }` once, and 410 `used` or `expired` (10 minutes after the session
17
+ * started) after that; 404 for a session the site does not know, 409 `key_limit` when the
18
+ * account already has its maximum of live keys.
19
+ * The key goes to Keychain item `oort.oort` (macOS) or `credentials.json` (Linux, Windows) and is
20
+ * never printed.
21
+ */
22
+ export const DEFAULT_SITE_URL = 'https://oortcloud.dev';
23
+ /** The site's session lifetime (CLI_SESSION_TTL_MS in apps/site). */
24
+ export const SESSION_TTL_MS = 10 * 60_000;
25
+ const KEY_SHAPE = /^oort_sk_[A-Za-z0-9_-]{16,256}$/;
26
+ /** The site's user code as shown: 8 letters of BCDFGHJKLMNPQRSTVWXZ, XXXX-XXXX. */
27
+ const USER_CODE = /^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/;
28
+ const FIRST_DELAY_MS = 2000;
29
+ const MAX_DELAY_MS = 5000;
30
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
31
+ /** `OORT_SITE_URL` (https, or http to localhost, for local dev) or oortcloud.dev. */
32
+ export function siteUrl(env) {
33
+ const raw = env['OORT_SITE_URL'];
34
+ if (raw === undefined || raw === '')
35
+ return DEFAULT_SITE_URL;
36
+ let u;
37
+ try {
38
+ u = new URL(raw);
39
+ }
40
+ catch {
41
+ throw new Refusal('OORT_SITE_URL is not a URL; unset it to sign in at oortcloud.dev.');
42
+ }
43
+ const ok = u.protocol === 'https:' || (u.protocol === 'http:' && LOOPBACK.has(u.hostname));
44
+ if (!ok || u.username !== '' || u.password !== '' || u.search !== '' || u.hash !== '') {
45
+ throw new Refusal('OORT_SITE_URL must be an https URL (or http to localhost) with no credentials or query.');
46
+ }
47
+ return `${u.origin}${u.pathname.replace(/\/+$/, '')}`;
48
+ }
49
+ /** S: 32 random bytes, kept in this process only. */
50
+ export const newSecret = () => randomBytes(32);
51
+ /** h = base64url(SHA-256(S)), the only thing about S the site sees before the poll. */
52
+ export const challengeOf = (secret) => createHash('sha256').update(secret).digest('base64url');
53
+ const OS_NAMES = { darwin: 'macOS', linux: 'Linux', win32: 'Windows' };
54
+ /** This computer, as the approve page shows it: OS and host name, nothing else. */
55
+ export function thisSystem() {
56
+ return { os: OS_NAMES[process.platform] ?? process.platform, host: os.hostname().slice(0, 64) };
57
+ }
58
+ /** The platform's opener, without a shell; false when it cannot start. */
59
+ export function platformOpener(platform = process.platform) {
60
+ return (url) => new Promise((resolve) => {
61
+ const [file, args] = platform === 'darwin'
62
+ ? ['open', [url]]
63
+ : platform === 'win32'
64
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
65
+ : ['xdg-open', [url]];
66
+ try {
67
+ const child = spawn(file, args, { stdio: 'ignore', detached: true });
68
+ child.once('error', () => resolve(false));
69
+ child.once('spawn', () => {
70
+ child.unref();
71
+ resolve(true);
72
+ });
73
+ }
74
+ catch {
75
+ resolve(false);
76
+ }
77
+ });
78
+ }
79
+ const defaultSleep = (ms, signal) => new Promise((resolve) => {
80
+ if (signal.aborted)
81
+ return resolve();
82
+ const t = setTimeout(done, ms);
83
+ function done() {
84
+ clearTimeout(t);
85
+ signal.removeEventListener('abort', done);
86
+ resolve();
87
+ }
88
+ signal.addEventListener('abort', done, { once: true });
89
+ });
90
+ /** Why no key store can hold the key here, or undefined when one can. */
91
+ export function keychainBlocker(ctx) {
92
+ const fallback = `create a key at ${ACCOUNT_URL} and export OORT_API_KEY=... instead`;
93
+ if (ctx.io.env['OORT_NO_KEYCHAIN'] === '1') {
94
+ return `OORT_NO_KEYCHAIN=1 is set, so oort login has nowhere to keep the key; unset it, or ${fallback}.`;
95
+ }
96
+ if (!ctx.keychain.supported) {
97
+ return `oort login keeps the key in the macOS Keychain or, on Linux and Windows, in credentials.json; this system has neither; ${fallback}.`;
98
+ }
99
+ return undefined;
100
+ }
101
+ /**
102
+ * The sign-in itself, writing its lines through `say` (stdout for the
103
+ * command, the wizard's log for `oort setup`). It never prompts: on a
104
+ * terminal it opens the browser, otherwise it prints the URL, and either way
105
+ * it polls until approved, expired or cancelled.
106
+ */
107
+ export async function runLogin(ctx, say, ui, opts = {}, deps = ctx.login ?? {}) {
108
+ const blocker = keychainBlocker(ctx);
109
+ if (blocker !== undefined)
110
+ throw new Refusal(blocker);
111
+ const site = siteUrl(ctx.io.env);
112
+ const doFetch = deps.fetch ?? globalThis.fetch;
113
+ const now = deps.now ?? Date.now;
114
+ const sleep = deps.sleep ?? defaultSleep;
115
+ const secretBytes = (deps.secret ?? newSecret)();
116
+ const secret = Buffer.from(secretBytes).toString('base64url');
117
+ const approve = `${site}/account/cli`;
118
+ const poll = `${site}/api/cli/session/poll`;
119
+ const failed = (message) => ({ ok: false, reason: 'failed', message });
120
+ let started;
121
+ try {
122
+ started = await doFetch(`${site}/api/cli/session`, {
123
+ method: 'POST',
124
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
125
+ body: JSON.stringify({
126
+ challenge: challengeOf(secretBytes),
127
+ ...(deps.system ?? thisSystem)(),
128
+ }),
129
+ signal: AbortSignal.timeout(10_000),
130
+ });
131
+ }
132
+ catch {
133
+ return failed(`Could not reach ${site}. Check your network, then run \`oort login\` again.`);
134
+ }
135
+ const startBody = (await started.json().catch(() => ({})));
136
+ const code = startBody.user_code;
137
+ if (started.status === 429) {
138
+ return failed('The site has had too many sign-in requests from this network. Wait a minute, then run `oort login` again.');
139
+ }
140
+ if (started.status !== 201 || typeof code !== 'string' || !USER_CODE.test(code)) {
141
+ return failed(started.status >= 500
142
+ ? `The site answered HTTP ${started.status}. Run \`oort login\` again later.`
143
+ : 'The site rejected this sign-in request. Update oortmem, then run `oort login` again.');
144
+ }
145
+ const terminal = ctx.io.stdinIsTTY && ctx.io.stdoutIsTTY === true;
146
+ const opened = terminal && opts.browser !== false
147
+ ? await (deps.openBrowser ?? platformOpener())(approve)
148
+ : false;
149
+ say(opened
150
+ ? `Opened ${approve} in your browser. Sign in there and enter the code below.`
151
+ : `Open this page in a browser, sign in and enter the code below:\n ${approve}`);
152
+ say(ui.kv([
153
+ [
154
+ 'code',
155
+ `${ui.bold(code)} ${ui.dim('type it on the page; approve only if you started this login yourself')}`,
156
+ ],
157
+ ]));
158
+ say(ui.dim('Waiting for approval (Ctrl-C cancels; the request expires in 10 minutes) …'));
159
+ // Ctrl-C ends the wait; nothing has been stored yet, so there is nothing to undo.
160
+ const own = new AbortController();
161
+ const signal = deps.signal ?? own.signal;
162
+ const onSigint = () => own.abort();
163
+ if (deps.signal === undefined)
164
+ process.once('SIGINT', onSigint);
165
+ const cancelled = () => ({
166
+ ok: false,
167
+ reason: 'cancelled',
168
+ message: 'Sign-in cancelled; nothing was stored.',
169
+ });
170
+ try {
171
+ const deadline = now() + SESSION_TTL_MS + 30_000;
172
+ let delay = FIRST_DELAY_MS;
173
+ let transient = 0;
174
+ for (;;) {
175
+ if (signal.aborted)
176
+ return cancelled();
177
+ let res;
178
+ try {
179
+ // S goes in the body, never in a URL.
180
+ res = await doFetch(poll, {
181
+ method: 'POST',
182
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
183
+ body: JSON.stringify({ secret }),
184
+ signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]),
185
+ });
186
+ }
187
+ catch {
188
+ if (signal.aborted)
189
+ return cancelled();
190
+ res = undefined; // offline for a moment: keep polling until the deadline
191
+ }
192
+ if (res !== undefined) {
193
+ const body = (await res.json().catch(() => ({})));
194
+ if (res.status === 200) {
195
+ const key = body.key;
196
+ if (typeof key !== 'string' || !KEY_SHAPE.test(key)) {
197
+ return {
198
+ ok: false,
199
+ reason: 'failed',
200
+ message: `The site sent no usable key. Check ${ACCOUNT_URL}: a key named "CLI on <date>" may need revoking.`,
201
+ };
202
+ }
203
+ return await keep(ctx, key, say, ui);
204
+ }
205
+ if (res.status === 410) {
206
+ return body.status === 'used'
207
+ ? {
208
+ ok: false,
209
+ reason: 'used',
210
+ message: 'This sign-in request was already used. Run `oort login` again.',
211
+ }
212
+ : {
213
+ ok: false,
214
+ reason: 'expired',
215
+ message: 'This sign-in request expired. Run `oort login` again.',
216
+ };
217
+ }
218
+ if (res.status === 409) {
219
+ return failed(`This account already has the most live keys it can have, so no key was made. Revoke a key at ${ACCOUNT_URL}, then run \`oort login\` again.`);
220
+ }
221
+ if (res.status === 404) {
222
+ return failed('The site does not know this sign-in request. Run `oort login` again.');
223
+ }
224
+ if (res.status === 400) {
225
+ return failed('The site rejected this sign-in request. Update oortmem, then run `oort login` again.');
226
+ }
227
+ if (res.status !== 202 && res.status !== 429 && res.status < 500) {
228
+ return {
229
+ ok: false,
230
+ reason: 'failed',
231
+ message: `The site answered HTTP ${res.status}. Run \`oort login\` again later.`,
232
+ };
233
+ }
234
+ transient = res.status === 202 ? 0 : transient + 1;
235
+ }
236
+ else {
237
+ transient++;
238
+ }
239
+ if (now() >= deadline) {
240
+ return {
241
+ ok: false,
242
+ reason: 'expired',
243
+ message: 'This sign-in request expired. Run `oort login` again.',
244
+ };
245
+ }
246
+ // Every couple of seconds; slower while the site or network is struggling.
247
+ delay = transient > 0 ? Math.min(MAX_DELAY_MS, delay * 1.5) : FIRST_DELAY_MS;
248
+ await sleep(delay, signal);
249
+ }
250
+ }
251
+ finally {
252
+ if (deps.signal === undefined)
253
+ process.off('SIGINT', onSigint);
254
+ }
255
+ }
256
+ /** Stores the key and reads it back, so a Keychain that silently refused is caught. */
257
+ async function keep(ctx, key, say, ui) {
258
+ const code = await ctx.keychain.store('oort', key);
259
+ const back = code === 0 ? await ctx.keychain.read('oort') : undefined;
260
+ if (back !== key) {
261
+ return {
262
+ ok: false,
263
+ reason: 'failed',
264
+ message: `${ctx.keychain.kind === 'file' ? 'Oort could not store the key in credentials.json (see the line above)' : 'The Keychain did not store the key'}, so nothing was saved. The key the site made for this sign-in ("CLI on <date>") is unused: ${REVOKE_HINT}.`,
265
+ };
266
+ }
267
+ say(ui.ok(ctx.keychain.kind === 'file'
268
+ ? `Signed in to Oort Pro. The key is in ${ctx.keychain.where('oort')} (mode 600).`
269
+ : 'Signed in to Oort Pro. The key is in the Keychain as oort.oort.'));
270
+ const routes = await routeSummaries(keyLookup(ctx.io.env, ctx.keychain.read));
271
+ const relayed = Object.values(routes).filter((r) => r.via === 'oort');
272
+ const own = Object.values(routes).filter((r) => r.via === 'vendor');
273
+ say(ui.kv([
274
+ ['relay', relayed.length > 0 ? relayed.map((r) => r.role).join(', ') : 'none'],
275
+ ...(own.length > 0
276
+ ? [
277
+ [
278
+ 'own keys',
279
+ `${own.map((r) => r.role).join(', ')} (a vendor key always wins)`,
280
+ ],
281
+ ]
282
+ : []),
283
+ ['undo', `oort logout (it does not revoke the key; ${REVOKE_HINT})`],
284
+ ], { indent: 2 }));
285
+ if (ctx.io.env['OORT_API_KEY']) {
286
+ say(ui.warn(`OORT_API_KEY is set in this environment and wins over ${ctx.keychain.kind === 'file' ? 'the stored key' : 'the Keychain item'}.`));
287
+ }
288
+ return { ok: true };
289
+ }
290
+ /** `oort login [--no-browser]` */
291
+ export async function loginCommand(opts, ctx) {
292
+ const ui = uiFor(ctx.io);
293
+ ctx.io.out(ui.header('login', 'Oort Pro'));
294
+ const r = await runLogin(ctx, (t) => ctx.io.out(`${t.trimEnd()}\n`), ui, opts);
295
+ if (r.ok)
296
+ return 0;
297
+ ctx.io.err(`oort: ${r.message}\n`);
298
+ return 1;
299
+ }
300
+ /** `oort logout`: removes the stored Oort key (Keychain item `oort.oort`, or its credentials.json entry). It never revokes the key server-side. */
301
+ export async function logoutCommand(ctx) {
302
+ const blocker = keychainBlocker(ctx);
303
+ if (blocker !== undefined) {
304
+ throw new Refusal(ctx.io.env['OORT_NO_KEYCHAIN'] === '1'
305
+ ? 'OORT_NO_KEYCHAIN=1 is set; unset it to remove the stored key.'
306
+ : 'this system has no stored key to remove (the Keychain is macOS, credentials.json is Linux and Windows); unset OORT_API_KEY to stop using Oort Pro.');
307
+ }
308
+ const ui = uiFor(ctx.io);
309
+ const had = (await ctx.keychain.read('oort')) !== undefined;
310
+ const code = had ? await ctx.keychain.remove('oort') : 0;
311
+ if (code !== 0) {
312
+ ctx.io.err(`oort: ${ctx.keychain.label} did not remove the Oort key.\n`);
313
+ return 1;
314
+ }
315
+ ctx.io.out(had
316
+ ? `${ui.ok(ctx.keychain.kind === 'file' ? `Removed the Oort key from ${ctx.keychain.where('oort')}.` : 'Removed the Oort key from the Keychain (oort.oort).')} It still works until you ${REVOKE_HINT}.\n`
317
+ : ctx.keychain.kind === 'file'
318
+ ? `No Oort key in ${ctx.keychain.where('oort')}; nothing changed.\n`
319
+ : 'No Oort key in the Keychain (oort.oort); nothing changed.\n');
320
+ if (ctx.io.env['OORT_API_KEY']) {
321
+ ctx.io.out(ui.warn('OORT_API_KEY is still set in this environment; unset it to stop using Oort Pro.') +
322
+ '\n');
323
+ }
324
+ return 0;
325
+ }
326
+ //# sourceMappingURL=login.js.map
@@ -0,0 +1,14 @@
1
+ import type { McpServer } from '@modelcontextprotocol/server';
2
+ import { type Ctx } from '../util.js';
3
+ /** Serves `factory` on this process's stdin/stdout until the host closes stdin. */
4
+ export type ServeFn = (factory: () => McpServer, onError: (e: Error) => void) => Promise<void>;
5
+ /**
6
+ * `oort mcp [--project <dir>]`: the local MCP server on stdio, for hosts to
7
+ * start. Its scope is the project of the directory it starts in (a host
8
+ * starts it in the workspace, or the config passes `--project`), resolved
9
+ * through the same trust rules as every other command; outside a repository
10
+ * it is global. stdout carries only MCP messages; diagnostics go to stderr.
11
+ */
12
+ export declare function mcpCommand(opts: {
13
+ project?: string;
14
+ }, ctx: Ctx, serve?: ServeFn): Promise<number>;
@@ -0,0 +1,42 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
4
+ import { createOortServer } from '../mcp.js';
5
+ import { Refusal, echo, withWired } from '../util.js';
6
+ const serveProcessStdio = async (factory, onError) => {
7
+ const ended = new Promise((resolve) => {
8
+ process.stdin.once('end', resolve).once('close', resolve);
9
+ });
10
+ const handle = serveStdio(factory, { onerror: onError });
11
+ await ended;
12
+ await handle.close();
13
+ };
14
+ /**
15
+ * `oort mcp [--project <dir>]`: the local MCP server on stdio, for hosts to
16
+ * start. Its scope is the project of the directory it starts in (a host
17
+ * starts it in the workspace, or the config passes `--project`), resolved
18
+ * through the same trust rules as every other command; outside a repository
19
+ * it is global. stdout carries only MCP messages; diagnostics go to stderr.
20
+ */
21
+ export async function mcpCommand(opts, ctx, serve = serveProcessStdio) {
22
+ let cwd = ctx.io.cwd;
23
+ if (opts.project !== undefined && (opts.project === '' || /\$\{[^}]*\}/.test(opts.project))) {
24
+ // `connect` writes `--project ${workspaceFolder}` for Cursor and VS Code; a host that
25
+ // leaves it as is (or empty, with no folder open) gets the directory it started us in.
26
+ ctx.io.err(`oort: the host did not fill in --project ${echo(opts.project)}; using the directory it started oort in.\n`);
27
+ }
28
+ else if (opts.project !== undefined) {
29
+ cwd = path.resolve(ctx.io.cwd, opts.project);
30
+ if (!fs.statSync(cwd, { throwIfNoEntry: false })?.isDirectory()) {
31
+ throw new Refusal(`--project ${echo(opts.project)} is not a directory.`);
32
+ }
33
+ }
34
+ if (ctx.io.stdinIsTTY) {
35
+ ctx.io.err('oort: `oort mcp` speaks MCP on stdin and stdout for an agent host to start; add it to one with `oort connect <host>`.\n');
36
+ }
37
+ return withWired({ ...ctx, io: { ...ctx.io, cwd } }, async (w) => {
38
+ await serve(() => createOortServer({ wired: w }), (e) => ctx.io.err(`oort: mcp: ${e.message}\n`));
39
+ return 0;
40
+ });
41
+ }
42
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +1,15 @@
1
+ import { type Observation } from '@oortmem/core';
2
+ import { type Ctx } from '../util.js';
3
+ export interface ObserveOptions {
4
+ user?: string;
5
+ assistant?: string;
6
+ dryRun?: boolean;
7
+ }
8
+ /** One turn as an Observation, the way `oort observe --user --assistant` builds it. */
9
+ export declare function turnObservation(userText: string, assistantText: string, at?: string): Observation;
10
+ /**
11
+ * `oort observe`: runs the write path on one observation. `--dry-run` only
12
+ * scrubs it and reports what would be redacted or dropped; it opens no store
13
+ * and calls no adapter.
14
+ */
15
+ export declare function observeCommand(opts: ObserveOptions, ctx: Ctx): Promise<number>;
@@ -0,0 +1,73 @@
1
+ import { z } from 'zod';
2
+ import { observe, scrubObservation } from '@oortmem/core';
3
+ import { Refusal, writePath, withWired } from '../util.js';
4
+ const ObservationInput = z.strictObject({
5
+ userText: z.string(),
6
+ assistantText: z.string(),
7
+ toolSummaries: z.array(z.string()).default([]),
8
+ sessionId: z.string().optional(),
9
+ turnRef: z.string().optional(),
10
+ projectId: z.string().optional(),
11
+ at: z
12
+ .string()
13
+ .refine((s) => !Number.isNaN(Date.parse(s)), 'not an ISO timestamp')
14
+ .optional(),
15
+ });
16
+ /** One turn as an Observation, the way `oort observe --user --assistant` builds it. */
17
+ export function turnObservation(userText, assistantText, at = new Date().toISOString()) {
18
+ return { userText, assistantText, toolSummaries: [], at };
19
+ }
20
+ async function readObservation(opts, ctx) {
21
+ const at = new Date().toISOString();
22
+ if (opts.user !== undefined || opts.assistant !== undefined) {
23
+ if (opts.user === undefined || opts.assistant === undefined) {
24
+ throw new Refusal('--user and --assistant go together.');
25
+ }
26
+ return turnObservation(opts.user, opts.assistant, at);
27
+ }
28
+ if (ctx.io.stdinIsTTY) {
29
+ throw new Refusal('pipe an Observation as JSON on stdin, or pass --user and --assistant.');
30
+ }
31
+ let raw;
32
+ try {
33
+ raw = JSON.parse(await ctx.io.readStdin());
34
+ }
35
+ catch {
36
+ throw new Refusal('stdin is not valid JSON.');
37
+ }
38
+ const parsed = ObservationInput.safeParse(raw);
39
+ if (!parsed.success) {
40
+ // Paths and codes only: the issue messages could quote the input.
41
+ const where = parsed.error.issues.map((i) => i.path.join('.') || '(root)').join(', ');
42
+ throw new Refusal(`stdin is not an Observation (check: ${where}).`);
43
+ }
44
+ const { at: given, ...rest } = parsed.data;
45
+ const obs = { ...rest, at: given ?? at };
46
+ return obs;
47
+ }
48
+ /**
49
+ * `oort observe`: runs the write path on one observation. `--dry-run` only
50
+ * scrubs it and reports what would be redacted or dropped; it opens no store
51
+ * and calls no adapter.
52
+ */
53
+ export async function observeCommand(opts, ctx) {
54
+ const obs = await readObservation(opts, ctx);
55
+ if (opts.dryRun === true) {
56
+ const s = scrubObservation(obs);
57
+ const report = { dropped: s.dropped, redactions: s.redactions };
58
+ ctx.io.out(`${JSON.stringify(report, null, 2)}\n`);
59
+ return 0;
60
+ }
61
+ return withWired(ctx, async (w) => {
62
+ const adapters = writePath(w, 'oort observe');
63
+ const result = await observe(obs, w.scope, {
64
+ store: w.store,
65
+ ...adapters,
66
+ config: w.config,
67
+ harness: 'cli',
68
+ });
69
+ ctx.io.out(`${JSON.stringify(result, null, 2)}\n`);
70
+ return 0;
71
+ });
72
+ }
73
+ //# sourceMappingURL=observe.js.map
@@ -0,0 +1,3 @@
1
+ import { type Ctx } from '../util.js';
2
+ /** `oort pin <id>` / `oort unpin <id>`: consolidation never sends a pinned memory to cold. */
3
+ export declare function pinCommand(id: string, pinned: boolean, ctx: Ctx): Promise<number>;
@@ -0,0 +1,16 @@
1
+ import { filterFor, grantFor } from '@oortmem/claude-code';
2
+ import { findMemory, withWired } from '../util.js';
3
+ /** `oort pin <id>` / `oort unpin <id>`: consolidation never sends a pinned memory to cold. */
4
+ export async function pinCommand(id, pinned, ctx) {
5
+ return withWired(ctx, async (w) => {
6
+ const m = await findMemory(w.store, filterFor(w.scope), id);
7
+ if (m.pinned === pinned) {
8
+ ctx.io.out(`${m.id} is already ${pinned ? 'pinned' : 'unpinned'}.\n`);
9
+ return 0;
10
+ }
11
+ await w.store.upsert(grantFor(w.scope), { ...m, pinned, updatedAt: new Date().toISOString() });
12
+ ctx.io.out(`${pinned ? 'Pinned' : 'Unpinned'} ${m.id}.\n`);
13
+ return 0;
14
+ });
15
+ }
16
+ //# sourceMappingURL=pin.js.map
@@ -0,0 +1,15 @@
1
+ import { type Ctx } from '../util.js';
2
+ /**
3
+ * `oort project link [--id <id>]`: trusts a project id for this repository by
4
+ * binding its main root (shared by every worktree) to `--id`, or to the
5
+ * `project.id` in `oort.config.json`. The binding lives in
6
+ * `$OORT_HOME/project-links.json` (0600); without it a repository file's
7
+ * `project.id` is ignored, since a cloned repository could name another
8
+ * project's scope. For the same reason a repository-supplied id already bound
9
+ * to another root is refused; an explicit `--id` is the user's own choice.
10
+ */
11
+ export declare function projectLinkCommand(opts: {
12
+ id?: string;
13
+ }, ctx: Ctx): Promise<number>;
14
+ /** `oort project unlink`: removes this repository's trust binding (back to the derived id). */
15
+ export declare function projectUnlinkCommand(ctx: Ctx): Promise<number>;