rubien-mcp-server 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,180 @@
1
+ # rubien-mcp-server
2
+
3
+ A Model Context Protocol server that wraps `rubien-cli`, making the Rubien reference library available to Claude Code, Claude Desktop, and claude.ai chat as a callable tool catalog.
4
+
5
+ The server is a thin Node/TypeScript process. It spawns `rubien-cli` under the hood and speaks MCP over one of two transports:
6
+
7
+ - **stdio** — used by **Claude Code** and **Claude Desktop**. The client launches the server as a child process and talks to it over the pipe. No network, no auth.
8
+ - **Streamable HTTP with bearer-token auth** — used by **claude.ai (web)** via a custom MCP connector. Requires a tunnel (e.g. Cloudflare Tunnel) because your library lives on your Mac.
9
+
10
+ Pick the section below that matches your client. Most users want one of the two stdio paths.
11
+
12
+ ## Install (Claude Code)
13
+
14
+ ```bash
15
+ claude mcp add rubien -- npx -y rubien-mcp-server
16
+ ```
17
+
18
+ This needs `rubien-cli` on the host:
19
+ - **Mac:** install Rubien.app (DMG) — the entitled `rubien-cli` ships inside it; nothing else to do.
20
+ - **Linux:** `sudo apt install libsqlite3-0 libcurl4 libxml2 libpoppler-glib8 libcairo2 libgdk-pixbuf-2.0-0 libglib2.0-0 ca-certificates`, then download `rubien-cli-*-linux-x86_64.tar.gz` from
21
+ https://github.com/devzhk/Rubien-releases/releases and **extract it to a directory, keeping `rubien-cli` and the `*.resources` folders together** (the CLI loads citation styles from beside the binary). Point the server at it: `export RUBIEN_CLI=/path/to/extracted/rubien-cli`. Do **not** copy the bare binary onto `PATH` alone — it would lose its resource bundles.
22
+
23
+ The server checks the CLI's build at startup; if it's too old it prints an update
24
+ instruction and exits (rather than failing mid-call). On **Mac**, update Rubien.app
25
+ (Sparkle). On **Linux**, run `rubien-cli self-update` (signature-verified, replaces in
26
+ place) — or re-download the tarball.
27
+
28
+ ## Prerequisites
29
+
30
+ - Node.js ≥ 20
31
+ - `rubien-cli` reachable on the host. The server looks for it in this order:
32
+ 1. `$RUBIEN_CLI` env var (explicit path)
33
+ 2. `/Applications/Rubien.app/Contents/Helpers/rubien-cli` (installed app bundle, Mac)
34
+ 3. `~/Applications/Rubien.app/Contents/Helpers/rubien-cli` (Mac)
35
+ 4. `./build/Rubien.app/Contents/Helpers/rubien-cli` (dev build output, Mac)
36
+ 5. `rubien-cli` on `PATH` (Linux installs land here — see the **Install** section above)
37
+
38
+ **On Mac, prefer the bundled helper.** It's signed with the App Group entitlement and reads the same `library.sqlite` the Rubien app uses. A bare `rubien-cli` on PATH is typically an SPM dev build without the entitlement, which hits a *different* database — see "Database location" in `Docs/CLI-Reference.md`.
39
+
40
+ **On Linux**, the server runs against a `rubien-cli` installed per the **Install** section above (prebuilt Linux tarball, or built from source). Everything works except `rubien_sync_status`, which always errors (`sync` subcommand isn't registered on Linux builds — CloudKit doesn't exist there).
41
+
42
+ To pin the spawned CLI to a specific library directory regardless of which binary resolves, set `RUBIEN_LIBRARY_ROOT` in the MCP server's `env` block (Claude Code: `claude mcp add rubien --env RUBIEN_LIBRARY_ROOT=...`; Claude Desktop: under `mcpServers.rubien.env` in `claude_desktop_config.json`). The path is used verbatim — point it at the directory that contains `library.sqlite`:
43
+
44
+ - Mac sandboxed: `~/Library/Group Containers/9TXK4V3SS8.com.rubien.shared/Rubien`
45
+ - Mac unsandboxed: `~/Library/Application Support/Rubien`
46
+ - Linux: `~/.local/share/rubien` (or wherever `$XDG_DATA_HOME/rubien` resolved to)
47
+
48
+ ## Claude Code (stdio)
49
+
50
+ The npx command above is the recommended path. To run a local checkout instead (see [Development](#development) for the build):
51
+
52
+ ```bash
53
+ claude mcp add rubien node $(pwd)/dist/index.js
54
+ ```
55
+
56
+ Try it:
57
+
58
+ > List my 5 most recently added references.
59
+ > Cite reference 42 in Nature style.
60
+
61
+ Claude Code's permission UI prompts for the destructive tools (`rubien_delete`, `rubien_update`, `rubien_import`, and the property write tools) on first use.
62
+
63
+ ## Claude Desktop (stdio)
64
+
65
+ Claude Desktop spawns MCP servers itself — no tunnel, no bearer token. Add Rubien to `claude_desktop_config.json` via either route:
66
+
67
+ - **Edit the file directly** at `~/Library/Application Support/Claude/claude_desktop_config.json`.
68
+ - **Settings → Developer → Edit Config** in Claude Desktop, which opens the same file in your editor.
69
+
70
+ Add Rubien under `mcpServers`:
71
+
72
+ ```json
73
+ {
74
+ "mcpServers": {
75
+ "rubien": {
76
+ "command": "node",
77
+ "args": ["/absolute/path/to/Rubien/mcp-server/dist/index.js"]
78
+ }
79
+ }
80
+ }
81
+ ```
82
+
83
+ Restart Claude Desktop and Rubien appears in the tool picker. To pin the spawned CLI to a specific library (see *Prerequisites* above for paths), add an `env` block:
84
+
85
+ ```json
86
+ "rubien": {
87
+ "command": "node",
88
+ "args": ["/absolute/path/to/Rubien/mcp-server/dist/index.js"],
89
+ "env": {
90
+ "RUBIEN_LIBRARY_ROOT": "/Users/you/Library/Group Containers/9TXK4V3SS8.com.rubien.shared/Rubien"
91
+ }
92
+ }
93
+ ```
94
+
95
+ > **Future work — Desktop Extension (`.dxt`).** Claude Desktop also supports one-click MCP installs via `.dxt` packages (a zip containing a `manifest.json` + bundled server). Rubien doesn't ship one yet; packaging it would replace the config-file edit above with a double-click install from a GitHub Release asset.
96
+
97
+ ## claude.ai web (Streamable HTTP + Cloudflare Tunnel)
98
+
99
+ claude.ai (the web app at https://claude.ai) can't spawn a local process, so it talks to the server over HTTPS via a custom MCP connector. Since your library lives on your Mac, you'll need a tunnel to expose the local server, and bearer-token auth to keep strangers out.
100
+
101
+ ```bash
102
+ # 1. Start the server with a bearer token
103
+ RUBIEN_MCP_BEARER=$(openssl rand -hex 32) \
104
+ node dist/index.js --http --port 4000 --bearer-token "$RUBIEN_MCP_BEARER"
105
+
106
+ # 2. Open a tunnel
107
+ cloudflared tunnel --url http://localhost:4000
108
+ # → copy the https://*.trycloudflare.com URL
109
+
110
+ # 3. In claude.ai: Settings → Connectors → Add custom MCP connector
111
+ # URL: https://<your-tunnel>.trycloudflare.com
112
+ # Token: $RUBIEN_MCP_BEARER (from step 1)
113
+ ```
114
+
115
+ Save the bearer token — you'll need it to reconnect after restarts.
116
+
117
+ ## Security model
118
+
119
+ This server is designed for **single-user personal use** only.
120
+
121
+ - The bearer token is a long-lived static secret. There's no rotation, revocation, rate limiting, or replay protection.
122
+ - The server will happily accept any request with the correct token. Don't paste the token into anything you don't trust, and treat a leaked token like an SSH key — regenerate immediately.
123
+ - Cloudflare Tunnel provides TLS termination; the token travels over HTTPS. If you use a plaintext tunnel (e.g. raw ngrok HTTP) the token can be sniffed.
124
+ - A leaked URL without the token is safe — every request gets a 401 — but rotate both if in doubt.
125
+
126
+ If this setup ever becomes multi-user, the auth layer needs a real story: OAuth, short-lived tokens, and per-client revocation.
127
+
128
+ ## Tool catalog
129
+
130
+ Roughly 36 tools covering every `rubien-cli` subcommand mode. Names are `rubien_<subject>_<action>` so Claude can pick the right tool from a single-word hint:
131
+
132
+ | Surface | Tools |
133
+ |---|---|
134
+ | References | `rubien_search`, `rubien_list`, `rubien_get`, `rubien_add`, `rubien_update`, `rubien_delete` |
135
+ | Citations | `rubien_cite`, `rubien_styles_list` |
136
+ | Import/Export | `rubien_import`, `rubien_export` |
137
+ | PDFs | `rubien_pdf_info`, `rubien_pdf_text`, `rubien_pdf_page_image`, `rubien_pdf_download`, `rubien_annotations_list` |
138
+ | Web clips | `rubien_web_get`, `rubien_web_annotations` |
139
+ | Properties (incl. Tags) | `rubien_properties_list`, `rubien_properties_create`, `rubien_properties_delete`, `rubien_properties_rename`, `rubien_properties_show`, `rubien_properties_hide`, `rubien_properties_add_option`, `rubien_properties_rename_option`, `rubien_properties_delete_option`, `rubien_properties_set`, `rubien_properties_add_values`, `rubien_properties_remove_values`, `rubien_properties_clear` |
140
+ | Saved views | `rubien_views_list`, `rubien_views_create`, `rubien_views_delete`, `rubien_views_rename`, `rubien_views_query` |
141
+ | Sync | `rubien_sync_status` (Mac-only — errors on Linux hosts) |
142
+
143
+ The PDF tools cover inspection and acquisition — `rubien_pdf_info` returns page count plus a flattened outline, `rubien_pdf_text` extracts text by page range or section title, `rubien_pdf_page_image` renders a page to PNG for figure inspection, and `rubien_pdf_download` fetches an open-access PDF for an existing reference and attaches it to the library. `rubien_annotations_list` returns the user's highlights/underlines/anchored-notes on the attached PDF.
144
+
145
+ The web-clip tools are the counterpart for clipped web pages — `rubien_web_get` returns the extracted body (markdown or HTML, paginated by character offset) along with `siteName` and `annotationCount`, and `rubien_web_annotations` returns highlights with a W3C TextQuoteSelector triple (`prefixText` / `anchorText` / `suffixText`) so the highlight can be located inside the body. Library-only — neither tool fetches from the network.
146
+
147
+ Destructive tools are tagged with `destructiveHint: true` so Claude Code's permission UI flags them. `rubien_delete` always passes `--force` — the confirmation happens in the MCP client permission UI, not in the CLI's TTY prompt. See the comment in `src/tools/references.ts` for rationale.
148
+
149
+ ## Contract pinning
150
+
151
+ Every tool's argument shape is defined in zod in the tool file; the expected *response* shape is in `src/schemas.ts`, mirroring the Swift DTOs in `Sources/RubienCLI/RubienCLI.swift` (search for `*DTO`). Crucial convention (see tests in `test/schemas.test.ts`):
152
+
153
+ - `.optional()` in zod for Swift `Optional` fields — Swift's `JSONEncoder` **omits** nil optionals from output.
154
+ - `.nullable()` only for `AlwaysEncodedOptional<T>` wrappers (currently just `DatabaseViewDTO.groupBy`).
155
+
156
+ If a Swift DTO changes, update both the Swift side and `src/schemas.ts` in the same commit, per the CLAUDE.md rule about keeping the CLI and data layer in lockstep.
157
+
158
+ ## Development
159
+
160
+ Build from a local checkout (instead of `npx`):
161
+
162
+ ```bash
163
+ cd mcp-server
164
+ npm install
165
+ npm run build # → dist/
166
+ npm test # vitest unit tests
167
+ ```
168
+
169
+ Watch mode:
170
+
171
+ ```bash
172
+ npm run dev # tsc --watch
173
+ npm run test:watch
174
+ ```
175
+
176
+ MCP Inspector is the fastest way to poke at tool schemas by hand:
177
+
178
+ ```bash
179
+ npx @modelcontextprotocol/inspector node dist/index.js
180
+ ```
package/dist/auth.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Constant-time string comparison. Avoids timing leaks on token verification.
3
+ */
4
+ function safeEqual(a, b) {
5
+ if (a.length !== b.length)
6
+ return false;
7
+ let diff = 0;
8
+ for (let i = 0; i < a.length; i += 1) {
9
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
10
+ }
11
+ return diff === 0;
12
+ }
13
+ /**
14
+ * Validate Authorization header against the configured bearer token.
15
+ * Writes a 401 to the response and returns false on mismatch.
16
+ *
17
+ * Single-user personal use model: the token is a long-lived static secret
18
+ * provided via CLI flag / env var. No rotation or revocation. See
19
+ * README.md → Security model for the full threat model.
20
+ */
21
+ export function requireBearer(req, res, expectedToken) {
22
+ const header = req.headers["authorization"];
23
+ if (typeof header !== "string" || !header.startsWith("Bearer ")) {
24
+ res.writeHead(401, { "WWW-Authenticate": "Bearer realm=\"rubien-mcp\"" });
25
+ res.end('{"error":"missing or malformed Authorization header"}');
26
+ return false;
27
+ }
28
+ const token = header.slice("Bearer ".length).trim();
29
+ if (!safeEqual(token, expectedToken)) {
30
+ res.writeHead(401, { "WWW-Authenticate": "Bearer realm=\"rubien-mcp\"" });
31
+ res.end('{"error":"invalid bearer token"}');
32
+ return false;
33
+ }
34
+ return true;
35
+ }
36
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,SAAS,SAAS,CAAC,CAAS,EAAE,CAAS;IACrC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QACrC,IAAI,IAAI,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC5C,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,CAAC;AACpB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAC3B,GAAoB,EACpB,GAAmB,EACnB,aAAqB;IAErB,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;IAC5C,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QAChE,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,CAAC,CAAC;QAC1E,GAAG,CAAC,GAAG,CAAC,uDAAuD,CAAC,CAAC;QACjE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;IACpD,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,aAAa,CAAC,EAAE,CAAC;QACrC,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,kBAAkB,EAAE,6BAA6B,EAAE,CAAC,CAAC;QAC1E,GAAG,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;QAC5C,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
package/dist/cli.js ADDED
@@ -0,0 +1,140 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { promisify } from "node:util";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ const execFileAsync = promisify(execFile);
7
+ const DEFAULT_TIMEOUT_MS = 60_000;
8
+ const DEFAULT_MAX_BUFFER = 32 * 1024 * 1024;
9
+ export class CliError extends Error {
10
+ exitCode;
11
+ stderr;
12
+ constructor(message, exitCode, stderr) {
13
+ super(message);
14
+ this.exitCode = exitCode;
15
+ this.stderr = stderr;
16
+ this.name = "CliError";
17
+ }
18
+ }
19
+ /**
20
+ * Resolve the rubien-cli binary path, preferring the App-Group-entitled
21
+ * embedded helper over any PATH-installed binary. A PATH CLI is usually an
22
+ * unsigned SPM dev build that would hit a different library.sqlite than the
23
+ * signed app.
24
+ */
25
+ export function resolveCliPath() {
26
+ const envOverride = process.env.RUBIEN_CLI;
27
+ if (envOverride && envOverride.length > 0) {
28
+ // Validate the env-pointed path so a stale value fails early with a
29
+ // clear error rather than deep inside execFile.
30
+ if (!existsSync(envOverride)) {
31
+ throw new Error(`RUBIEN_CLI points at a path that does not exist: ${envOverride}`);
32
+ }
33
+ return envOverride;
34
+ }
35
+ const candidates = [
36
+ "/Applications/Rubien.app/Contents/Helpers/rubien-cli",
37
+ join(homedir(), "Applications/Rubien.app/Contents/Helpers/rubien-cli"),
38
+ // Dev path, matching scripts/build-app.sh output.
39
+ join(process.cwd(), "build/Rubien.app/Contents/Helpers/rubien-cli"),
40
+ join(process.cwd(), "../build/Rubien.app/Contents/Helpers/rubien-cli"),
41
+ ];
42
+ for (const p of candidates) {
43
+ if (existsSync(p))
44
+ return p;
45
+ }
46
+ // Fallback: `rubien-cli` on PATH. Last resort only — typically points at a
47
+ // dev SPM build without the App Group entitlement, which would read a
48
+ // different library.sqlite than the signed app.
49
+ return "rubien-cli";
50
+ }
51
+ /**
52
+ * Invoke rubien-cli with the given argv and return the parsed result.
53
+ *
54
+ * Contract: on exit 0, stdout is JSON (default) or plain text (`textMode`).
55
+ * On non-zero exit, stderr is `{"error": "..."}` per the contract pinned in
56
+ * Tests/RubienCLITests/SwiftLibCLITests.swift:189; this function throws a
57
+ * CliError with that message.
58
+ */
59
+ export async function invokeCli(args, options = {}) {
60
+ const cliPath = resolveCliPath();
61
+ const timeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
62
+ try {
63
+ const child = execFileAsync(cliPath, args, {
64
+ timeout,
65
+ maxBuffer: DEFAULT_MAX_BUFFER,
66
+ });
67
+ // Close stdin unconditionally. Even when we have nothing to pipe, leaving
68
+ // it open causes subcommands that call `readDataToEndOfFile()` (like
69
+ // `import -`) to block until the timeout fires.
70
+ if (child.child.stdin) {
71
+ if (options.stdin !== undefined) {
72
+ child.child.stdin.write(options.stdin);
73
+ }
74
+ child.child.stdin.end();
75
+ }
76
+ const { stdout } = await child;
77
+ if (options.textMode) {
78
+ return { format: extractFormat(args), text: stdout };
79
+ }
80
+ const trimmed = stdout.trim();
81
+ if (trimmed.length === 0)
82
+ return null;
83
+ return JSON.parse(trimmed);
84
+ }
85
+ catch (err) {
86
+ // execFile error shape: { code, signal, stdout, stderr, message }
87
+ const e = err;
88
+ const stderr = (e.stderr ?? "").trim();
89
+ let parsedError;
90
+ if (stderr.length > 0) {
91
+ try {
92
+ const parsed = JSON.parse(stderr);
93
+ if (parsed && typeof parsed === "object" && "error" in parsed) {
94
+ parsedError = String(parsed.error);
95
+ }
96
+ }
97
+ catch {
98
+ // stderr wasn't JSON; fall through and use raw text.
99
+ }
100
+ }
101
+ const message = parsedError ??
102
+ (stderr.length > 0 ? stderr : (e.message ?? "rubien-cli invocation failed"));
103
+ throw new CliError(message, typeof e.code === "number" ? e.code : null, stderr);
104
+ }
105
+ }
106
+ function extractFormat(args) {
107
+ const idx = args.indexOf("--format");
108
+ if (idx >= 0 && idx + 1 < args.length)
109
+ return args[idx + 1];
110
+ const idxShort = args.indexOf("-f");
111
+ if (idxShort >= 0 && idxShort + 1 < args.length)
112
+ return args[idxShort + 1];
113
+ return "text";
114
+ }
115
+ /** Convenience: invoke and cast to a specific type. Caller is responsible
116
+ * for schema validation (use zod `.parse` at the call site). */
117
+ export async function invokeCliTyped(args, options = {}) {
118
+ return (await invokeCli(args, options));
119
+ }
120
+ /**
121
+ * Probe `rubien-cli version` with a short timeout. Returns the parsed
122
+ * {version, build} or null on any failure (missing subcommand on an old CLI,
123
+ * non-zero exit, malformed output, timeout). Never throws.
124
+ */
125
+ export async function getCliVersion() {
126
+ try {
127
+ const result = await invokeCli(["version"], { timeoutMs: 5_000 });
128
+ if (result &&
129
+ typeof result === "object" &&
130
+ typeof result.version === "string" &&
131
+ typeof result.build === "number") {
132
+ return result;
133
+ }
134
+ return null;
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }
140
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAE1C,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAE5C,MAAM,OAAO,QAAS,SAAQ,KAAK;IAGf;IACA;IAHlB,YACE,OAAe,EACC,QAAuB,EACvB,MAAc;QAE9B,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,aAAQ,GAAR,QAAQ,CAAe;QACvB,WAAM,GAAN,MAAM,CAAQ;QAG9B,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IACzB,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,cAAc;IAC5B,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;IAC3C,IAAI,WAAW,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC1C,oE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