@pleasure1234/vesper 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,575 @@
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.0";
14
+ // src/types.ts
15
+ const VISIBILITIES = ["private", "public"];
16
+ const SHELVES = [
17
+ "all",
18
+ "favorites",
19
+ "archive"
20
+ ];
21
+ const visibility = z.enum(VISIBILITIES);
22
+ const photo = z.looseObject({
23
+ id: z.string(),
24
+ width: z.number(),
25
+ height: z.number(),
26
+ takenAt: z.number().nullable(),
27
+ geo: z.object({
28
+ lat: z.number(),
29
+ lng: z.number()
30
+ }).nullable(),
31
+ place: z.string().nullable()
32
+ });
33
+ const post = z.object({
34
+ provider: z.string(),
35
+ url: z.string(),
36
+ at: z.string()
37
+ });
38
+ const entryListSchema = z.object({
39
+ entries: z.array(z.object({
40
+ id: z.string(),
41
+ excerpt: z.string(),
42
+ occurredAt: z.number(),
43
+ pinned: z.boolean(),
44
+ favorite: z.boolean(),
45
+ archived: z.boolean(),
46
+ visibility,
47
+ tags: z.array(z.string()),
48
+ photos: z.array(photo),
49
+ published: z.array(post)
50
+ })),
51
+ next: z.string().nullable()
52
+ });
53
+ const entrySchema = z.object({
54
+ meta: z.looseObject({
55
+ id: z.string(),
56
+ visibility,
57
+ tags: z.array(z.string())
58
+ }),
59
+ body: z.string(),
60
+ photos: z.array(photo)
61
+ });
62
+ const photoListSchema = z.object({
63
+ photos: z.array(photo.extend({
64
+ entryId: z.string(),
65
+ caption: z.string(),
66
+ tags: z.array(z.string()),
67
+ occurredAt: z.number()
68
+ })),
69
+ next: z.string().nullable()
70
+ });
71
+ const tagListSchema = z.object({ tags: z.array(z.object({
72
+ name: z.string(),
73
+ count: z.number()
74
+ })) });
75
+ const whoamiSchema = z.object({
76
+ workspace: z.object({
77
+ id: z.string(),
78
+ handle: z.string(),
79
+ timezone: z.string(),
80
+ plan: z.string()
81
+ }),
82
+ role: z.string(),
83
+ principal: z.string(),
84
+ scopes: z.array(z.string()),
85
+ write: z.boolean(),
86
+ unlocked: z.boolean()
87
+ });
88
+ const idSchema = z.object({ id: z.string() });
89
+ const deletedSchema = z.object({ deleted: z.string() });
90
+ const changedSchema = z.object({ changed: z.number() });
91
+ const errorSchema = z.object({
92
+ error: z.string(),
93
+ message: z.string()
94
+ });
95
+ const credentialsSchema = z.object({
96
+ origin: z.string(),
97
+ clientId: z.string(),
98
+ tokenEndpoint: z.string(),
99
+ revocationEndpoint: z.string().nullable(),
100
+ accessToken: z.string(),
101
+ refreshToken: z.string().nullable(),
102
+ expiresAt: z.number()
103
+ });
104
+ const metadataSchema = z.object({
105
+ authorization_endpoint: z.string(),
106
+ token_endpoint: z.string(),
107
+ registration_endpoint: z.string(),
108
+ revocation_endpoint: z.string().nullable().default(null)
109
+ });
110
+ const resourceSchema = z.object({ authorization_servers: z.array(z.string()).min(1) });
111
+ const clientSchema = z.object({ client_id: z.string() });
112
+ const tokenSchema = z.object({
113
+ access_token: z.string(),
114
+ refresh_token: z.string().nullable().default(null),
115
+ expires_in: z.number()
116
+ });
117
+ z.object({
118
+ body: z.string().nullable(),
119
+ tags: z.array(z.string()).nullable(),
120
+ visibility: visibility.nullable(),
121
+ pinned: z.boolean().nullable(),
122
+ favorite: z.boolean().nullable(),
123
+ archived: z.boolean().nullable()
124
+ });
125
+ const dateSchema = z.iso.date();
126
+ const countSchema = z.coerce.number().int().positive();
127
+ const visibilitySchema = visibility;
128
+ const shelfSchema = z.enum(SHELVES);
129
+ const addressSchema = z.object({ port: z.number() });
130
+ const MAX_WAIT_SECONDS = 60;
131
+ var ApiError = class extends Error {
132
+ status;
133
+ code;
134
+ constructor(status, code, message) {
135
+ super(message);
136
+ this.status = status;
137
+ this.code = code;
138
+ }
139
+ };
140
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
141
+ function urlFor(origin, path, query) {
142
+ const url = new URL(path, origin);
143
+ for (const [key, value] of Object.entries(query)) if (value !== null && value !== "") url.searchParams.set(key, value);
144
+ return url;
145
+ }
146
+ function parseJson(text) {
147
+ try {
148
+ return JSON.parse(text);
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+ async function failure(response) {
154
+ const text = await response.text();
155
+ const parsed = errorSchema.safeParse(parseJson(text));
156
+ 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);
157
+ }
158
+ function createClient(options) {
159
+ async function request(method, path, query, body) {
160
+ let token = await options.token();
161
+ let renewed = false;
162
+ let retried = false;
163
+ for (;;) {
164
+ const headers = new Headers({
165
+ authorization: `Bearer ${token}`,
166
+ accept: "application/json"
167
+ });
168
+ if (body !== null) headers.set("content-type", "application/json");
169
+ const response = await fetch(urlFor(options.origin, path, query), {
170
+ method,
171
+ headers,
172
+ body: body === null ? null : JSON.stringify(body)
173
+ });
174
+ if (response.status === 401 && !renewed && options.renew) {
175
+ renewed = true;
176
+ token = await options.renew();
177
+ continue;
178
+ }
179
+ if (response.status === 429 && !retried) {
180
+ retried = true;
181
+ const seconds = Number(response.headers.get("retry-after")) || 10;
182
+ await options.sleep(Math.min(seconds, MAX_WAIT_SECONDS) * 1e3);
183
+ continue;
184
+ }
185
+ if (!response.ok) throw await failure(response);
186
+ return response;
187
+ }
188
+ }
189
+ const read = async (schema, response) => schema.parse(await response.json());
190
+ return {
191
+ get: async (path, schema, query = {}) => read(schema, await request("GET", path, query, null)),
192
+ post: async (path, schema, body) => read(schema, await request("POST", path, {}, body)),
193
+ patch: async (path, schema, body) => read(schema, await request("PATCH", path, {}, body)),
194
+ delete: async (path, schema) => read(schema, await request("DELETE", path, {}, null)),
195
+ download: (path, query) => request("GET", path, query, null)
196
+ };
197
+ }
198
+ async function collect(load, first, all, max) {
199
+ const items = [];
200
+ let cursor = first;
201
+ for (;;) {
202
+ const page = await load(cursor);
203
+ items.push(...page.items);
204
+ cursor = page.next;
205
+ if (!all || !cursor || items.length >= max) return {
206
+ items,
207
+ next: cursor
208
+ };
209
+ }
210
+ }
211
+ // src/oauth.ts
212
+ const SCOPE = "entries:read entries:write offline_access";
213
+ const WAIT_MS = 3e5;
214
+ var OAuthError = class extends Error {};
215
+ async function read(schema, response) {
216
+ if (!response.ok) {
217
+ const text = await response.text();
218
+ throw new OAuthError(`${response.status} ${response.statusText}: ${text.slice(0, 300)}`);
219
+ }
220
+ return schema.parse(await response.json());
221
+ }
222
+ const form = (fields) => ({
223
+ method: "POST",
224
+ headers: { "content-type": "application/x-www-form-urlencoded" },
225
+ body: new URLSearchParams(fields)
226
+ });
227
+ const resourceOf = (origin) => `${origin}/mcp`;
228
+ async function discover(origin) {
229
+ const resource = await read(resourceSchema, await fetch(`${origin}/.well-known/oauth-protected-resource/mcp`));
230
+ const issuer = new URL(resource.authorization_servers[0] || origin);
231
+ return read(metadataSchema, await fetch(`${origin}/.well-known/oauth-authorization-server${issuer.pathname}`));
232
+ }
233
+ function pkce() {
234
+ const verifier = randomBytes(32).toString("base64url");
235
+ return {
236
+ verifier,
237
+ challenge: createHash("sha256").update(verifier).digest("base64url")
238
+ };
239
+ }
240
+ function openBrowser(url) {
241
+ const command = process.platform === "darwin" ? {
242
+ file: "open",
243
+ args: [url]
244
+ } : process.platform === "win32" ? {
245
+ file: "cmd",
246
+ args: [
247
+ "/c",
248
+ "start",
249
+ "",
250
+ url
251
+ ]
252
+ } : {
253
+ file: "xdg-open",
254
+ args: [url]
255
+ };
256
+ const child = spawn(command.file, command.args, {
257
+ stdio: "ignore",
258
+ detached: true
259
+ });
260
+ child.on("error", () => {});
261
+ child.unref();
262
+ }
263
+ const page = (text) => `<!doctype html><meta charset="utf-8"><title>Vesper</title><body style="font:16px system-ui;padding:3rem">${text}</body>`;
264
+ function listen(state) {
265
+ return new Promise((ready, fail) => {
266
+ const settle = Promise.withResolvers();
267
+ const server = createServer((request, response) => {
268
+ const url = new URL(request.url || "/", "http://127.0.0.1");
269
+ if (url.pathname !== "/callback") {
270
+ response.writeHead(404).end();
271
+ return;
272
+ }
273
+ const error = url.searchParams.get("error");
274
+ const code = url.searchParams.get("code");
275
+ const matched = url.searchParams.get("state") === state;
276
+ const ok = !error && code !== null && matched;
277
+ response.writeHead(ok ? 200 : 400, { "content-type": "text/html; charset=utf-8" }).end(page(ok ? "Signed in. You can close this tab." : "Sign-in failed. Check the terminal."));
278
+ server.close();
279
+ clearTimeout(timer);
280
+ if (code !== null && ok) settle.resolve(code);
281
+ else settle.reject(new OAuthError(error || "The callback did not match this sign-in."));
282
+ });
283
+ const timer = setTimeout(() => {
284
+ server.close();
285
+ settle.reject(new OAuthError("Timed out waiting for the browser."));
286
+ }, WAIT_MS);
287
+ server.on("error", fail);
288
+ server.listen(0, "127.0.0.1", () => {
289
+ const { port } = addressSchema.parse(server.address());
290
+ ready({
291
+ redirectUri: `http://127.0.0.1:${port}/callback`,
292
+ code: settle.promise
293
+ });
294
+ });
295
+ });
296
+ }
297
+ async function login(origin, notify) {
298
+ const metadata = await discover(origin);
299
+ const state = randomBytes(16).toString("base64url");
300
+ const callback = await listen(state);
301
+ const client = await read(clientSchema, await fetch(metadata.registration_endpoint, {
302
+ method: "POST",
303
+ headers: { "content-type": "application/json" },
304
+ body: JSON.stringify({
305
+ client_name: "Vesper CLI",
306
+ application_type: "native",
307
+ redirect_uris: [callback.redirectUri],
308
+ grant_types: ["authorization_code", "refresh_token"],
309
+ response_types: ["code"],
310
+ token_endpoint_auth_method: "none",
311
+ scope: SCOPE
312
+ })
313
+ }));
314
+ const { verifier, challenge } = pkce();
315
+ const authorize = new URL(metadata.authorization_endpoint);
316
+ authorize.search = new URLSearchParams({
317
+ response_type: "code",
318
+ client_id: client.client_id,
319
+ redirect_uri: callback.redirectUri,
320
+ scope: SCOPE,
321
+ state,
322
+ code_challenge: challenge,
323
+ code_challenge_method: "S256",
324
+ resource: resourceOf(origin)
325
+ }).toString();
326
+ notify(authorize.toString());
327
+ openBrowser(authorize.toString());
328
+ const tokens = await read(tokenSchema, await fetch(metadata.token_endpoint, form({
329
+ grant_type: "authorization_code",
330
+ code: await callback.code,
331
+ redirect_uri: callback.redirectUri,
332
+ client_id: client.client_id,
333
+ code_verifier: verifier,
334
+ resource: resourceOf(origin)
335
+ })));
336
+ return {
337
+ origin,
338
+ clientId: client.client_id,
339
+ tokenEndpoint: metadata.token_endpoint,
340
+ revocationEndpoint: metadata.revocation_endpoint,
341
+ accessToken: tokens.access_token,
342
+ refreshToken: tokens.refresh_token,
343
+ expiresAt: Date.now() + tokens.expires_in * 1e3
344
+ };
345
+ }
346
+ async function refresh(credentials) {
347
+ if (!credentials.refreshToken) throw new OAuthError("The sign-in expired. Run `vesper login`.");
348
+ const tokens = await read(tokenSchema, await fetch(credentials.tokenEndpoint, form({
349
+ grant_type: "refresh_token",
350
+ refresh_token: credentials.refreshToken,
351
+ client_id: credentials.clientId,
352
+ resource: resourceOf(credentials.origin)
353
+ })));
354
+ return {
355
+ ...credentials,
356
+ accessToken: tokens.access_token,
357
+ refreshToken: tokens.refresh_token || credentials.refreshToken,
358
+ expiresAt: Date.now() + tokens.expires_in * 1e3
359
+ };
360
+ }
361
+ async function revoke(credentials) {
362
+ const endpoint = credentials.revocationEndpoint;
363
+ if (!endpoint) return;
364
+ for (const token of [credentials.refreshToken, credentials.accessToken]) if (token) await fetch(endpoint, form({
365
+ token,
366
+ client_id: credentials.clientId
367
+ })).catch(() => null);
368
+ }
369
+ // src/store.ts
370
+ const configDir = () => join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "vesper");
371
+ const authFile = () => join(configDir(), "auth.json");
372
+ async function loadCredentials() {
373
+ const text = await readFile(authFile(), "utf8").catch(() => null);
374
+ if (text === null) return null;
375
+ const parsed = credentialsSchema.safeParse(JSON.parse(text));
376
+ return parsed.success ? parsed.data : null;
377
+ }
378
+ async function saveCredentials(credentials) {
379
+ const file = authFile();
380
+ await mkdir(dirname(file), {
381
+ recursive: true,
382
+ mode: 448
383
+ });
384
+ await writeFile(file, JSON.stringify(credentials, null, 2), { mode: 384 });
385
+ await chmod(file, 384);
386
+ }
387
+ const clearCredentials = () => rm(authFile(), { force: true });
388
+ // src/session.ts
389
+ const EARLY_MS = 6e4;
390
+ const originOf = (flag) => (flag || process.env.VESPER_URL || "https://noted-this.date").replace(/\/+$/, "");
391
+ async function openClient(flag) {
392
+ const personal = process.env.VESPER_TOKEN;
393
+ if (personal) return createClient({
394
+ origin: originOf(flag),
395
+ token: async () => personal,
396
+ renew: null,
397
+ sleep: wait
398
+ });
399
+ const saved = await loadCredentials();
400
+ if (!saved) throw new OAuthError("Not signed in. Run `vesper login`.");
401
+ if (flag && originOf(flag) !== saved.origin) throw new OAuthError(`Signed in to ${saved.origin}. Run \`vesper login --url ${flag}\`.`);
402
+ let credentials = saved;
403
+ const renew = async () => {
404
+ credentials = await refresh(credentials);
405
+ await saveCredentials(credentials);
406
+ return credentials.accessToken;
407
+ };
408
+ return createClient({
409
+ origin: credentials.origin,
410
+ token: async () => credentials.expiresAt - EARLY_MS > Date.now() ? credentials.accessToken : renew(),
411
+ renew: credentials.refreshToken ? renew : null,
412
+ sleep: wait
413
+ });
414
+ }
415
+ // src/index.ts
416
+ const MAX_ITEMS = 500;
417
+ function print(value) {
418
+ process.stdout.write(`${JSON.stringify(value, null, process.stdout.isTTY ? 2 : 0)}\n`);
419
+ }
420
+ const parse = (schema, expected) => (value) => {
421
+ const parsed = schema.safeParse(value);
422
+ if (!parsed.success) throw new InvalidArgumentError(`Expected ${expected}.`);
423
+ return parsed.data;
424
+ };
425
+ const day = parse(dateSchema, "a day as YYYY-MM-DD");
426
+ const addTag = (value, previous = []) => [...previous, value];
427
+ async function readBody(inline, flags) {
428
+ if (flags.file) return readFile(flags.file, "utf8");
429
+ if (flags.stdin) return text(process.stdin);
430
+ return inline.join(" ");
431
+ }
432
+ 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();
433
+ const urlFlag = () => program.opts().url || null;
434
+ const client = () => openClient(urlFlag());
435
+ 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"));
436
+ const listQuery = (flags) => ({
437
+ tag: flags.tag || null,
438
+ fromDate: flags.from || null,
439
+ toDate: flags.to || null
440
+ });
441
+ async function listEntries(api, flags, extra) {
442
+ const page = await collect(async (before) => {
443
+ const list = await api.get("/api/entries", entryListSchema, {
444
+ ...listQuery(flags),
445
+ ...extra,
446
+ before
447
+ });
448
+ return {
449
+ items: list.entries,
450
+ next: list.next
451
+ };
452
+ }, flags.cursor || null, Boolean(flags.all), flags.max || MAX_ITEMS);
453
+ return {
454
+ entries: page.items,
455
+ next: page.next
456
+ };
457
+ }
458
+ program.command("login").description("Sign in through the browser and pick the workspace to use").action(async () => {
459
+ const origin = originOf(urlFlag());
460
+ const credentials = await login(origin, (url) => process.stderr.write(`Opening your browser to sign in. If it does not open, visit:\n${url}\n`));
461
+ await saveCredentials(credentials);
462
+ const me = await createClient({
463
+ origin,
464
+ token: async () => credentials.accessToken,
465
+ renew: null,
466
+ sleep: wait
467
+ }).get("/api/workspace", whoamiSchema);
468
+ 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`);
469
+ print(me);
470
+ });
471
+ program.command("logout").description("Revoke the saved sign-in and forget it").action(async () => {
472
+ const credentials = await loadCredentials();
473
+ if (credentials) await revoke(credentials);
474
+ await clearCredentials();
475
+ print({ signedOut: true });
476
+ });
477
+ 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)));
478
+ const entries = program.command("entries").alias("entry").description("Journal entries");
479
+ 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, {
480
+ in: flags.in || null,
481
+ pinned: flags.pinned ? "true" : null
482
+ }))));
483
+ 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(" ") }))));
484
+ 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)));
485
+ 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) => {
486
+ const body = (await readBody(text, flags)).trim();
487
+ if (!body) throw new Error("Write something: pass text, --file or --stdin.");
488
+ print(await (await client()).post("/api/entries", idSchema, {
489
+ body,
490
+ tags: flags.tag || [],
491
+ visibility: flags.public ? "public" : "private"
492
+ }));
493
+ });
494
+ 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) => {
495
+ const body = (await readBody(text, flags)).trim();
496
+ const toggle = (on, off) => on ? true : off ? false : null;
497
+ const patch = {
498
+ body: body || null,
499
+ tags: flags.clearTags ? [] : flags.tag || null,
500
+ visibility: flags.visibility || null,
501
+ pinned: toggle(Boolean(flags.pin), Boolean(flags.unpin)),
502
+ favorite: toggle(Boolean(flags.favorite), Boolean(flags.unfavorite)),
503
+ archived: toggle(Boolean(flags.archive), Boolean(flags.unarchive))
504
+ };
505
+ if (Object.values(patch).every((value) => value === null)) throw new Error("Nothing to change.");
506
+ print(await (await client()).patch(`/api/entries/${id}`, idSchema, patch));
507
+ });
508
+ 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)));
509
+ const tags = program.command("tags").alias("tag").description("Tags");
510
+ tags.command("list").description("Tags and how many entries use each").action(async () => print(await (await client()).get("/api/tags", tagListSchema)));
511
+ 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, {
512
+ from,
513
+ to
514
+ })));
515
+ tags.command("remove").description("Remove a tag from every entry (Pro)").argument("<tag>").action(async (from) => print(await (await client()).patch("/api/tags", changedSchema, {
516
+ from,
517
+ to: null
518
+ })));
519
+ const photos = program.command("photos").alias("photo").description("Photos");
520
+ photos.addCommand(listCommand("list", "Photos newest first, from 24 entries per page").action(async (flags) => {
521
+ const api = await client();
522
+ const page = await collect(async (before) => {
523
+ const list = await api.get("/api/photos", photoListSchema, {
524
+ ...listQuery(flags),
525
+ before
526
+ });
527
+ return {
528
+ items: list.photos,
529
+ next: list.next
530
+ };
531
+ }, flags.cursor || null, Boolean(flags.all), flags.max || MAX_ITEMS);
532
+ print({
533
+ photos: page.items,
534
+ next: page.next
535
+ });
536
+ }));
537
+ 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) => {
538
+ const response = await (await client()).download(`/api/photos/${id}`, { size: flags.thumb ? "thumb" : "original" });
539
+ const type = response.headers.get("content-type") || "application/octet-stream";
540
+ const subtype = type.split(";")[0]?.split("/")[1] || "bin";
541
+ const output = flags.output || `${id}.${subtype === "jpeg" ? "jpg" : subtype}`;
542
+ if (!response.body) throw new Error("The server sent no image.");
543
+ await writeFile(output, response.body);
544
+ print({
545
+ id,
546
+ saved: output,
547
+ type
548
+ });
549
+ });
550
+ 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) => {
551
+ const target = join(flags.dir || join(homedir(), ".claude", "skills"), "vesper");
552
+ await mkdir(target, { recursive: true });
553
+ const source = fileURLToPath(new URL("../skills/vesper/SKILL.md", import.meta.url));
554
+ await copyFile(source, join(target, "SKILL.md"));
555
+ print({ installed: join(target, "SKILL.md") });
556
+ });
557
+ function report(error) {
558
+ if (error instanceof ApiError) {
559
+ const hint = error.status === 403 && /needs Pro/.test(error.message) ? " Free workspaces are read-only through the API." : "";
560
+ return {
561
+ error: error.code,
562
+ status: error.status,
563
+ message: error.message + hint
564
+ };
565
+ }
566
+ return {
567
+ error: error instanceof OAuthError ? "auth" : "error",
568
+ message: error.message
569
+ };
570
+ }
571
+ program.parseAsync().catch((error) => {
572
+ process.stderr.write(`${JSON.stringify(report(error))}\n`);
573
+ process.exit(1);
574
+ });
575
+ export {};
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@pleasure1234/vesper",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Read and write your Vesper entries from the terminal.",
5
+ "license": "UNLICENSED",
6
+ "bin": {
7
+ "vesper": "./dist/index.mjs"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "skills"
12
+ ],
13
+ "type": "module",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "scripts": {
18
+ "build": "vp pack src/index.ts --clean",
19
+ "prepublishOnly": "pnpm build"
20
+ },
21
+ "dependencies": {
22
+ "@commander-js/extra-typings": "15.1.0",
23
+ "commander": "15.1.0",
24
+ "zod": "4.6.7"
25
+ },
26
+ "engines": {
27
+ "node": ">=22.12.0"
28
+ }
29
+ }
@@ -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
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.