@pleasure1234/vesper 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.
- package/dist/index.mjs +655 -0
- package/package.json +35 -4
- package/skills/vesper/SKILL.md +56 -0
- package/README.md +0 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command, InvalidArgumentError } from "@commander-js/extra-typings";
|
|
3
|
+
import { chmod, copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { text } from "node:stream/consumers";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
11
|
+
import { createServer } from "node:http";
|
|
12
|
+
// package.json
|
|
13
|
+
var version = "0.1.1";
|
|
14
|
+
// ../../packages/core/src/constants.ts
|
|
15
|
+
const VISIBILITIES = ["private", "public"];
|
|
16
|
+
const SHELVES = [
|
|
17
|
+
"all",
|
|
18
|
+
"favorites",
|
|
19
|
+
"archive"
|
|
20
|
+
];
|
|
21
|
+
// src/types.ts
|
|
22
|
+
const visibility = z.enum(VISIBILITIES);
|
|
23
|
+
const photo = z.looseObject({
|
|
24
|
+
id: z.string(),
|
|
25
|
+
width: z.number(),
|
|
26
|
+
height: z.number(),
|
|
27
|
+
takenAt: z.number().nullable(),
|
|
28
|
+
geo: z.object({
|
|
29
|
+
lat: z.number(),
|
|
30
|
+
lng: z.number()
|
|
31
|
+
}).nullable(),
|
|
32
|
+
place: z.string().nullable()
|
|
33
|
+
});
|
|
34
|
+
const post = z.object({
|
|
35
|
+
provider: z.string(),
|
|
36
|
+
url: z.string(),
|
|
37
|
+
at: z.string()
|
|
38
|
+
});
|
|
39
|
+
const entryListSchema = z.object({
|
|
40
|
+
entries: z.array(z.object({
|
|
41
|
+
id: z.string(),
|
|
42
|
+
excerpt: z.string(),
|
|
43
|
+
occurredAt: z.number(),
|
|
44
|
+
pinned: z.boolean(),
|
|
45
|
+
favorite: z.boolean(),
|
|
46
|
+
archived: z.boolean(),
|
|
47
|
+
visibility,
|
|
48
|
+
tags: z.array(z.string()),
|
|
49
|
+
photos: z.array(photo),
|
|
50
|
+
published: z.array(post)
|
|
51
|
+
})),
|
|
52
|
+
next: z.string().nullable()
|
|
53
|
+
});
|
|
54
|
+
const entrySchema = z.object({
|
|
55
|
+
meta: z.looseObject({
|
|
56
|
+
id: z.string(),
|
|
57
|
+
visibility,
|
|
58
|
+
tags: z.array(z.string())
|
|
59
|
+
}),
|
|
60
|
+
body: z.string(),
|
|
61
|
+
photos: z.array(photo)
|
|
62
|
+
});
|
|
63
|
+
const photoListSchema = z.object({
|
|
64
|
+
photos: z.array(photo.extend({
|
|
65
|
+
entryId: z.string(),
|
|
66
|
+
caption: z.string(),
|
|
67
|
+
tags: z.array(z.string()),
|
|
68
|
+
occurredAt: z.number()
|
|
69
|
+
})),
|
|
70
|
+
next: z.string().nullable()
|
|
71
|
+
});
|
|
72
|
+
const tagListSchema = z.object({ tags: z.array(z.object({
|
|
73
|
+
name: z.string(),
|
|
74
|
+
count: z.number()
|
|
75
|
+
})) });
|
|
76
|
+
const whoamiSchema = z.object({
|
|
77
|
+
workspace: z.object({
|
|
78
|
+
id: z.string(),
|
|
79
|
+
handle: z.string(),
|
|
80
|
+
timezone: z.string(),
|
|
81
|
+
plan: z.string()
|
|
82
|
+
}),
|
|
83
|
+
role: z.string(),
|
|
84
|
+
principal: z.string(),
|
|
85
|
+
scopes: z.array(z.string()),
|
|
86
|
+
write: z.boolean(),
|
|
87
|
+
unlocked: z.boolean()
|
|
88
|
+
});
|
|
89
|
+
const idSchema = z.object({ id: z.string() });
|
|
90
|
+
const deletedSchema = z.object({ deleted: z.string() });
|
|
91
|
+
const changedSchema = z.object({ changed: z.number() });
|
|
92
|
+
const errorSchema = z.object({
|
|
93
|
+
error: z.string(),
|
|
94
|
+
message: z.string()
|
|
95
|
+
});
|
|
96
|
+
const credentialsSchema = z.object({
|
|
97
|
+
origin: z.string(),
|
|
98
|
+
clientId: z.string(),
|
|
99
|
+
tokenEndpoint: z.string(),
|
|
100
|
+
revocationEndpoint: z.string().nullable(),
|
|
101
|
+
accessToken: z.string(),
|
|
102
|
+
refreshToken: z.string().nullable(),
|
|
103
|
+
expiresAt: z.number()
|
|
104
|
+
});
|
|
105
|
+
const metadataSchema = z.object({
|
|
106
|
+
authorization_endpoint: z.string(),
|
|
107
|
+
token_endpoint: z.string(),
|
|
108
|
+
registration_endpoint: z.string(),
|
|
109
|
+
revocation_endpoint: z.string().nullable().default(null)
|
|
110
|
+
});
|
|
111
|
+
const resourceSchema = z.object({ authorization_servers: z.array(z.string()).min(1) });
|
|
112
|
+
const clientSchema = z.object({ client_id: z.string() });
|
|
113
|
+
const oauthErrorSchema = z.object({
|
|
114
|
+
error: z.string(),
|
|
115
|
+
error_description: z.string().nullable().default(null)
|
|
116
|
+
});
|
|
117
|
+
const tokenSchema = z.object({
|
|
118
|
+
access_token: z.string(),
|
|
119
|
+
refresh_token: z.string().nullable().default(null),
|
|
120
|
+
expires_in: z.number()
|
|
121
|
+
});
|
|
122
|
+
z.object({
|
|
123
|
+
body: z.string().nullable(),
|
|
124
|
+
tags: z.array(z.string()).nullable(),
|
|
125
|
+
visibility: visibility.nullable(),
|
|
126
|
+
pinned: z.boolean().nullable(),
|
|
127
|
+
favorite: z.boolean().nullable(),
|
|
128
|
+
archived: z.boolean().nullable()
|
|
129
|
+
});
|
|
130
|
+
const dateSchema = z.iso.date();
|
|
131
|
+
const countSchema = z.coerce.number().int().positive();
|
|
132
|
+
const visibilitySchema = visibility;
|
|
133
|
+
const shelfSchema = z.enum(SHELVES);
|
|
134
|
+
const addressSchema = z.object({ port: z.number() });
|
|
135
|
+
const MAX_WAIT_SECONDS = 60;
|
|
136
|
+
var ApiError = class extends Error {
|
|
137
|
+
status;
|
|
138
|
+
code;
|
|
139
|
+
constructor(status, code, message) {
|
|
140
|
+
super(message);
|
|
141
|
+
this.status = status;
|
|
142
|
+
this.code = code;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
146
|
+
function urlFor(origin, path, query) {
|
|
147
|
+
const url = new URL(path, origin);
|
|
148
|
+
for (const [key, value] of Object.entries(query)) if (value !== null && value !== "") url.searchParams.set(key, value);
|
|
149
|
+
return url;
|
|
150
|
+
}
|
|
151
|
+
function parseJson(text) {
|
|
152
|
+
try {
|
|
153
|
+
return JSON.parse(text);
|
|
154
|
+
} catch {
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async function failure(response) {
|
|
159
|
+
const text = await response.text();
|
|
160
|
+
const parsed = errorSchema.safeParse(parseJson(text));
|
|
161
|
+
return parsed.success ? new ApiError(response.status, parsed.data.error, parsed.data.message) : new ApiError(response.status, "http_error", text.slice(0, 300) || response.statusText);
|
|
162
|
+
}
|
|
163
|
+
function createClient(options) {
|
|
164
|
+
async function request(method, path, query, body) {
|
|
165
|
+
let token = await options.token();
|
|
166
|
+
let renewed = false;
|
|
167
|
+
let retried = false;
|
|
168
|
+
for (;;) {
|
|
169
|
+
const headers = new Headers({
|
|
170
|
+
authorization: `Bearer ${token}`,
|
|
171
|
+
accept: "application/json"
|
|
172
|
+
});
|
|
173
|
+
if (body !== null) headers.set("content-type", "application/json");
|
|
174
|
+
const response = await fetch(urlFor(options.origin, path, query), {
|
|
175
|
+
method,
|
|
176
|
+
headers,
|
|
177
|
+
body: body === null ? null : JSON.stringify(body)
|
|
178
|
+
});
|
|
179
|
+
if (response.status === 401 && !renewed && options.renew) {
|
|
180
|
+
renewed = true;
|
|
181
|
+
token = await options.renew();
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (response.status === 429 && !retried) {
|
|
185
|
+
retried = true;
|
|
186
|
+
const seconds = Number(response.headers.get("retry-after")) || 10;
|
|
187
|
+
await options.sleep(Math.min(seconds, MAX_WAIT_SECONDS) * 1e3);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
if (!response.ok) throw await failure(response);
|
|
191
|
+
return response;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const read = async (schema, response) => schema.parse(await response.json());
|
|
195
|
+
return {
|
|
196
|
+
get: async (path, schema, query = {}) => read(schema, await request("GET", path, query, null)),
|
|
197
|
+
post: async (path, schema, body) => read(schema, await request("POST", path, {}, body)),
|
|
198
|
+
patch: async (path, schema, body) => read(schema, await request("PATCH", path, {}, body)),
|
|
199
|
+
delete: async (path, schema) => read(schema, await request("DELETE", path, {}, null)),
|
|
200
|
+
download: (path, query) => request("GET", path, query, null)
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
async function collect(load, first, all, max) {
|
|
204
|
+
const items = [];
|
|
205
|
+
let cursor = first;
|
|
206
|
+
for (;;) {
|
|
207
|
+
const page = await load(cursor);
|
|
208
|
+
items.push(...page.items);
|
|
209
|
+
cursor = page.next;
|
|
210
|
+
if (!all || !cursor || items.length >= max) return {
|
|
211
|
+
items,
|
|
212
|
+
next: cursor
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
// src/oauth.ts
|
|
217
|
+
const SCOPE = "entries:read entries:write offline_access";
|
|
218
|
+
const WAIT_MS = 3e5;
|
|
219
|
+
var OAuthError = class extends Error {};
|
|
220
|
+
async function read(schema, response) {
|
|
221
|
+
if (!response.ok) throw new OAuthError(`${response.status}: ${await reason(response)}`);
|
|
222
|
+
return schema.parse(await response.json());
|
|
223
|
+
}
|
|
224
|
+
async function reason(response) {
|
|
225
|
+
const text = await response.text();
|
|
226
|
+
if (!String(response.headers.get("content-type")).includes("json")) return text.slice(0, 300);
|
|
227
|
+
const parsed = oauthErrorSchema.safeParse(JSON.parse(text));
|
|
228
|
+
if (!parsed.success) return text.slice(0, 300);
|
|
229
|
+
const { error, error_description } = parsed.data;
|
|
230
|
+
return error_description === null ? error : `${error_description} (${error})`;
|
|
231
|
+
}
|
|
232
|
+
const form = (fields) => ({
|
|
233
|
+
method: "POST",
|
|
234
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
235
|
+
body: new URLSearchParams(fields)
|
|
236
|
+
});
|
|
237
|
+
const resourceOf = (origin) => `${origin}/mcp`;
|
|
238
|
+
async function discover(origin) {
|
|
239
|
+
const resource = await read(resourceSchema, await fetch(`${origin}/.well-known/oauth-protected-resource/mcp`));
|
|
240
|
+
const issuer = new URL(resource.authorization_servers[0] || origin);
|
|
241
|
+
return read(metadataSchema, await fetch(`${origin}/.well-known/oauth-authorization-server${issuer.pathname}`));
|
|
242
|
+
}
|
|
243
|
+
function pkce() {
|
|
244
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
245
|
+
return {
|
|
246
|
+
verifier,
|
|
247
|
+
challenge: createHash("sha256").update(verifier).digest("base64url")
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
function openBrowser(url) {
|
|
251
|
+
const command = process.platform === "darwin" ? {
|
|
252
|
+
file: "open",
|
|
253
|
+
args: [url]
|
|
254
|
+
} : process.platform === "win32" ? {
|
|
255
|
+
file: "cmd",
|
|
256
|
+
args: [
|
|
257
|
+
"/c",
|
|
258
|
+
"start",
|
|
259
|
+
"",
|
|
260
|
+
url
|
|
261
|
+
]
|
|
262
|
+
} : {
|
|
263
|
+
file: "xdg-open",
|
|
264
|
+
args: [url]
|
|
265
|
+
};
|
|
266
|
+
const child = spawn(command.file, command.args, {
|
|
267
|
+
stdio: "ignore",
|
|
268
|
+
detached: true
|
|
269
|
+
});
|
|
270
|
+
child.on("error", () => {});
|
|
271
|
+
child.unref();
|
|
272
|
+
}
|
|
273
|
+
const page = (ok) => `<!doctype html>
|
|
274
|
+
<html lang="en">
|
|
275
|
+
<meta charset="utf-8">
|
|
276
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
277
|
+
<meta name="color-scheme" content="light dark">
|
|
278
|
+
<title>Vesper</title>
|
|
279
|
+
<style>
|
|
280
|
+
:root { --paper: #f6f1e7; --card: #fffdf8; --ink: #2b2620; --muted: #7a7065; --line: #e8dfd0;
|
|
281
|
+
--accent: ${ok ? "#5f7a52" : "#b4553f"}; --tape: rgb(222 196 140 / 0.7); }
|
|
282
|
+
@media (prefers-color-scheme: dark) {
|
|
283
|
+
:root { --paper: #1c1916; --card: #24201c; --ink: #ece4d7; --muted: #a39887; --line: #3a332c;
|
|
284
|
+
--tape: rgb(170 140 90 / 0.45); }
|
|
285
|
+
}
|
|
286
|
+
* { box-sizing: border-box; }
|
|
287
|
+
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 1.5rem;
|
|
288
|
+
background: var(--paper); color: var(--ink); font: 1rem/1.6 ui-serif, Georgia, "Songti SC", serif; }
|
|
289
|
+
main { position: relative; width: min(26rem, 100%); padding: 2.5rem 2rem 2rem; background: var(--card);
|
|
290
|
+
border: 1px solid var(--line); border-radius: 0.375rem; transform: rotate(-0.6deg);
|
|
291
|
+
box-shadow: 0 1px 2px rgb(0 0 0 / 0.06), 0 12px 32px -12px rgb(0 0 0 / 0.18);
|
|
292
|
+
background-image: repeating-linear-gradient(transparent 0 1.55rem, var(--line) 1.55rem 1.6rem); }
|
|
293
|
+
main::before { content: ""; position: absolute; top: -0.7rem; left: 50%; width: 6rem; height: 1.4rem;
|
|
294
|
+
background: var(--tape); transform: translateX(-50%) rotate(2deg); }
|
|
295
|
+
.mark { width: 2.75rem; height: 2.75rem; border-radius: 50%; display: grid; place-items: center;
|
|
296
|
+
border: 2px solid var(--accent); color: var(--accent); margin-bottom: 1rem; }
|
|
297
|
+
h1 { margin: 0 0 0.25rem; font-size: 1.5rem; font-weight: 600; letter-spacing: -0.01em; }
|
|
298
|
+
p { margin: 0; color: var(--muted); }
|
|
299
|
+
small { display: block; margin-top: 1.5rem; font: 0.75rem/1.4 ui-monospace, Menlo, monospace; color: var(--muted); }
|
|
300
|
+
</style>
|
|
301
|
+
<main>
|
|
302
|
+
<div class="mark" aria-hidden="true">
|
|
303
|
+
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">${ok ? "<path d=\"M20 6 9 17l-5-5\"/>" : "<path d=\"M18 6 6 18M6 6l12 12\"/>"}</svg>
|
|
304
|
+
</div>
|
|
305
|
+
<h1>${ok ? "You're signed in" : "Sign-in didn't finish"}</h1>
|
|
306
|
+
<p>${ok ? "The Vesper CLI can use your journal now. You can close this tab and go back to the terminal." : "Something went wrong on the way back. Check the terminal for details, then run vesper login again."}</p>
|
|
307
|
+
<small>vesper · ${ok ? "signed in" : "sign-in failed"}</small>
|
|
308
|
+
</main>
|
|
309
|
+
</html>`;
|
|
310
|
+
function listen(state) {
|
|
311
|
+
return new Promise((ready, fail) => {
|
|
312
|
+
const settle = Promise.withResolvers();
|
|
313
|
+
const server = createServer((request, response) => {
|
|
314
|
+
const url = new URL(request.url || "/", "http://127.0.0.1");
|
|
315
|
+
if (url.pathname !== "/callback") {
|
|
316
|
+
response.writeHead(404).end();
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
const error = url.searchParams.get("error");
|
|
320
|
+
const code = url.searchParams.get("code");
|
|
321
|
+
const matched = url.searchParams.get("state") === state;
|
|
322
|
+
const ok = !error && code !== null && matched;
|
|
323
|
+
response.writeHead(ok ? 200 : 400, { "content-type": "text/html; charset=utf-8" }).end(page(ok));
|
|
324
|
+
server.close();
|
|
325
|
+
clearTimeout(timer);
|
|
326
|
+
if (code !== null && ok) settle.resolve(code);
|
|
327
|
+
else settle.reject(new OAuthError(error || "The callback did not match this sign-in."));
|
|
328
|
+
});
|
|
329
|
+
const timer = setTimeout(() => {
|
|
330
|
+
server.close();
|
|
331
|
+
settle.reject(new OAuthError("Timed out waiting for the browser."));
|
|
332
|
+
}, WAIT_MS);
|
|
333
|
+
server.on("error", fail);
|
|
334
|
+
server.listen(0, "127.0.0.1", () => {
|
|
335
|
+
const { port } = addressSchema.parse(server.address());
|
|
336
|
+
ready({
|
|
337
|
+
redirectUri: `http://127.0.0.1:${port}/callback`,
|
|
338
|
+
code: settle.promise
|
|
339
|
+
});
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
async function login(origin, notify) {
|
|
344
|
+
const metadata = await discover(origin);
|
|
345
|
+
const state = randomBytes(16).toString("base64url");
|
|
346
|
+
const callback = await listen(state);
|
|
347
|
+
const client = await read(clientSchema, await fetch(metadata.registration_endpoint, {
|
|
348
|
+
method: "POST",
|
|
349
|
+
headers: { "content-type": "application/json" },
|
|
350
|
+
body: JSON.stringify({
|
|
351
|
+
client_name: "Vesper CLI",
|
|
352
|
+
application_type: "native",
|
|
353
|
+
redirect_uris: [callback.redirectUri],
|
|
354
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
355
|
+
response_types: ["code"],
|
|
356
|
+
token_endpoint_auth_method: "none",
|
|
357
|
+
scope: SCOPE
|
|
358
|
+
})
|
|
359
|
+
}));
|
|
360
|
+
const { verifier, challenge } = pkce();
|
|
361
|
+
const authorize = new URL(metadata.authorization_endpoint);
|
|
362
|
+
authorize.search = new URLSearchParams({
|
|
363
|
+
response_type: "code",
|
|
364
|
+
client_id: client.client_id,
|
|
365
|
+
redirect_uri: callback.redirectUri,
|
|
366
|
+
scope: SCOPE,
|
|
367
|
+
state,
|
|
368
|
+
code_challenge: challenge,
|
|
369
|
+
code_challenge_method: "S256",
|
|
370
|
+
resource: resourceOf(origin)
|
|
371
|
+
}).toString();
|
|
372
|
+
notify(authorize.toString());
|
|
373
|
+
openBrowser(authorize.toString());
|
|
374
|
+
const tokens = await read(tokenSchema, await fetch(metadata.token_endpoint, form({
|
|
375
|
+
grant_type: "authorization_code",
|
|
376
|
+
code: await callback.code,
|
|
377
|
+
redirect_uri: callback.redirectUri,
|
|
378
|
+
client_id: client.client_id,
|
|
379
|
+
code_verifier: verifier,
|
|
380
|
+
resource: resourceOf(origin)
|
|
381
|
+
})));
|
|
382
|
+
return {
|
|
383
|
+
origin,
|
|
384
|
+
clientId: client.client_id,
|
|
385
|
+
tokenEndpoint: metadata.token_endpoint,
|
|
386
|
+
revocationEndpoint: metadata.revocation_endpoint,
|
|
387
|
+
accessToken: tokens.access_token,
|
|
388
|
+
refreshToken: tokens.refresh_token,
|
|
389
|
+
expiresAt: Date.now() + tokens.expires_in * 1e3
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
async function refresh(credentials) {
|
|
393
|
+
if (!credentials.refreshToken) throw new OAuthError("The sign-in expired. Run `vesper login`.");
|
|
394
|
+
const response = await fetch(credentials.tokenEndpoint, form({
|
|
395
|
+
grant_type: "refresh_token",
|
|
396
|
+
refresh_token: credentials.refreshToken,
|
|
397
|
+
client_id: credentials.clientId,
|
|
398
|
+
resource: resourceOf(credentials.origin)
|
|
399
|
+
}));
|
|
400
|
+
if (response.status === 400 || response.status === 401) throw new OAuthError(`The sign-in expired: ${await reason(response)}. Run \`vesper login\`.`);
|
|
401
|
+
const tokens = await read(tokenSchema, response);
|
|
402
|
+
return {
|
|
403
|
+
...credentials,
|
|
404
|
+
accessToken: tokens.access_token,
|
|
405
|
+
refreshToken: tokens.refresh_token || credentials.refreshToken,
|
|
406
|
+
expiresAt: Date.now() + tokens.expires_in * 1e3
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
async function revoke(credentials) {
|
|
410
|
+
const endpoint = credentials.revocationEndpoint;
|
|
411
|
+
if (!endpoint) return;
|
|
412
|
+
for (const token of [credentials.refreshToken, credentials.accessToken]) if (token) await fetch(endpoint, form({
|
|
413
|
+
token,
|
|
414
|
+
client_id: credentials.clientId
|
|
415
|
+
})).catch(() => null);
|
|
416
|
+
}
|
|
417
|
+
// src/store.ts
|
|
418
|
+
const configDir = () => join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "vesper");
|
|
419
|
+
const authFile = () => join(configDir(), "auth.json");
|
|
420
|
+
async function loadCredentials() {
|
|
421
|
+
const text = await readFile(authFile(), "utf8").catch(() => null);
|
|
422
|
+
if (text === null) return null;
|
|
423
|
+
const parsed = credentialsSchema.safeParse(JSON.parse(text));
|
|
424
|
+
return parsed.success ? parsed.data : null;
|
|
425
|
+
}
|
|
426
|
+
async function saveCredentials(credentials) {
|
|
427
|
+
const file = authFile();
|
|
428
|
+
await mkdir(dirname(file), {
|
|
429
|
+
recursive: true,
|
|
430
|
+
mode: 448
|
|
431
|
+
});
|
|
432
|
+
await writeFile(file, JSON.stringify(credentials, null, 2), { mode: 384 });
|
|
433
|
+
await chmod(file, 384);
|
|
434
|
+
}
|
|
435
|
+
const clearCredentials = () => rm(authFile(), { force: true });
|
|
436
|
+
// src/session.ts
|
|
437
|
+
const EARLY_MS = 6e4;
|
|
438
|
+
const originOf = (flag) => (flag || process.env.VESPER_URL || "https://noted-this.date").replace(/\/+$/, "");
|
|
439
|
+
async function openClient(flag) {
|
|
440
|
+
const personal = process.env.VESPER_TOKEN;
|
|
441
|
+
if (personal) return createClient({
|
|
442
|
+
origin: originOf(flag),
|
|
443
|
+
token: async () => personal,
|
|
444
|
+
renew: null,
|
|
445
|
+
sleep: wait
|
|
446
|
+
});
|
|
447
|
+
const saved = await loadCredentials();
|
|
448
|
+
if (!saved) throw new OAuthError("Not signed in. Run `vesper login`.");
|
|
449
|
+
if (flag && originOf(flag) !== saved.origin) throw new OAuthError(`Signed in to ${saved.origin}. Run \`vesper login --url ${flag}\`.`);
|
|
450
|
+
let credentials = saved;
|
|
451
|
+
const renew = async () => {
|
|
452
|
+
credentials = await refresh(credentials);
|
|
453
|
+
await saveCredentials(credentials);
|
|
454
|
+
return credentials.accessToken;
|
|
455
|
+
};
|
|
456
|
+
return createClient({
|
|
457
|
+
origin: credentials.origin,
|
|
458
|
+
token: async () => credentials.expiresAt - EARLY_MS > Date.now() ? credentials.accessToken : renew(),
|
|
459
|
+
renew: credentials.refreshToken ? renew : null,
|
|
460
|
+
sleep: wait
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
// src/index.ts
|
|
464
|
+
const MAX_ITEMS = 500;
|
|
465
|
+
function print(value) {
|
|
466
|
+
process.stdout.write(`${JSON.stringify(value, null, process.stdout.isTTY ? 2 : 0)}\n`);
|
|
467
|
+
}
|
|
468
|
+
const parse = (schema, expected) => (value) => {
|
|
469
|
+
const parsed = schema.safeParse(value);
|
|
470
|
+
if (!parsed.success) throw new InvalidArgumentError(`Expected ${expected}.`);
|
|
471
|
+
return parsed.data;
|
|
472
|
+
};
|
|
473
|
+
const day = parse(dateSchema, "a day as YYYY-MM-DD");
|
|
474
|
+
const addTag = (value, previous = []) => [...previous, value];
|
|
475
|
+
async function readBody(inline, flags) {
|
|
476
|
+
if (flags.file) return readFile(flags.file, "utf8");
|
|
477
|
+
if (flags.stdin) return text(process.stdin);
|
|
478
|
+
return inline.join(" ");
|
|
479
|
+
}
|
|
480
|
+
const program = new Command().name("vesper").description("Read and write your Vesper entries. Output is JSON.").version(version).option("--url <origin>", "Vesper server (default https://noted-this.date, or VESPER_URL)").showHelpAfterError();
|
|
481
|
+
const urlFlag = () => program.opts().url || null;
|
|
482
|
+
const client = () => openClient(urlFlag());
|
|
483
|
+
const listCommand = (name, description) => new Command(name).description(description).option("--tag <tag>", "only entries with this tag").option("--from <date>", "from this day (YYYY-MM-DD, UTC)", day).option("--to <date>", "to this day, inclusive", day).option("--cursor <next>", "continue from a page's `next`").option("--all", "follow `next` until the end").option("--max <count>", `stop --all after this many items (default ${MAX_ITEMS})`, parse(countSchema, "a positive whole number"));
|
|
484
|
+
const listQuery = (flags) => ({
|
|
485
|
+
tag: flags.tag || null,
|
|
486
|
+
fromDate: flags.from || null,
|
|
487
|
+
toDate: flags.to || null
|
|
488
|
+
});
|
|
489
|
+
async function listEntries(api, flags, extra) {
|
|
490
|
+
const page = await collect(async (before) => {
|
|
491
|
+
const list = await api.get("/api/entries", entryListSchema, {
|
|
492
|
+
...listQuery(flags),
|
|
493
|
+
...extra,
|
|
494
|
+
before
|
|
495
|
+
});
|
|
496
|
+
return {
|
|
497
|
+
items: list.entries,
|
|
498
|
+
next: list.next
|
|
499
|
+
};
|
|
500
|
+
}, flags.cursor || null, Boolean(flags.all), flags.max || MAX_ITEMS);
|
|
501
|
+
return {
|
|
502
|
+
entries: page.items,
|
|
503
|
+
next: page.next
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
program.command("login").description("Sign in through the browser and pick the workspace to use").action(async () => {
|
|
507
|
+
const origin = originOf(urlFlag());
|
|
508
|
+
const credentials = await login(origin, (url) => process.stderr.write(`Opening your browser to sign in. If it does not open, visit:\n${url}\n`));
|
|
509
|
+
await saveCredentials(credentials);
|
|
510
|
+
const me = await createClient({
|
|
511
|
+
origin,
|
|
512
|
+
token: async () => credentials.accessToken,
|
|
513
|
+
renew: null,
|
|
514
|
+
sleep: wait
|
|
515
|
+
}).get("/api/workspace", whoamiSchema);
|
|
516
|
+
if (!me.write) process.stderr.write(`@${me.workspace.handle} is on the ${me.workspace.plan} plan, so this sign-in is read-only. Writing through the API needs Pro.\n`);
|
|
517
|
+
print(me);
|
|
518
|
+
});
|
|
519
|
+
program.command("logout").description("Revoke the saved sign-in and forget it").action(async () => {
|
|
520
|
+
const credentials = await loadCredentials();
|
|
521
|
+
if (credentials) await revoke(credentials);
|
|
522
|
+
await clearCredentials();
|
|
523
|
+
print({ signedOut: true });
|
|
524
|
+
});
|
|
525
|
+
program.command("status").description("Check the server, whether this CLI is signed in, and the workspace it uses").action(async () => {
|
|
526
|
+
const saved = await loadCredentials();
|
|
527
|
+
const via = process.env.VESPER_TOKEN ? "token" : saved ? "oauth" : null;
|
|
528
|
+
const base = {
|
|
529
|
+
version,
|
|
530
|
+
server: saved && !process.env.VESPER_TOKEN ? saved.origin : originOf(urlFlag()),
|
|
531
|
+
via
|
|
532
|
+
};
|
|
533
|
+
if (!via) return print({
|
|
534
|
+
...base,
|
|
535
|
+
signedIn: false,
|
|
536
|
+
hint: "Run `vesper login`."
|
|
537
|
+
});
|
|
538
|
+
try {
|
|
539
|
+
const me = await (await client()).get("/api/workspace", whoamiSchema);
|
|
540
|
+
print({
|
|
541
|
+
...base,
|
|
542
|
+
signedIn: true,
|
|
543
|
+
workspace: me.workspace.handle,
|
|
544
|
+
plan: me.workspace.plan,
|
|
545
|
+
write: me.write,
|
|
546
|
+
renewsBefore: saved && via === "oauth" ? new Date(saved.expiresAt).toISOString() : null
|
|
547
|
+
});
|
|
548
|
+
} catch (error) {
|
|
549
|
+
if (!(error instanceof OAuthError || error instanceof ApiError && error.status === 401)) throw error;
|
|
550
|
+
print({
|
|
551
|
+
...base,
|
|
552
|
+
signedIn: false,
|
|
553
|
+
hint: `${error.message} Run \`vesper login\`.`
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
program.command("whoami").description("Show the workspace, plan, role and whether this sign-in can write").action(async () => print(await (await client()).get("/api/workspace", whoamiSchema)));
|
|
558
|
+
const entries = program.command("entries").alias("entry").description("Journal entries");
|
|
559
|
+
entries.addCommand(listCommand("list", "Entries newest first, 50 per page").option("--in <shelf>", "all, favorites or archive", parse(shelfSchema, "all, favorites or archive")).option("--pinned", "only pinned entries").action(async (flags) => print(await listEntries(await client(), flags, {
|
|
560
|
+
in: flags.in || null,
|
|
561
|
+
pinned: flags.pinned ? "true" : null
|
|
562
|
+
}))));
|
|
563
|
+
entries.addCommand(listCommand("search", "Entries whose text or tags contain the query").argument("<query...>").action(async (query, flags) => print(await listEntries(await client(), flags, { q: query.join(" ") }))));
|
|
564
|
+
entries.command("get").description("One entry with its full Markdown, metadata and photos").argument("<id>").action(async (id) => print(await (await client()).get(`/api/entries/${id}`, entrySchema)));
|
|
565
|
+
entries.command("create").description("Write a new entry in Markdown (Pro)").argument("[text...]").option("--file <path>", "read the body from a file").option("--stdin", "read the body from standard input").option("--tag <tag>", "add a tag; repeat for more", addTag).option("--public", "share it (Pro)").action(async (text, flags) => {
|
|
566
|
+
const body = (await readBody(text, flags)).trim();
|
|
567
|
+
if (!body) throw new Error("Write something: pass text, --file or --stdin.");
|
|
568
|
+
print(await (await client()).post("/api/entries", idSchema, {
|
|
569
|
+
body,
|
|
570
|
+
tags: flags.tag || [],
|
|
571
|
+
visibility: flags.public ? "public" : "private"
|
|
572
|
+
}));
|
|
573
|
+
});
|
|
574
|
+
entries.command("update").description("Change an entry; only what you pass changes (Pro)").argument("<id>").argument("[text...]", "new body").option("--file <path>", "read the new body from a file").option("--stdin", "read the new body from standard input").option("--tag <tag>", "replace the tags; repeat for more", addTag).option("--clear-tags", "remove every tag").option("--visibility <visibility>", "private or public", parse(visibilitySchema, "private or public")).option("--pin", "pin it").option("--unpin", "unpin it").option("--favorite", "mark it a favorite").option("--unfavorite", "unmark it").option("--archive", "archive it").option("--unarchive", "bring it back from the archive").action(async (id, text, flags) => {
|
|
575
|
+
const body = (await readBody(text, flags)).trim();
|
|
576
|
+
const toggle = (on, off) => on ? true : off ? false : null;
|
|
577
|
+
const patch = {
|
|
578
|
+
body: body || null,
|
|
579
|
+
tags: flags.clearTags ? [] : flags.tag || null,
|
|
580
|
+
visibility: flags.visibility || null,
|
|
581
|
+
pinned: toggle(Boolean(flags.pin), Boolean(flags.unpin)),
|
|
582
|
+
favorite: toggle(Boolean(flags.favorite), Boolean(flags.unfavorite)),
|
|
583
|
+
archived: toggle(Boolean(flags.archive), Boolean(flags.unarchive))
|
|
584
|
+
};
|
|
585
|
+
if (Object.values(patch).every((value) => value === null)) throw new Error("Nothing to change.");
|
|
586
|
+
print(await (await client()).patch(`/api/entries/${id}`, idSchema, patch));
|
|
587
|
+
});
|
|
588
|
+
entries.command("delete").description("Delete an entry for good, with photos no other entry uses (Pro)").argument("<id>").requiredOption("--yes", "confirm the deletion").action(async (id) => print(await (await client()).delete(`/api/entries/${id}`, deletedSchema)));
|
|
589
|
+
const tags = program.command("tags").alias("tag").description("Tags");
|
|
590
|
+
tags.command("list").description("Tags and how many entries use each").action(async () => print(await (await client()).get("/api/tags", tagListSchema)));
|
|
591
|
+
tags.command("rename").description("Rename a tag on every entry (Pro)").argument("<from>").argument("<to>").action(async (from, to) => print(await (await client()).patch("/api/tags", changedSchema, {
|
|
592
|
+
from,
|
|
593
|
+
to
|
|
594
|
+
})));
|
|
595
|
+
tags.command("remove").description("Remove a tag from every entry (Pro)").argument("<tag>").action(async (from) => print(await (await client()).patch("/api/tags", changedSchema, {
|
|
596
|
+
from,
|
|
597
|
+
to: null
|
|
598
|
+
})));
|
|
599
|
+
const photos = program.command("photos").alias("photo").description("Photos");
|
|
600
|
+
photos.addCommand(listCommand("list", "Photos newest first, from 24 entries per page").action(async (flags) => {
|
|
601
|
+
const api = await client();
|
|
602
|
+
const page = await collect(async (before) => {
|
|
603
|
+
const list = await api.get("/api/photos", photoListSchema, {
|
|
604
|
+
...listQuery(flags),
|
|
605
|
+
before
|
|
606
|
+
});
|
|
607
|
+
return {
|
|
608
|
+
items: list.photos,
|
|
609
|
+
next: list.next
|
|
610
|
+
};
|
|
611
|
+
}, flags.cursor || null, Boolean(flags.all), flags.max || MAX_ITEMS);
|
|
612
|
+
print({
|
|
613
|
+
photos: page.items,
|
|
614
|
+
next: page.next
|
|
615
|
+
});
|
|
616
|
+
}));
|
|
617
|
+
photos.command("download").description("Save a photo's original, or its thumbnail").argument("<id>").option("--thumb", "the small JPEG thumbnail instead").option("-o, --output <path>", "where to save it (default <id>.<ext>)").action(async (id, flags) => {
|
|
618
|
+
const response = await (await client()).download(`/api/photos/${id}`, { size: flags.thumb ? "thumb" : "original" });
|
|
619
|
+
const type = response.headers.get("content-type") || "application/octet-stream";
|
|
620
|
+
const [, subtype = "bin"] = /\/([\w.+-]+)/.exec(type) || [];
|
|
621
|
+
const output = flags.output || `${id}.${subtype === "jpeg" ? "jpg" : subtype}`;
|
|
622
|
+
if (!response.body) throw new Error("The server sent no image.");
|
|
623
|
+
await writeFile(output, response.body);
|
|
624
|
+
print({
|
|
625
|
+
id,
|
|
626
|
+
saved: output,
|
|
627
|
+
type
|
|
628
|
+
});
|
|
629
|
+
});
|
|
630
|
+
program.command("skill").description("Install the Vesper agent skill for Claude Code and other agents").option("--dir <path>", "skills directory (default ~/.claude/skills)").action(async (flags) => {
|
|
631
|
+
const target = join(flags.dir || join(homedir(), ".claude", "skills"), "vesper");
|
|
632
|
+
await mkdir(target, { recursive: true });
|
|
633
|
+
const source = fileURLToPath(new URL("../skills/vesper/SKILL.md", import.meta.url));
|
|
634
|
+
await copyFile(source, join(target, "SKILL.md"));
|
|
635
|
+
print({ installed: join(target, "SKILL.md") });
|
|
636
|
+
});
|
|
637
|
+
function report(error) {
|
|
638
|
+
if (error instanceof ApiError) {
|
|
639
|
+
const hint = error.status === 403 && /needs Pro/.test(error.message) ? " Free workspaces are read-only through the API." : "";
|
|
640
|
+
return {
|
|
641
|
+
error: error.code,
|
|
642
|
+
status: error.status,
|
|
643
|
+
message: error.message + hint
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
return {
|
|
647
|
+
error: error instanceof OAuthError ? "auth" : "error",
|
|
648
|
+
message: error.message
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
program.parseAsync().catch((error) => {
|
|
652
|
+
process.stderr.write(`${JSON.stringify(report(error))}\n`);
|
|
653
|
+
process.exit(1);
|
|
654
|
+
});
|
|
655
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pleasure1234/vesper",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Read and write your Vesper entries from the terminal.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/vesper-shop/vesper-cloud.git",
|
|
9
|
+
"directory": "apps/cli"
|
|
10
|
+
},
|
|
11
|
+
"bin": {
|
|
12
|
+
"vesper": "dist/index.mjs"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"skills"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "vp pack src/index.ts --clean",
|
|
24
|
+
"prepublishOnly": "pnpm build"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@commander-js/extra-typings": "15.1.0",
|
|
28
|
+
"commander": "15.1.0",
|
|
29
|
+
"zod": "4.6.7"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@vesper/core": "workspace:*"
|
|
33
|
+
},
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=22.12.0"
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: vesper
|
|
3
|
+
description: Use the `vesper` CLI to read, search and (on Pro) write the user's Vesper entries, tags and photos at noted-this.date. Use when the user asks about what they wrote, recorded or photographed, or wants an entry created or changed.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Vesper CLI
|
|
7
|
+
|
|
8
|
+
`vesper` talks to the user's Vesper workspace. Every data command prints JSON on stdout; failures print
|
|
9
|
+
`{"error","message"}` on stderr and exit nonzero. Run `vesper <command> --help` for exact flags.
|
|
10
|
+
|
|
11
|
+
## Before anything
|
|
12
|
+
|
|
13
|
+
- Run `vesper whoami`. `"write": false` means the sign-in is read-only (Free plan, or no write scope):
|
|
14
|
+
do not try writes, tell the user writing needs Pro.
|
|
15
|
+
- `{"error":"auth"}` means nobody is signed in. Ask the user to run `vesper login` themselves; it opens a
|
|
16
|
+
browser where they sign in and unlock their workspace. Never ask for their passkey, token or password.
|
|
17
|
+
- `VESPER_TOKEN` (a `vsp_` personal token) overrides the saved sign-in. Never print or pass tokens as arguments.
|
|
18
|
+
|
|
19
|
+
## Reading
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
vesper entries list [--tag t] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--in favorites|archive] [--pinned]
|
|
23
|
+
vesper entries search <words...> [--tag t] [--from …] [--to …]
|
|
24
|
+
vesper entries get <id> # full Markdown body, front matter and photos
|
|
25
|
+
vesper tags list # [{ name, count }], most used first
|
|
26
|
+
vesper photos list [--tag t] [--from …] [--to …]
|
|
27
|
+
vesper photos download <id> [--thumb] [-o file]
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
- Lists return `{ entries | photos, next }`, newest first: 50 entries, or the photos of 24 entries, per
|
|
31
|
+
page. Pass `--cursor <next>` for the next page, or `--all` to follow pages (stops at `--max`, default 500).
|
|
32
|
+
A null `next` is the end. Prefer narrowing with dates and tags over `--all`.
|
|
33
|
+
- Dates are UTC days; `--to` includes the whole day.
|
|
34
|
+
- List items carry an `excerpt` (up to 2000 characters). Use `entries get` when the full text matters.
|
|
35
|
+
- Search matches text and tag names, case-insensitively, and pages like a list.
|
|
36
|
+
|
|
37
|
+
## Writing (Pro only, and only when the user clearly asked)
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
vesper entries create "text" [--tag t]... [--public]
|
|
41
|
+
vesper entries create --file note.md # or --stdin; prefer files for multiline Markdown
|
|
42
|
+
vesper entries update <id> [text | --file f] [--tag t]... [--clear-tags] [--visibility private|public]
|
|
43
|
+
[--pin|--unpin] [--favorite|--unfavorite] [--archive|--unarchive]
|
|
44
|
+
vesper entries delete <id> --yes # permanent, with photos no other entry uses
|
|
45
|
+
vesper tags rename <from> <to>
|
|
46
|
+
vesper tags remove <tag>
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
- `update` changes only what is passed; `--tag` replaces the whole tag list.
|
|
50
|
+
- Entries are private unless `--public`; sharing needs Pro. Photos can only be added in the Vesper app.
|
|
51
|
+
- Confirm before `delete`, `tags remove` and `tags rename`: they touch many entries and cannot be undone.
|
|
52
|
+
|
|
53
|
+
## Limits
|
|
54
|
+
|
|
55
|
+
Requests are rate limited per workspace (120 a minute). A `429` is retried once after `retry-after`;
|
|
56
|
+
if it still fails, wait a minute instead of looping.
|
package/README.md
DELETED