@refhub/cli 1.0.0 → 1.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/README.md CHANGED
@@ -3,10 +3,20 @@
3
3
  > command-line execution layer for the [refhub.io](https://refhub.io) API.
4
4
  > manage vaults, papers, tags, and relations — scriptable, pipeable, agent-ready.
5
5
 
6
+ [![npm](https://img.shields.io/npm/v/@refhub/cli?style=flat-square)](https://www.npmjs.com/package/@refhub/cli)
7
+
6
8
  ---
7
9
 
8
10
  ## // install
9
11
 
12
+ ```bash
13
+ npm install -g @refhub/cli
14
+ ```
15
+
16
+ **requires** node ≥ 18.
17
+
18
+ ### install from source
19
+
10
20
  ```bash
11
21
  git clone https://github.com/refhub/refhub-cli
12
22
  cd refhub-cli
@@ -15,25 +25,27 @@ npm run build
15
25
  npm link
16
26
  ```
17
27
 
18
- `npm link` makes `refhub` available globally without publishing to npm.
19
-
20
- **requires** node ≥ 18.
21
-
22
28
  ---
23
29
 
24
30
  ## // auth
25
31
 
32
+ The CLI uses two credentials depending on the command:
33
+
34
+ **API key** — required for all vault/item/tag/relation/import/export/audit commands:
26
35
  ```bash
27
36
  export REFHUB_API_KEY=your_key_here
37
+ # or pass inline:
38
+ refhub --api-key <key> vaults list
28
39
  ```
40
+ Resolution order: `--api-key` flag → `REFHUB_API_KEY` env → exit 3.
29
41
 
30
- or pass inline:
31
-
42
+ **Session JWT** — required for `enrich` and `pdf upload` (management routes):
32
43
  ```bash
33
- refhub --api-key <key> vaults list
44
+ export REFHUB_JWT=your_supabase_session_jwt
45
+ # or pass inline:
46
+ refhub enrich --vault <id> --jwt <token>
34
47
  ```
35
-
36
- key resolution order: `--api-key` flag → `REFHUB_API_KEY` env → exit 3.
48
+ Resolution order: `--jwt` flag → `REFHUB_JWT` env → exit 3.
37
49
 
38
50
  ---
39
51
 
@@ -46,6 +58,7 @@ refhub [--api-key <key>] [--table] <command> [subcommand] [options]
46
58
  | flag | behavior |
47
59
  |------|----------|
48
60
  | `--api-key` | override `REFHUB_API_KEY` |
61
+ | `--jwt` | override `REFHUB_JWT` (used by `enrich` and `pdf upload`) |
49
62
  | `--table` | human-readable table output (default: json) |
50
63
  | `--version` | print version |
51
64
  | `--help` | available on every command and subcommand |
@@ -137,6 +150,29 @@ refhub export --vault <id> [--format json|bibtex]
137
150
  refhub audit --vault <id> [--since <ISO>] [--until <ISO>] [--limit] [--page]
138
151
  ```
139
152
 
153
+ ### enrich
154
+
155
+ Enriches incomplete publication metadata by looking up each item's DOI against Semantic Scholar and patching missing fields (title, authors, year, abstract). Requires a session JWT.
156
+
157
+ ```bash
158
+ refhub enrich --vault <id> [--item <itemId>] [--dry-run] [--jwt <token>]
159
+ ```
160
+
161
+ - omit `--item` to process all items in the vault that have a DOI and missing fields
162
+ - `--dry-run` shows what would be updated without writing anything
163
+ - rate-limited to 1 req/s to respect Semantic Scholar's per-key limit
164
+
165
+ ### pdf
166
+
167
+ Uploads a PDF file to the user's linked Google Drive and links it to a publication. Requires a session JWT and Google Drive connected to the account.
168
+
169
+ ```bash
170
+ refhub pdf upload --publication <original_publication_id> --file <path/to/file.pdf> [--jwt <token>]
171
+ ```
172
+
173
+ - `--publication` is the `original_publication_id` from the vault item (not the vault item's `id`)
174
+ - max file size: 26 MB by default
175
+
140
176
  ---
141
177
 
142
178
  ## // exit codes
@@ -204,9 +240,9 @@ smoke test covers: `list_vaults` → `create_vault` → `tag_crud` → `relation
204
240
 
205
241
  ## // out of scope (v1)
206
242
 
207
- not exposed by the cli — these routes require a human session (jwt-only):
243
+ not exposed by the cli:
208
244
 
209
- - api key management
210
- - google drive integration
211
- - semantic scholar recommendations / references
212
- - global audit log (non-vault-scoped)
245
+ - api key management (jwt-only, no cli command)
246
+ - google drive link/unlink (jwt-only, no cli command)
247
+ - semantic scholar recommendations / references / citations / lookup (jwt-only, no cli command)
248
+ - global audit log (jwt-only, non-vault-scoped, no cli command)
package/dist/client.d.ts CHANGED
@@ -132,5 +132,34 @@ export declare class RefHubClient {
132
132
  page?: number;
133
133
  }): Promise<ApiResponse<AuditEntry[]>>;
134
134
  }
135
+ export interface DoiMetadata {
136
+ title: string;
137
+ authors: string[];
138
+ year?: number;
139
+ journal?: string;
140
+ doi: string;
141
+ url: string;
142
+ abstract?: string;
143
+ type: string;
144
+ }
145
+ export interface PdfUploadResult {
146
+ attempted: boolean;
147
+ stored: boolean;
148
+ provider: string;
149
+ fileId?: string;
150
+ folderId?: string;
151
+ folderName?: string;
152
+ pdfUrl?: string;
153
+ sourceUrl?: string | null;
154
+ }
155
+ export declare class ManagementClient {
156
+ private readonly baseUrl;
157
+ private readonly jwt;
158
+ constructor(jwt: string);
159
+ private req;
160
+ doiMetadata(doi: string): Promise<DoiMetadata | null>;
161
+ uploadPublicationPdf(publicationId: string, pdfBuffer: Buffer): Promise<ApiResponse<PdfUploadResult>>;
162
+ }
163
+ export declare function resolveManagementClient(jwt?: string): ManagementClient;
135
164
  export declare function resolveClient(apiKey?: string): RefHubClient;
136
165
  export declare function run(fn: () => Promise<void>): Promise<void>;
package/dist/client.js CHANGED
@@ -192,6 +192,49 @@ export class RefHubClient {
192
192
  return this.req('GET', `/vaults/${vaultId}/audit${qs}`);
193
193
  }
194
194
  }
195
+ export class ManagementClient {
196
+ baseUrl = 'https://refhub-api.netlify.app/api/v1';
197
+ jwt;
198
+ constructor(jwt) {
199
+ this.jwt = jwt;
200
+ }
201
+ async req(method, path, body, contentType = 'application/json') {
202
+ const headers = {
203
+ Authorization: `Bearer ${this.jwt}`,
204
+ 'Content-Type': contentType,
205
+ };
206
+ let fetchBody;
207
+ if (body !== undefined) {
208
+ fetchBody = body instanceof Buffer ? body : JSON.stringify(body);
209
+ }
210
+ const res = await fetch(`${this.baseUrl}${path}`, {
211
+ method,
212
+ headers,
213
+ body: fetchBody,
214
+ });
215
+ if (!res.ok) {
216
+ const payload = await res.json().catch(() => ({}));
217
+ const err = (payload['error'] ?? {});
218
+ throw new RefHubError(res.status, String(err['code'] ?? 'unknown_error'), String(err['message'] ?? `HTTP ${res.status}`), String(payload['meta']?.['request_id'] ?? ''));
219
+ }
220
+ return res.json();
221
+ }
222
+ async doiMetadata(doi) {
223
+ const result = await this.req('POST', '/doi-metadata', { doi });
224
+ return result.data;
225
+ }
226
+ async uploadPublicationPdf(publicationId, pdfBuffer) {
227
+ return this.req('POST', `/publications/${encodeURIComponent(publicationId)}/pdf`, pdfBuffer, 'application/pdf');
228
+ }
229
+ }
230
+ export function resolveManagementClient(jwt) {
231
+ const token = jwt ?? process.env['REFHUB_JWT'];
232
+ if (!token) {
233
+ process.stderr.write(JSON.stringify({ error: { code: 'missing_jwt', message: 'No session JWT found. Set REFHUB_JWT or pass --jwt <token>.' } }) + '\n');
234
+ process.exit(3);
235
+ }
236
+ return new ManagementClient(token);
237
+ }
195
238
  // ── Helpers ───────────────────────────────────────────────────────────────────
196
239
  export function resolveClient(apiKey) {
197
240
  const key = apiKey ?? process.env['REFHUB_API_KEY'];
@@ -0,0 +1,5 @@
1
+ import type { Command } from 'commander';
2
+ import { RefHubClient, ManagementClient } from '../client.js';
3
+ import type { Item } from '../types.js';
4
+ export declare function enrichItem(item: Item, mgmt: ManagementClient, client: RefHubClient, vaultId: string, dryRun: boolean): Promise<'enriched' | 'skipped' | 'not_found' | 'no_missing_fields'>;
5
+ export declare function registerEnrich(program: Command): void;
@@ -0,0 +1,82 @@
1
+ import { resolveClient, resolveManagementClient, run } from '../client.js';
2
+ export async function enrichItem(item, mgmt, client, vaultId, dryRun) {
3
+ if (!item.doi)
4
+ return 'skipped';
5
+ const missing = [];
6
+ if (!item.title)
7
+ missing.push('title');
8
+ if (!item.authors || item.authors.length === 0)
9
+ missing.push('authors');
10
+ if (!item.year)
11
+ missing.push('year');
12
+ if (!item.abstract)
13
+ missing.push('abstract');
14
+ if (missing.length === 0)
15
+ return 'no_missing_fields';
16
+ const meta = await mgmt.doiMetadata(item.doi);
17
+ if (!meta)
18
+ return 'not_found';
19
+ const patch = {};
20
+ if (missing.includes('title') && meta.title)
21
+ patch['title'] = meta.title;
22
+ if (missing.includes('authors') && meta.authors?.length)
23
+ patch['authors'] = meta.authors;
24
+ if (missing.includes('year') && meta.year)
25
+ patch['year'] = meta.year;
26
+ if (missing.includes('abstract') && meta.abstract)
27
+ patch['abstract'] = meta.abstract;
28
+ if (Object.keys(patch).length === 0)
29
+ return 'not_found';
30
+ if (!dryRun) {
31
+ await client.updateItem(vaultId, item.id, patch);
32
+ }
33
+ return 'enriched';
34
+ }
35
+ export function registerEnrich(program) {
36
+ program
37
+ .command('enrich')
38
+ .description('Enrich incomplete publication metadata from Semantic Scholar via DOI')
39
+ .requiredOption('--vault <id>', 'vault to enrich')
40
+ .option('--item <itemId>', 'enrich a single item instead of the whole vault')
41
+ .option('--dry-run', 'show what would be updated without writing')
42
+ .option('--jwt <token>', 'session JWT (overrides REFHUB_JWT env var)')
43
+ .action(async (opts, cmd) => {
44
+ const g = cmd.optsWithGlobals();
45
+ const client = resolveClient(g.apiKey);
46
+ const mgmt = resolveManagementClient(opts.jwt);
47
+ const dryRun = opts.dryRun ?? false;
48
+ await run(async () => {
49
+ let items;
50
+ if (opts.item) {
51
+ const result = await client.getItem(opts.vault, opts.item);
52
+ items = [result.data];
53
+ }
54
+ else {
55
+ const result = await client.listItems(opts.vault);
56
+ items = result.data;
57
+ }
58
+ const withDoi = items.filter((i) => i.doi);
59
+ if (withDoi.length === 0) {
60
+ process.stdout.write(JSON.stringify({ data: { enriched: 0, skipped: 0, not_found: 0, no_missing_fields: 0, message: 'No items with a DOI found.' } }, null, 2) + '\n');
61
+ return;
62
+ }
63
+ const counts = { enriched: 0, skipped: 0, not_found: 0, no_missing_fields: 0 };
64
+ const enriched = [];
65
+ for (const item of withDoi) {
66
+ const outcome = await enrichItem(item, mgmt, client, opts.vault, dryRun);
67
+ counts[outcome]++;
68
+ if (outcome === 'enriched')
69
+ enriched.push(item.id);
70
+ // 1 req/s to respect Semantic Scholar rate limit
71
+ await new Promise((r) => setTimeout(r, 1000));
72
+ }
73
+ process.stdout.write(JSON.stringify({
74
+ data: {
75
+ dry_run: dryRun,
76
+ ...counts,
77
+ enriched_ids: enriched,
78
+ },
79
+ }, null, 2) + '\n');
80
+ });
81
+ });
82
+ }
@@ -0,0 +1,4 @@
1
+ import type { Command } from 'commander';
2
+ import { ManagementClient } from '../client.js';
3
+ export declare function handlePdfUpload(mgmt: ManagementClient, publicationId: string, filePath: string, tableMode: boolean): Promise<void>;
4
+ export declare function registerPdf(program: Command): void;
@@ -0,0 +1,30 @@
1
+ // src/commands/pdf.ts
2
+ import { readFileSync } from 'fs';
3
+ import { resolveManagementClient, run } from '../client.js';
4
+ import { format } from '../format.js';
5
+ export async function handlePdfUpload(mgmt, publicationId, filePath, tableMode) {
6
+ let pdfBuffer;
7
+ try {
8
+ pdfBuffer = readFileSync(filePath);
9
+ }
10
+ catch (e) {
11
+ process.stderr.write(JSON.stringify({ error: { code: 'file_read_error', message: `Cannot read file: ${String(e)}` } }) + '\n');
12
+ process.exit(2);
13
+ }
14
+ const result = await mgmt.uploadPublicationPdf(publicationId, pdfBuffer);
15
+ format(result, tableMode);
16
+ }
17
+ export function registerPdf(program) {
18
+ const pdf = program.command('pdf').description('Upload a PDF to Google Drive for a publication');
19
+ pdf
20
+ .command('upload')
21
+ .description('Upload a PDF file and link it to a publication')
22
+ .requiredOption('--publication <id>', 'publication ID (original_publication_id from vault item)')
23
+ .requiredOption('--file <path>', 'path to PDF file')
24
+ .option('--jwt <token>', 'session JWT (overrides REFHUB_JWT env var)')
25
+ .action(async (opts, cmd) => {
26
+ const g = cmd.optsWithGlobals();
27
+ const mgmt = resolveManagementClient(opts.jwt);
28
+ await run(() => handlePdfUpload(mgmt, opts.publication, opts.file, g.table ?? false));
29
+ });
30
+ }
package/dist/index.js CHANGED
@@ -8,12 +8,15 @@ import { registerRelations } from './commands/relations.js';
8
8
  import { registerImport } from './commands/import.js';
9
9
  import { registerExport } from './commands/export.js';
10
10
  import { registerAudit } from './commands/audit.js';
11
+ import { registerEnrich } from './commands/enrich.js';
12
+ import { registerPdf } from './commands/pdf.js';
11
13
  const program = new Command();
12
14
  program
13
15
  .name('refhub')
14
16
  .description('RefHub CLI — manage vaults, items, tags, and relations')
15
17
  .version('0.1.0')
16
18
  .option('--api-key <key>', 'RefHub API key (overrides REFHUB_API_KEY env var)')
19
+ .option('--jwt <token>', 'Supabase session JWT (overrides REFHUB_JWT env var)')
17
20
  .option('--table', 'human-readable table output (default: JSON)');
18
21
  registerVaults(program);
19
22
  registerItems(program);
@@ -22,4 +25,6 @@ registerRelations(program);
22
25
  registerImport(program);
23
26
  registerExport(program);
24
27
  registerAudit(program);
28
+ registerEnrich(program);
29
+ registerPdf(program);
25
30
  program.parseAsync();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@refhub/cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "refhub CLI execution layer for agent skills",
5
5
  "type": "module",
6
6
  "engines": { "node": ">=18" },