literarywormai 0.0.0-stage → 1.0.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 +95 -2
- package/bin/literarywormai.js +8 -0
- package/lib/args.js +155 -0
- package/lib/client.js +316 -0
- package/lib/display.js +158 -0
- package/lib/main.js +334 -0
- package/lib/oauth.js +118 -0
- package/package.json +19 -4
package/README.md
CHANGED
|
@@ -1,3 +1,96 @@
|
|
|
1
|
-
#
|
|
1
|
+
# literarywormai
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
LiteraryWorm AI from the command line. It reads your books, chapters, story bible, research notes and readiness
|
|
4
|
+
scores, and saves drafts when you say so. It talks to the same connector your AI apps use
|
|
5
|
+
(`https://literaryworm.net/api/mcp`), so it can do exactly what a connected AI app can do and nothing more: it never
|
|
6
|
+
publishes, deletes, buys or changes your account.
|
|
7
|
+
|
|
8
|
+
Needs Node 18 or later. No dependencies.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install -g literarywormai # puts "literarywormai" on your PATH
|
|
14
|
+
npx literarywormai help # or run it without installing
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
From a copy of the LiteraryWorm AI repository: `npx ./cli help` or `node cli/bin/literarywormai.js help`.
|
|
18
|
+
|
|
19
|
+
## Sign in
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
literarywormai login # opens LiteraryWorm AI in your browser: sign in, then Allow
|
|
23
|
+
literarywormai whoami # which account this computer is signed in to
|
|
24
|
+
literarywormai logout # forgets the sign-in on this computer
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`login` uses OAuth 2.1 with PKCE, through the same Supabase sign-in your AI apps use. It waits for the browser on
|
|
28
|
+
`http://127.0.0.1:47319/callback` (another port if that one is taken; `--port N` picks one). If you use two-step
|
|
29
|
+
sign-in, enter your code when you sign in, or your books stay hidden.
|
|
30
|
+
|
|
31
|
+
The sign-in is kept in one file only you can read (`~/.config/literarywormai/credentials.json`, or
|
|
32
|
+
`%APPDATA%\literarywormai\credentials.json` on Windows) and renews itself. `logout` forgets it here; to end its
|
|
33
|
+
access everywhere, **Disconnect** "LiteraryWorm AI command line on <your computer>" in
|
|
34
|
+
**Settings › Connected AI apps** on literaryworm.net.
|
|
35
|
+
|
|
36
|
+
## Read
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
literarywormai books # your books (books marked "No AI" are left out)
|
|
40
|
+
literarywormai book <book-id> # details and chapters
|
|
41
|
+
literarywormai chapters <book-id> # chapters with each one's revision
|
|
42
|
+
literarywormai chapter <book-id> <chapter-id> --all
|
|
43
|
+
literarywormai bible <book-id>
|
|
44
|
+
literarywormai notes [book-id]
|
|
45
|
+
literarywormai note <note-id> --all
|
|
46
|
+
literarywormai readiness <book-id>
|
|
47
|
+
literarywormai tools # the connector's tools
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Long chapters and notes come in parts; `--part N` reads one, `--all` reads them all. `--page N` pages through long
|
|
51
|
+
lists. Add `--json` to any command for the connector's own answer.
|
|
52
|
+
|
|
53
|
+
## Save drafts
|
|
54
|
+
|
|
55
|
+
Each of these asks before saving. Add `--yes` (or `-y`) to save without being asked, for example in a script;
|
|
56
|
+
without a terminal to ask on, they need `--yes`.
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
literarywormai add-chapter <book-id> --text @chapter-12.txt --title "The Crossing"
|
|
60
|
+
literarywormai edit-chapter <book-id> <chapter-id> --revision <revision> --find "old words" --replace-with "new words"
|
|
61
|
+
literarywormai edit-chapter <book-id> <chapter-id> --revision <revision> --append @more.txt
|
|
62
|
+
literarywormai add-note <book-id> --title "Tide tables" --url https://example.com/tides --kind source
|
|
63
|
+
literarywormai add-entry <book-id> --kind character --name "Mara Vey" --notes "Captain of the Gull"
|
|
64
|
+
literarywormai edit-entry <book-id> <entry-id> --notes "Captain, later harbourmaster"
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Text can come from a file (`@path`) or standard input (`-`); start with `@@` for text that begins with `@`.
|
|
68
|
+
`edit-chapter` needs the chapter's revision (from `chapters` or `chapter`), so a newer change is never overwritten.
|
|
69
|
+
Every change is kept in Version history in LiteraryWorm AI, so you can undo it there, and text saved this way counts
|
|
70
|
+
as AI-generated for the book's AI disclosure, as with any connected AI app.
|
|
71
|
+
|
|
72
|
+
## Exit codes
|
|
73
|
+
|
|
74
|
+
| Code | Meaning |
|
|
75
|
+
| --- | --- |
|
|
76
|
+
| 0 | Done (or you answered no) |
|
|
77
|
+
| 1 | Something went wrong; the message says what |
|
|
78
|
+
| 2 | The command line wasn't right, or a save needs `--yes` |
|
|
79
|
+
| 3 | Not signed in, or the sign-in ended: run `literarywormai login` |
|
|
80
|
+
| 4 | LiteraryWorm AI said no: the demo account, a guest, a locked or "No AI" book, a sign-in without your two-step code |
|
|
81
|
+
| 5 | LiteraryWorm AI couldn't be reached |
|
|
82
|
+
|
|
83
|
+
## Developing
|
|
84
|
+
|
|
85
|
+
`npm test` here (or `npm test` at the top of the repository) runs the Jest tests; the connector and the sign-in
|
|
86
|
+
server are stand-ins, so nothing goes over the network. `LITERARYWORMAI_MCP_URL` points the tool at another copy of
|
|
87
|
+
the connector, for example a local `vercel dev` (`http://localhost:3000/api/mcp`). Every command then warns which
|
|
88
|
+
connector it is using, `login` names the connector and the sign-in server before opening the browser, and a connector
|
|
89
|
+
that sends sign-in anywhere but LiteraryWorm AI's own Supabase projects is refused unless
|
|
90
|
+
`LITERARYWORMAI_ALLOW_OTHER_AUTH=1` is set.
|
|
91
|
+
|
|
92
|
+
The connector is `app/api/mcp.ts`; its tools are in `app/api/_lib/mcpTools.ts`. The command line adds nothing on the
|
|
93
|
+
server: a command is one `tools/call` (or `tools/list`) JSON-RPC request with the author's own token.
|
|
94
|
+
|
|
95
|
+
Publishing: `npm publish` from this folder (the package is `literarywormai`). Settings, Help and What's new on
|
|
96
|
+
literaryworm.net tell authors to run `npm install -g literarywormai`, so publish before a release that shows them.
|
package/lib/args.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Reads the command line: a command, its words and its options. No I/O (text given as @file or - is read later,
|
|
3
|
+
// by main.js).
|
|
4
|
+
|
|
5
|
+
/** The story bible kinds and research note kinds the connector takes (app/api/_lib/mcpTools.ts). */
|
|
6
|
+
const BIBLE_KINDS = ["character", "place", "rule", "timeline", "style", "term", "relationship"];
|
|
7
|
+
const NOTE_KINDS = ["note", "source"];
|
|
8
|
+
|
|
9
|
+
/** Options that take a whole number, with the smallest and largest each allows. */
|
|
10
|
+
const NUMBERS = { page: [1, 10_000], part: [1, 10_000], port: [0, 65_535] };
|
|
11
|
+
/** Options that take text. */
|
|
12
|
+
const TEXTS = ["title", "text", "url", "kind", "name", "notes", "revision", "find", "replace-with", "append", "new-text"];
|
|
13
|
+
/** Options that are on or off. */
|
|
14
|
+
const FLAGS = { "--json": "json", "--yes": "yes", "-y": "yes", "--all": "all" };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Each command: its words (required, then optional), the options it takes, and whether it saves a draft (and so
|
|
18
|
+
* asks first, unless --yes).
|
|
19
|
+
*/
|
|
20
|
+
const COMMANDS = {
|
|
21
|
+
help: { words: [], optional: ["command"], options: [] },
|
|
22
|
+
version: { words: [], options: [] },
|
|
23
|
+
login: { words: [], options: ["port"] },
|
|
24
|
+
logout: { words: [], options: [] },
|
|
25
|
+
whoami: { words: [], options: [] },
|
|
26
|
+
tools: { words: [], options: [] },
|
|
27
|
+
books: { words: [], options: ["page"] },
|
|
28
|
+
book: { words: ["book-id"], options: [] },
|
|
29
|
+
chapters: { words: ["book-id"], options: [] },
|
|
30
|
+
chapter: { words: ["book-id", "chapter-id"], options: ["part", "all"] },
|
|
31
|
+
bible: { words: ["book-id"], options: ["page"] },
|
|
32
|
+
notes: { words: [], optional: ["book-id"], options: ["page"] },
|
|
33
|
+
note: { words: ["note-id"], options: ["part", "all"] },
|
|
34
|
+
readiness: { words: ["book-id"], options: [] },
|
|
35
|
+
"add-chapter": { words: ["book-id"], options: ["text", "title", "yes"], write: true },
|
|
36
|
+
"edit-chapter": { words: ["book-id", "chapter-id"], options: ["revision", "find", "replace-with", "append", "new-text", "yes"], write: true },
|
|
37
|
+
"add-note": { words: [], optional: ["book-id"], options: ["title", "text", "url", "kind", "yes"], write: true },
|
|
38
|
+
"add-entry": { words: ["book-id"], options: ["kind", "name", "notes", "yes"], write: true },
|
|
39
|
+
"edit-entry": { words: ["book-id", "entry-id"], options: ["name", "kind", "notes", "yes"], write: true },
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
class UsageError extends Error {}
|
|
43
|
+
|
|
44
|
+
const usageFor = (command) => {
|
|
45
|
+
const c = COMMANDS[command];
|
|
46
|
+
const words = [...c.words.map((w) => `<${w}>`), ...(c.optional || []).map((w) => `[${w}]`)].join(" ");
|
|
47
|
+
return `literarywormai ${command}${words ? ` ${words}` : ""}`;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** A whole-number option's value, or a UsageError naming the range. */
|
|
51
|
+
function wholeNumber(name, value) {
|
|
52
|
+
const [min, max] = NUMBERS[name];
|
|
53
|
+
const n = Number(value);
|
|
54
|
+
if (value === "" || !Number.isInteger(n) || n < min || n > max) throw new UsageError(`--${name} must be a whole number from ${min} to ${max}.`);
|
|
55
|
+
return n;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The rules a command's options must meet before anything is sent. */
|
|
59
|
+
function checkCommand(command, options) {
|
|
60
|
+
if (command === "add-chapter" && !options.text) throw new UsageError('Give the chapter text: --text "..." or --text @chapter.txt');
|
|
61
|
+
if (command === "edit-chapter") {
|
|
62
|
+
if (!options.revision) throw new UsageError('Give the chapter\'s revision (from "literarywormai chapters <book-id>"): --revision <revision>');
|
|
63
|
+
const modes = [options.find !== undefined || options["replace-with"] !== undefined, options.append !== undefined, options["new-text"] !== undefined].filter(Boolean).length;
|
|
64
|
+
if (modes !== 1) throw new UsageError("Send exactly one kind of change: --find with --replace-with, --append, or --new-text.");
|
|
65
|
+
if ((options.find === undefined) !== (options["replace-with"] === undefined)) throw new UsageError("--find and --replace-with go together.");
|
|
66
|
+
}
|
|
67
|
+
if (command === "add-note") {
|
|
68
|
+
if (!options.title) throw new UsageError('Give the note a title: --title "..."');
|
|
69
|
+
if (!options.text && !options.url) throw new UsageError("Give the note text (--text), a web address (--url), or both.");
|
|
70
|
+
if (options.kind !== undefined && !NOTE_KINDS.includes(options.kind)) throw new UsageError(`--kind must be one of ${NOTE_KINDS.join(", ")}.`);
|
|
71
|
+
}
|
|
72
|
+
if (command === "add-entry") {
|
|
73
|
+
if (!options.kind || !BIBLE_KINDS.includes(options.kind)) throw new UsageError(`--kind must be one of ${BIBLE_KINDS.join(", ")}.`);
|
|
74
|
+
if (!options.name) throw new UsageError('Give the entry a name: --name "..."');
|
|
75
|
+
}
|
|
76
|
+
if (command === "edit-entry") {
|
|
77
|
+
if (options.name === undefined && options.kind === undefined && options.notes === undefined) throw new UsageError("Send at least one of --name, --kind or --notes.");
|
|
78
|
+
if (options.kind !== undefined && !BIBLE_KINDS.includes(options.kind)) throw new UsageError(`--kind must be one of ${BIBLE_KINDS.join(", ")}.`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* parseArgs(["chapter", "b1", "c1", "--part", "2", "--json"]) →
|
|
84
|
+
* { command: "chapter", words: ["b1", "c1"], options: { part: 2 }, json: true }
|
|
85
|
+
*/
|
|
86
|
+
function parseArgs(argv) {
|
|
87
|
+
const words = [];
|
|
88
|
+
const options = {};
|
|
89
|
+
let json = false;
|
|
90
|
+
for (let i = 0; i < argv.length; i++) {
|
|
91
|
+
const arg = argv[i];
|
|
92
|
+
if (arg === "--help" || arg === "-h") return { command: "help", words: words.slice(0, 1), options: {}, json };
|
|
93
|
+
if (arg === "--version" || arg === "-v") return { command: "version", words: [], options: {}, json };
|
|
94
|
+
if (arg in FLAGS) {
|
|
95
|
+
if (FLAGS[arg] === "json") json = true;
|
|
96
|
+
else options[FLAGS[arg]] = true;
|
|
97
|
+
} else if (arg.startsWith("--")) {
|
|
98
|
+
const eq = arg.indexOf("=");
|
|
99
|
+
const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
|
|
100
|
+
const value = eq === -1 ? argv[++i] : arg.slice(eq + 1);
|
|
101
|
+
if (!(name in NUMBERS) && !TEXTS.includes(name)) throw new UsageError(`Unknown option --${name}. Try "literarywormai help".`);
|
|
102
|
+
// "--title --yes" is a missing title, not a title of "--yes" (write --title=--yes for that).
|
|
103
|
+
if (value === undefined || (eq === -1 && value.startsWith("--"))) throw new UsageError(`--${name} needs a value.`);
|
|
104
|
+
options[name] = name in NUMBERS ? wholeNumber(name, value) : value;
|
|
105
|
+
} else words.push(arg);
|
|
106
|
+
}
|
|
107
|
+
const command = words.shift() || "help";
|
|
108
|
+
const spec = COMMANDS[command];
|
|
109
|
+
if (!spec) throw new UsageError(`Unknown command: ${command}. Try "literarywormai help".`);
|
|
110
|
+
for (const name of Object.keys(options)) {
|
|
111
|
+
if (!spec.options.includes(name)) throw new UsageError(`--${name} doesn't go with ${command}. Usage: ${usageFor(command)}`);
|
|
112
|
+
}
|
|
113
|
+
const most = spec.words.length + (spec.optional || []).length;
|
|
114
|
+
if (words.length < spec.words.length || words.length > most) throw new UsageError(`Usage: ${usageFor(command)}`);
|
|
115
|
+
if (words.some((w) => w.trim() === "")) throw new UsageError(`An id can't be empty. Usage: ${usageFor(command)}`);
|
|
116
|
+
checkCommand(command, options);
|
|
117
|
+
return { command, words, options, json };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const isWrite = (command) => Boolean(COMMANDS[command] && COMMANDS[command].write);
|
|
121
|
+
|
|
122
|
+
const HELP = `LiteraryWorm AI from the command line. It reads your books and, when you say so, saves drafts, through the
|
|
123
|
+
same connector your AI apps use (https://literaryworm.net/api/mcp). It never publishes, deletes, buys or changes
|
|
124
|
+
your account.
|
|
125
|
+
|
|
126
|
+
Sign in:
|
|
127
|
+
literarywormai login [--port N] Opens LiteraryWorm AI in your browser to sign in and allow this computer
|
|
128
|
+
literarywormai whoami Who this computer is signed in as
|
|
129
|
+
literarywormai logout Forgets the sign-in on this computer
|
|
130
|
+
|
|
131
|
+
Read:
|
|
132
|
+
literarywormai books [--page N] Your books (books marked "No AI" are left out)
|
|
133
|
+
literarywormai book <book-id> A book's details and chapters
|
|
134
|
+
literarywormai chapters <book-id> A book's chapters, with each one's revision
|
|
135
|
+
literarywormai chapter <book-id> <chapter-id> [--part N | --all]
|
|
136
|
+
literarywormai bible <book-id> [--page N] The story bible
|
|
137
|
+
literarywormai notes [book-id] [--page N] Research notes (without a book: notes not tied to one)
|
|
138
|
+
literarywormai note <note-id> [--part N | --all] One research note in full
|
|
139
|
+
literarywormai readiness <book-id> How ready the book is at each stage
|
|
140
|
+
literarywormai tools The connector's tools
|
|
141
|
+
|
|
142
|
+
Save drafts (each asks first; add --yes to skip the question):
|
|
143
|
+
literarywormai add-chapter <book-id> --text <text> [--title <title>]
|
|
144
|
+
literarywormai edit-chapter <book-id> <chapter-id> --revision <revision>
|
|
145
|
+
(--find <text> --replace-with <text> | --append <text> | --new-text <text>)
|
|
146
|
+
literarywormai add-note [book-id] --title <title> [--text <text>] [--url <address>] [--kind note|source]
|
|
147
|
+
literarywormai add-entry <book-id> --kind <kind> --name <name> [--notes <text>]
|
|
148
|
+
literarywormai edit-entry <book-id> <entry-id> [--name <name>] [--kind <kind>] [--notes <text>]
|
|
149
|
+
Kinds: ${BIBLE_KINDS.join(", ")}.
|
|
150
|
+
Any text can come from a file (--text @chapter.txt) or from standard input (--text -).
|
|
151
|
+
|
|
152
|
+
Add --json to any command for the connector's own answer. Every change is kept in Version history in
|
|
153
|
+
LiteraryWorm AI, so you can undo it there. Disconnect this computer at any time in Settings › Connected AI apps.`;
|
|
154
|
+
|
|
155
|
+
module.exports = { parseArgs, isWrite, UsageError, HELP, COMMANDS, BIBLE_KINDS, NOTE_KINDS, NUMBERS };
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Talks to the LiteraryWorm AI connector (https://literaryworm.net/api/mcp) with JSON-RPC, as an MCP app does, and
|
|
3
|
+
// keeps this computer's sign-in in one small file readable only by you. The connector decides what the tokens can
|
|
4
|
+
// reach (row-level security, "No AI" books, locked books, the demo and guest rules): this tool adds nothing.
|
|
5
|
+
|
|
6
|
+
const fs = require("node:fs");
|
|
7
|
+
const os = require("node:os");
|
|
8
|
+
const path = require("node:path");
|
|
9
|
+
const oauth = require("./oauth");
|
|
10
|
+
|
|
11
|
+
const DEFAULT_URL = "https://literaryworm.net/api/mcp";
|
|
12
|
+
/** The MCP protocol version the connector speaks (app/api/_lib/mcpServer.test.ts). */
|
|
13
|
+
const PROTOCOL_VERSION = "2025-11-25";
|
|
14
|
+
/** Refresh the access token this long before it runs out. */
|
|
15
|
+
const REFRESH_EARLY_MS = 60_000;
|
|
16
|
+
/** Supabase's access tokens last an hour unless it says otherwise. */
|
|
17
|
+
const DEFAULT_EXPIRES_SECONDS = 3600;
|
|
18
|
+
/** How long one call to LiteraryWorm AI may take. */
|
|
19
|
+
const TIMEOUT_MS = 60_000;
|
|
20
|
+
/**
|
|
21
|
+
* The Supabase projects that sign authors in to LiteraryWorm AI: production and its dev branch. A connector named by
|
|
22
|
+
* LITERARYWORMAI_MCP_URL must send sign-in to one of these, unless LITERARYWORMAI_ALLOW_OTHER_AUTH=1.
|
|
23
|
+
*/
|
|
24
|
+
const LITERARYWORM_AUTH_HOSTS = ["vudzfuvvvonktwcdeigl.supabase.co", "qllwelvpgrdimjofsryp.supabase.co"];
|
|
25
|
+
|
|
26
|
+
class NotConnected extends Error {
|
|
27
|
+
constructor(message = 'This computer isn\'t signed in to LiteraryWorm AI. Run "literarywormai login".') {
|
|
28
|
+
super(message);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** The connector said no (the demo, a guest, a locked or "No AI" book, a missing two-step sign-in, bad input). */
|
|
32
|
+
class Refused extends Error {}
|
|
33
|
+
/** LiteraryWorm AI couldn't be reached at all. */
|
|
34
|
+
class Offline extends Error {
|
|
35
|
+
constructor(message = "Couldn't reach LiteraryWorm AI. Check your internet connection, then try again.") {
|
|
36
|
+
super(message);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The connector's address: LITERARYWORMAI_MCP_URL (to try another copy) or literaryworm.net's. */
|
|
41
|
+
function mcpUrl(env = process.env) {
|
|
42
|
+
const url = (env.LITERARYWORMAI_MCP_URL || DEFAULT_URL).replace(/\/+$/, "");
|
|
43
|
+
if (!oauth.safeAddress(url)) throw new Error("LITERARYWORMAI_MCP_URL must be an https address (or http on this computer).");
|
|
44
|
+
return url;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Where the sign-in is kept: the platform's own place for a program's settings. */
|
|
48
|
+
function credentialsPath(env = process.env, platform = process.platform, home = os.homedir()) {
|
|
49
|
+
const base = platform === "win32" ? env.APPDATA || path.join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || path.join(home, ".config");
|
|
50
|
+
return path.join(base, "literarywormai", "credentials.json");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The connector's host when it isn't literaryworm.net's, for the warning every command prints; else null. */
|
|
54
|
+
function overriddenHost(url) {
|
|
55
|
+
return url === DEFAULT_URL ? null : new URL(url).host;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function fileStore(file = credentialsPath(), platform = process.platform) {
|
|
59
|
+
return {
|
|
60
|
+
file,
|
|
61
|
+
read() {
|
|
62
|
+
try {
|
|
63
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
64
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
65
|
+
} catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
/** Written for this user only: the file 0600, its folder 0700. */
|
|
70
|
+
write(value) {
|
|
71
|
+
const dir = path.dirname(file);
|
|
72
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
73
|
+
// mkdir leaves a folder that already existed as it was: tighten it too (Windows has no such permissions).
|
|
74
|
+
if (platform !== "win32") fs.chmodSync(dir, 0o700);
|
|
75
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
76
|
+
fs.writeFileSync(temp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 });
|
|
77
|
+
fs.chmodSync(temp, 0o600);
|
|
78
|
+
fs.renameSync(temp, file);
|
|
79
|
+
},
|
|
80
|
+
remove() {
|
|
81
|
+
fs.rmSync(file, { force: true });
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The body as JSON, or null. */
|
|
87
|
+
async function readJson(res) {
|
|
88
|
+
const text = await res.text();
|
|
89
|
+
try {
|
|
90
|
+
return JSON.parse(text);
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A JSON-RPC answer sent as JSON, or (if the server chose a stream) as server-sent events. */
|
|
97
|
+
async function readRpc(res) {
|
|
98
|
+
const type = (res.headers && typeof res.headers.get === "function" && res.headers.get("content-type")) || "";
|
|
99
|
+
const text = await res.text();
|
|
100
|
+
if (type.includes("text/event-stream")) {
|
|
101
|
+
const data = text.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim());
|
|
102
|
+
for (const d of data.reverse()) {
|
|
103
|
+
try {
|
|
104
|
+
const value = JSON.parse(d);
|
|
105
|
+
if (value && (value.result !== undefined || value.error !== undefined)) return value;
|
|
106
|
+
} catch {
|
|
107
|
+
// Not JSON: keep looking.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
return JSON.parse(text);
|
|
114
|
+
} catch {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The tokens from a token endpoint answer, with when the access token runs out. */
|
|
120
|
+
function tokensFrom(body, now) {
|
|
121
|
+
if (!body || typeof body.access_token !== "string" || body.access_token === "") throw new Error("LiteraryWorm AI's answer had no sign-in in it. Try again.");
|
|
122
|
+
const seconds = Number.isFinite(body.expires_in) && body.expires_in > 0 ? body.expires_in : DEFAULT_EXPIRES_SECONDS;
|
|
123
|
+
return { accessToken: body.access_token, refreshToken: typeof body.refresh_token === "string" ? body.refresh_token : null, expiresAt: now + seconds * 1000 };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Makes the calls. `store` keeps the sign-in (the file, or a stand-in in tests) and `fetcher` is fetch. Nothing
|
|
128
|
+
* here ever prints or returns a token.
|
|
129
|
+
*/
|
|
130
|
+
function createClient({ url = mcpUrl(), fetcher = (u, i) => fetch(u, i), store = fileStore(), now = Date.now, timeoutMs = TIMEOUT_MS, env = process.env } = {}) {
|
|
131
|
+
let rpcId = 0;
|
|
132
|
+
|
|
133
|
+
async function send(target, init = {}) {
|
|
134
|
+
try {
|
|
135
|
+
return await fetcher(target, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
136
|
+
} catch (e) {
|
|
137
|
+
if (e && (e.name === "TimeoutError" || e.name === "AbortError")) throw new Offline("LiteraryWorm AI took too long to answer. Try again in a minute.");
|
|
138
|
+
throw new Offline();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function getJson(target, what) {
|
|
143
|
+
const res = await send(target, { headers: { Accept: "application/json" } });
|
|
144
|
+
if (!res.ok) throw new Error(`Couldn't read ${what} (${res.status}). Try again later.`);
|
|
145
|
+
return readJson(res);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function postForm(target, fields) {
|
|
149
|
+
const res = await send(target, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" }, body: new URLSearchParams(fields).toString() });
|
|
150
|
+
return { res, body: await readJson(res) };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The connector's sign-in server and its endpoints, checked (oauth.checkResource, oauth.checkServer). */
|
|
154
|
+
async function discover() {
|
|
155
|
+
const issuer = oauth.checkResource(await getJson(oauth.resourceMetadataUrl(url), "LiteraryWorm AI's sign-in details"), url);
|
|
156
|
+
if (url !== DEFAULT_URL && !LITERARYWORM_AUTH_HOSTS.includes(new URL(issuer).host) && env.LITERARYWORMAI_ALLOW_OTHER_AUTH !== "1") {
|
|
157
|
+
throw new Error(`The connector at ${new URL(url).host} sends sign-in to ${new URL(issuer).host}, which isn't LiteraryWorm AI's; stopping. Set LITERARYWORMAI_ALLOW_OTHER_AUTH=1 only if you trust it.`);
|
|
158
|
+
}
|
|
159
|
+
return oauth.checkServer(await getJson(oauth.serverMetadataUrl(issuer), "the sign-in server's details"), issuer);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The saved sign-in for this address, or null. */
|
|
163
|
+
function saved() {
|
|
164
|
+
const all = store.read();
|
|
165
|
+
return all && all.url === url ? all : null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** This computer's app registration ({ clientId, redirectUri }), kept apart from the tokens; or null. */
|
|
169
|
+
function registration() {
|
|
170
|
+
const all = saved();
|
|
171
|
+
const reg = all && all.registration;
|
|
172
|
+
return reg && typeof reg.clientId === "string" && typeof reg.redirectUri === "string" ? reg : null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The saved file with its tokens dropped, keeping the registration. */
|
|
176
|
+
const withoutTokens = () => ({ url, ...(registration() ? { registration: registration() } : {}) });
|
|
177
|
+
|
|
178
|
+
async function refresh(current) {
|
|
179
|
+
if (!current.refreshToken || !current.tokenEndpoint) {
|
|
180
|
+
store.write(withoutTokens());
|
|
181
|
+
throw new NotConnected('Your sign-in has run out. Run "literarywormai login" to sign in again.');
|
|
182
|
+
}
|
|
183
|
+
const { res, body } = await postForm(current.tokenEndpoint, { grant_type: "refresh_token", refresh_token: current.refreshToken, client_id: current.clientId });
|
|
184
|
+
if (!res.ok) {
|
|
185
|
+
if (res.status === 400 || res.status === 401) {
|
|
186
|
+
// The connection ended: disconnected in Settings, or the refresh token is no longer valid.
|
|
187
|
+
store.write(withoutTokens());
|
|
188
|
+
throw new NotConnected('This computer\'s sign-in has ended (it may have been disconnected in Settings › Connected AI apps). Run "literarywormai login" to sign in again.');
|
|
189
|
+
}
|
|
190
|
+
throw new Error(`Couldn't renew the sign-in (${res.status}). Try again later.`);
|
|
191
|
+
}
|
|
192
|
+
const next = { ...current, ...tokensFrom(body, now()) };
|
|
193
|
+
if (!next.refreshToken) next.refreshToken = current.refreshToken;
|
|
194
|
+
store.write(next);
|
|
195
|
+
return next;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The signed-in connection with an access token that hasn't run out. */
|
|
199
|
+
async function ready() {
|
|
200
|
+
let current = saved();
|
|
201
|
+
if (!current || !current.accessToken) throw new NotConnected();
|
|
202
|
+
if (!Number.isFinite(current.expiresAt) || current.expiresAt - REFRESH_EARLY_MS < now()) current = await refresh(current);
|
|
203
|
+
return current;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function rpcOnce(method, params, token) {
|
|
207
|
+
const res = await send(url, {
|
|
208
|
+
method: "POST",
|
|
209
|
+
headers: {
|
|
210
|
+
"Content-Type": "application/json",
|
|
211
|
+
Accept: "application/json, text/event-stream",
|
|
212
|
+
"MCP-Protocol-Version": PROTOCOL_VERSION,
|
|
213
|
+
Authorization: `Bearer ${token}`,
|
|
214
|
+
},
|
|
215
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: ++rpcId, method, params }),
|
|
216
|
+
});
|
|
217
|
+
if (res.status === 401) {
|
|
218
|
+
const body = await readJson(res);
|
|
219
|
+
return { unauthorized: (body && typeof body.error === "string" && body.error) || null };
|
|
220
|
+
}
|
|
221
|
+
if (res.status === 429) throw new Error("Too many requests just now. Wait a minute, then try again.");
|
|
222
|
+
const body = await readRpc(res);
|
|
223
|
+
if (!res.ok || !body) {
|
|
224
|
+
const message = body && typeof body.error === "string" ? body.error : body && body.error && body.error.message;
|
|
225
|
+
throw new Error(message || `LiteraryWorm AI couldn't answer (${res.status}). Try again later.`);
|
|
226
|
+
}
|
|
227
|
+
if (body.error) throw new Error(body.error.message || "LiteraryWorm AI couldn't answer.");
|
|
228
|
+
return { result: body.result };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** One JSON-RPC call as the signed-in author: refreshes once and tries again if the token was refused. */
|
|
232
|
+
async function rpc(method, params) {
|
|
233
|
+
let current = await ready();
|
|
234
|
+
let answer = await rpcOnce(method, params, current.accessToken);
|
|
235
|
+
if (answer.unauthorized !== undefined) {
|
|
236
|
+
current = await refresh(current);
|
|
237
|
+
answer = await rpcOnce(method, params, current.accessToken);
|
|
238
|
+
if (answer.unauthorized !== undefined) {
|
|
239
|
+
throw new NotConnected(`${answer.unauthorized || "LiteraryWorm AI didn't accept this computer's sign-in."} Run "literarywormai login" to sign in again.`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return answer.result;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
url,
|
|
247
|
+
discover,
|
|
248
|
+
saved,
|
|
249
|
+
registration,
|
|
250
|
+
ready,
|
|
251
|
+
|
|
252
|
+
/** The connector's tools: name, title, description, and whether each only reads. */
|
|
253
|
+
async listTools() {
|
|
254
|
+
const result = await rpc("tools/list", {});
|
|
255
|
+
return (result && Array.isArray(result.tools) ? result.tools : []).map((t) => ({
|
|
256
|
+
name: t.name, title: t.title || (t.annotations && t.annotations.title) || t.name, description: t.description || "", readOnly: Boolean(t.annotations && t.annotations.readOnlyHint),
|
|
257
|
+
}));
|
|
258
|
+
},
|
|
259
|
+
|
|
260
|
+
/** Calls one tool. The answer's data, or Refused with the connector's own words. */
|
|
261
|
+
async callTool(name, args = {}) {
|
|
262
|
+
const result = await rpc("tools/call", { name, arguments: args });
|
|
263
|
+
const text = result && Array.isArray(result.content) && result.content[0] && typeof result.content[0].text === "string" ? result.content[0].text : "";
|
|
264
|
+
if (!result || result.isError) throw new Refused(text || "LiteraryWorm AI didn't allow that.");
|
|
265
|
+
if (result.structuredContent && typeof result.structuredContent === "object") return result.structuredContent;
|
|
266
|
+
try {
|
|
267
|
+
return JSON.parse(text);
|
|
268
|
+
} catch {
|
|
269
|
+
throw new Error("LiteraryWorm AI's answer couldn't be read. Try again.");
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Registers this computer as an app for one redirect address, unless it already is; returns the client id. The
|
|
275
|
+
* registration is kept under its own key: a working sign-in's tokens are left alone until exchange() succeeds.
|
|
276
|
+
*/
|
|
277
|
+
async register(meta, name, redirectUri) {
|
|
278
|
+
const reg = registration();
|
|
279
|
+
if (reg && reg.redirectUri === redirectUri) return reg.clientId;
|
|
280
|
+
const res = await send(meta.registration_endpoint, {
|
|
281
|
+
method: "POST",
|
|
282
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
283
|
+
body: JSON.stringify({ client_name: name, redirect_uris: [redirectUri], token_endpoint_auth_method: "none", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"] }),
|
|
284
|
+
});
|
|
285
|
+
const body = await readJson(res);
|
|
286
|
+
if (!res.ok || !body || typeof body.client_id !== "string") throw new Error((body && (body.error_description || body.msg)) || `Couldn't register this computer with LiteraryWorm AI (${res.status}). Try again later.`);
|
|
287
|
+
store.write({ ...(saved() || { url }), registration: { clientId: body.client_id, redirectUri } });
|
|
288
|
+
return body.client_id;
|
|
289
|
+
},
|
|
290
|
+
|
|
291
|
+
/** Swaps the code from the browser for this computer's tokens and keeps them. */
|
|
292
|
+
async exchange(meta, clientId, code, verifier, redirectUri) {
|
|
293
|
+
const { res, body } = await postForm(meta.token_endpoint, { grant_type: "authorization_code", code, code_verifier: verifier, client_id: clientId, redirect_uri: redirectUri });
|
|
294
|
+
if (!res.ok) throw new Error((body && body.error_description) || `Couldn't finish signing in (${res.status}). Run "literarywormai login" again.`);
|
|
295
|
+
const tokens = tokensFrom(body, now());
|
|
296
|
+
store.write({ url, registration: { clientId, redirectUri }, clientId, redirectUri, tokenEndpoint: meta.token_endpoint, issuer: meta.issuer, ...tokens });
|
|
297
|
+
},
|
|
298
|
+
|
|
299
|
+
/** Who the saved sign-in belongs to (from the access token, renewed first if needed). Never the token itself. */
|
|
300
|
+
async whoami() {
|
|
301
|
+
const current = await ready();
|
|
302
|
+
const claims = oauth.claimsOf(current.accessToken) || {};
|
|
303
|
+
return { url, email: typeof claims.email === "string" ? claims.email : null, userId: typeof claims.sub === "string" ? claims.sub : null, expiresAt: new Date(current.expiresAt).toISOString() };
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
/** Forgets the sign-in here (keeping the app registration, so the next login reuses it). */
|
|
307
|
+
logout() {
|
|
308
|
+
const current = saved();
|
|
309
|
+
if (!current || !current.accessToken) return false;
|
|
310
|
+
store.write(withoutTokens());
|
|
311
|
+
return true;
|
|
312
|
+
},
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
module.exports = { createClient, fileStore, overriddenHost, LITERARYWORM_AUTH_HOSTS, credentialsPath, mcpUrl, tokensFrom, readRpc, NotConnected, Refused, Offline, DEFAULT_URL, PROTOCOL_VERSION, REFRESH_EARLY_MS };
|
package/lib/display.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Turns the connector's answers into plain text for a terminal: tables for lists, the text itself for chapters
|
|
3
|
+
// and notes. No I/O.
|
|
4
|
+
|
|
5
|
+
/** The widest a table cell gets before it is cut with "…". */
|
|
6
|
+
const MAX_CELL = 48;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Text from the server is shown as it is, but never allowed to drive the terminal: control characters (escape
|
|
10
|
+
* sequences among them) are dropped, keeping only line breaks and tabs.
|
|
11
|
+
*/
|
|
12
|
+
function safe(text) {
|
|
13
|
+
// eslint-disable-next-line no-control-regex
|
|
14
|
+
return String(text).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** One line, at most `max` characters. */
|
|
18
|
+
function oneLine(text, max = MAX_CELL) {
|
|
19
|
+
const flat = String(text === null || text === undefined ? "" : text).replace(/\s+/g, " ").trim();
|
|
20
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const day = (iso) => (typeof iso === "string" && iso.length >= 10 ? iso.slice(0, 10) : "");
|
|
24
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
25
|
+
const count = (n) => (Number.isFinite(n) ? Number(n).toLocaleString("en-US") : "");
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A plain-text table: `columns` is [[heading, (row) => value, { full }]]; cells are cut to MAX_CELL unless full
|
|
29
|
+
* (ids and revisions stay whole so they can be copied).
|
|
30
|
+
*/
|
|
31
|
+
function table(rows, columns) {
|
|
32
|
+
const cells = rows.map((r) => columns.map(([, get, opts]) => (opts && opts.full ? oneLine(get(r), Infinity) : oneLine(get(r)))));
|
|
33
|
+
const widths = columns.map(([head], i) => Math.max(head.length, ...cells.map((c) => c[i].length)));
|
|
34
|
+
const line = (values) => values.map((v, i) => (i === values.length - 1 ? v : v.padEnd(widths[i]))).join(" ").trimEnd();
|
|
35
|
+
return [line(columns.map(([head]) => head)), ...cells.map(line)].join("\n");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** "Page 1 of 3. Next: ... --page 2" when there is more. */
|
|
39
|
+
function pageLine(result, next) {
|
|
40
|
+
if (!result.pages || result.pages <= 1) return "";
|
|
41
|
+
return result.next_page ? `Page ${result.page} of ${result.pages}. Next: ${next} --page ${result.next_page}` : `Page ${result.page} of ${result.pages}.`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const joined = (...parts) => parts.filter((p) => p !== "" && p !== null && p !== undefined).join("\n\n");
|
|
45
|
+
|
|
46
|
+
function books(result) {
|
|
47
|
+
const list = Array.isArray(result.books) ? result.books : [];
|
|
48
|
+
if (list.length === 0) return joined(result.note || "No books to show.", result.kept_note);
|
|
49
|
+
const rows = table(list, [
|
|
50
|
+
["ID", (b) => b.id, { full: true }],
|
|
51
|
+
["TITLE", (b) => b.title],
|
|
52
|
+
["STAGE", (b) => b.stage],
|
|
53
|
+
["GENRE", (b) => b.genre],
|
|
54
|
+
["UPDATED", (b) => day(b.updated_at)],
|
|
55
|
+
]);
|
|
56
|
+
return joined(rows, result.kept_note, pageLine(result, "literarywormai books"));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function chapterRows(list, withRevision) {
|
|
60
|
+
const columns = [
|
|
61
|
+
["#", (c) => c.number],
|
|
62
|
+
["ID", (c) => c.id, { full: true }],
|
|
63
|
+
["TITLE", (c) => c.title],
|
|
64
|
+
["WORDS", (c) => count(c.words)],
|
|
65
|
+
["STATUS", (c) => c.status],
|
|
66
|
+
];
|
|
67
|
+
if (withRevision) columns.push(["REVISION", (c) => c.revision, { full: true }]);
|
|
68
|
+
return table(list, columns);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function book(result) {
|
|
72
|
+
const head = [
|
|
73
|
+
`${oneLine(result.title, Infinity)}${result.subtitle ? `: ${oneLine(result.subtitle, Infinity)}` : ""}`,
|
|
74
|
+
[result.genre, result.stage, result.words !== undefined ? `${count(result.words)} words` : "", result.word_goal ? `goal ${count(result.word_goal)}` : "", result.launch_date ? `launch ${result.launch_date}` : ""].filter(Boolean).join(" · "),
|
|
75
|
+
`Book id: ${result.id}`,
|
|
76
|
+
].filter(Boolean).join("\n");
|
|
77
|
+
const list = Array.isArray(result.chapters) ? result.chapters : [];
|
|
78
|
+
return joined(head, result.description ? oneLine(result.description, 600) : "", list.length ? chapterRows(list, false) : result.note || "No chapters yet.");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function chapters(result) {
|
|
82
|
+
const list = Array.isArray(result.chapters) ? result.chapters : [];
|
|
83
|
+
if (list.length === 0) return result.note || "This book has no chapters yet.";
|
|
84
|
+
return joined(chapterRows(list, true), "Change a chapter with: literarywormai edit-chapter <book-id> <chapter-id> --revision <REVISION> ...");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A chapter or note read in parts: the text, then where it ends. */
|
|
88
|
+
function partText(result, nextCommand) {
|
|
89
|
+
const text = typeof result.text === "string" ? result.text : "";
|
|
90
|
+
const lines = [];
|
|
91
|
+
if (result.title) lines.push(oneLine(result.title, Infinity));
|
|
92
|
+
if (result.url) lines.push(result.url);
|
|
93
|
+
const body = text.trim() === "" ? result.note || "(No text yet.)" : text;
|
|
94
|
+
const tail = [];
|
|
95
|
+
if (result.parts > 1) tail.push(result.next_part ? `Part ${result.part} of ${result.parts}. Next: ${nextCommand} --part ${result.next_part} (or --all)` : `Part ${result.part} of ${result.parts}.`);
|
|
96
|
+
if (result.revision) tail.push(`Revision: ${result.revision}`);
|
|
97
|
+
return joined(lines.join("\n"), body, tail.join("\n"));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function bible(result) {
|
|
101
|
+
const list = Array.isArray(result.entries) ? result.entries : [];
|
|
102
|
+
if (list.length === 0) return result.note || "No story bible entries yet.";
|
|
103
|
+
const rows = table(list, [
|
|
104
|
+
["KIND", (e) => e.kind],
|
|
105
|
+
["NAME", (e) => `${e.name}${e.shared_with_series ? " (series)" : ""}`],
|
|
106
|
+
["ID", (e) => e.id, { full: true }],
|
|
107
|
+
["DETAILS", (e) => e.details],
|
|
108
|
+
]);
|
|
109
|
+
return joined(rows, pageLine(result, `literarywormai bible ${result.book_id}`));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function notes(result) {
|
|
113
|
+
const list = Array.isArray(result.notes) ? result.notes : [];
|
|
114
|
+
if (list.length === 0) return joined(result.note || "No research notes to show.", result.kept_note);
|
|
115
|
+
const rows = table(list, [
|
|
116
|
+
["KIND", (n) => n.kind],
|
|
117
|
+
["TITLE", (n) => n.title],
|
|
118
|
+
["ID", (n) => n.id, { full: true }],
|
|
119
|
+
["ADDED", (n) => day(n.created_at)],
|
|
120
|
+
]);
|
|
121
|
+
return joined(rows, result.kept_note, pageLine(result, `literarywormai notes${result.book_id ? ` ${result.book_id}` : ""}`), "Read one in full with: literarywormai note <ID>");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function readiness(result) {
|
|
125
|
+
const stages = Array.isArray(result.stages) ? result.stages : [];
|
|
126
|
+
const blocks = stages.map((s) => {
|
|
127
|
+
const done = Array.isArray(s.done) ? s.done : [];
|
|
128
|
+
const todo = Array.isArray(s.still_to_do) ? s.still_to_do : [];
|
|
129
|
+
return [`${s.stage}: ${s.score_percent}%`, ...done.map((d) => ` done: ${oneLine(d, 200)}`), ...todo.map((t) => ` to do: ${oneLine(t, 200)}`)].join("\n");
|
|
130
|
+
});
|
|
131
|
+
return joined(oneLine(result.title, Infinity), blocks.join("\n"), result.note);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function tools(list) {
|
|
135
|
+
if (!Array.isArray(list) || list.length === 0) return "The connector listed no tools.";
|
|
136
|
+
return table(list, [
|
|
137
|
+
["TOOL", (t) => t.name],
|
|
138
|
+
["KIND", (t) => (t.readOnly ? "read" : "saves a draft")],
|
|
139
|
+
["WHAT IT DOES", (t) => t.title],
|
|
140
|
+
]);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** What a write did: "Saved." with the ids and the connector's note. */
|
|
144
|
+
function saved(result) {
|
|
145
|
+
if (result.changed === false) return result.note || "Nothing changed: the text was already like this.";
|
|
146
|
+
const facts = [
|
|
147
|
+
["Book", result.book_id], ["Chapter", result.chapter_id], ["Note", result.note_id], ["Entry", result.entry_id],
|
|
148
|
+
["Title", result.title], ["Name", result.name], ["Kind", result.kind],
|
|
149
|
+
["Words", result.words !== undefined ? count(result.words) : undefined], ["Revision", result.revision], ["Saved by", result.saved_by],
|
|
150
|
+
].filter(([, v]) => v !== undefined && v !== null && v !== "");
|
|
151
|
+
return joined("Saved.", facts.map(([k, v]) => ` ${k}: ${oneLine(v, Infinity)}`).join("\n"), [result.note, result.undo, result.version_note].filter(Boolean).join("\n"));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function whoami(info) {
|
|
155
|
+
return [`Signed in to LiteraryWorm AI${info.email ? ` as ${info.email}` : ""}.`, `Connector: ${info.url}`, `This sign-in renews itself; the current one runs until ${info.expiresAt}.`].join("\n");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
module.exports = { MAX_CELL, safe, oneLine, table, pageLine, books, book, chapters, partText, bible, notes, readiness, tools, saved, whoami };
|
package/lib/main.js
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// The commands. Reads go straight to the connector; draft saves ask first (or need --yes), and nothing here can
|
|
3
|
+
// publish, delete, buy or change an account: the connector has no tool for any of that.
|
|
4
|
+
|
|
5
|
+
const fs = require("node:fs");
|
|
6
|
+
const http = require("node:http");
|
|
7
|
+
const os = require("node:os");
|
|
8
|
+
const readline = require("node:readline");
|
|
9
|
+
const { spawn } = require("node:child_process");
|
|
10
|
+
const { HELP, parseArgs, isWrite, UsageError } = require("./args");
|
|
11
|
+
const { createClient, credentialsPath, overriddenHost, NotConnected, Refused, Offline } = require("./client");
|
|
12
|
+
const display = require("./display");
|
|
13
|
+
const oauth = require("./oauth");
|
|
14
|
+
const { version } = require("../package.json");
|
|
15
|
+
|
|
16
|
+
/** How long the browser has to come back. */
|
|
17
|
+
const LOGIN_MINUTES = 5;
|
|
18
|
+
/** The port this computer listens on for the browser's answer; the redirect address must match it exactly. */
|
|
19
|
+
const DEFAULT_PORT = 47319;
|
|
20
|
+
/** The longest app name sent when registering (the connector keeps 60 characters). */
|
|
21
|
+
const MAX_APP_NAME = 60;
|
|
22
|
+
/** Options whose text may come from a file (@path) or standard input (-). */
|
|
23
|
+
const TEXT_OPTIONS = ["text", "notes", "find", "replace-with", "append", "new-text"];
|
|
24
|
+
|
|
25
|
+
/** Exit codes: what went wrong, for scripts. */
|
|
26
|
+
const EXIT = { ok: 0, failed: 1, usage: 2, notSignedIn: 3, refused: 4, offline: 5 };
|
|
27
|
+
|
|
28
|
+
const page = (title, text) =>
|
|
29
|
+
`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title} · LiteraryWorm AI</title>` +
|
|
30
|
+
`<body style="font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 16px"><h1>${title}</h1><p>${text}</p></body></html>`;
|
|
31
|
+
|
|
32
|
+
/** Opens the browser. If it can't, the address is on screen to open by hand. */
|
|
33
|
+
function openBrowser(url) {
|
|
34
|
+
const [cmd, args] =
|
|
35
|
+
process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
36
|
+
try {
|
|
37
|
+
const child = spawn(cmd, args, { stdio: "ignore", detached: true });
|
|
38
|
+
child.on("error", () => {});
|
|
39
|
+
child.unref();
|
|
40
|
+
} catch {
|
|
41
|
+
// The address is printed too.
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Listens on 127.0.0.1 at `port`; if that port is taken and `fallback`, on one the system picks. */
|
|
46
|
+
function listen(server, port, fallback) {
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
const onError = (err) => {
|
|
49
|
+
server.off("listening", onListening);
|
|
50
|
+
if (fallback && err && err.code === "EADDRINUSE") resolve(listen(server, 0, false));
|
|
51
|
+
else reject(err);
|
|
52
|
+
};
|
|
53
|
+
const onListening = () => {
|
|
54
|
+
server.off("error", onError);
|
|
55
|
+
resolve(server.address().port);
|
|
56
|
+
};
|
|
57
|
+
server.once("error", onError);
|
|
58
|
+
server.once("listening", onListening);
|
|
59
|
+
server.listen(port, "127.0.0.1");
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Waits on this computer (127.0.0.1 only) for the browser to come back with the answer. `started(redirectUri)` is
|
|
65
|
+
* called once it is listening, to register and open the browser.
|
|
66
|
+
*/
|
|
67
|
+
async function waitForAnswer({ attempt, issuer, port, fallback, minutes = LOGIN_MINUTES }, started) {
|
|
68
|
+
let settle;
|
|
69
|
+
const outcome = new Promise((resolve, reject) => {
|
|
70
|
+
settle = { resolve, reject };
|
|
71
|
+
});
|
|
72
|
+
const server = http.createServer((req, res) => {
|
|
73
|
+
if (!req.url || !req.url.startsWith("/callback")) {
|
|
74
|
+
res.writeHead(404).end();
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
let result;
|
|
78
|
+
try {
|
|
79
|
+
result = { ok: oauth.readCallback(req.url, attempt, issuer) };
|
|
80
|
+
} catch (err) {
|
|
81
|
+
result = { error: err };
|
|
82
|
+
}
|
|
83
|
+
res.writeHead(result.ok ? 200 : 400, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" });
|
|
84
|
+
res.end(result.ok ? page("Nearly there", "Go back to your terminal. You can close this tab.") : page("Not connected", "Go back to your terminal to see why. You can close this tab."));
|
|
85
|
+
if (result.ok) settle.resolve(result.ok);
|
|
86
|
+
else settle.reject(result.error);
|
|
87
|
+
});
|
|
88
|
+
const timer = setTimeout(() => settle.reject(new Error(`No answer after ${LOGIN_MINUTES} minutes. Run "literarywormai login" again.`)), minutes * 60_000);
|
|
89
|
+
try {
|
|
90
|
+
const bound = await listen(server, port, fallback);
|
|
91
|
+
const redirectUri = `http://127.0.0.1:${bound}/callback`;
|
|
92
|
+
await started(redirectUri);
|
|
93
|
+
const answer = await outcome;
|
|
94
|
+
return { ...answer, redirectUri };
|
|
95
|
+
} finally {
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
server.close();
|
|
98
|
+
server.closeAllConnections?.();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function login(client, out, { port, browser, minutes }) {
|
|
103
|
+
const meta = await client.discover();
|
|
104
|
+
const attempt = oauth.newAttempt();
|
|
105
|
+
const previous = client.saved();
|
|
106
|
+
const reg = client.registration ? client.registration() : null;
|
|
107
|
+
const savedPort = reg ? Number(new URL(reg.redirectUri).port) : previous && previous.redirectUri ? Number(new URL(previous.redirectUri).port) : null;
|
|
108
|
+
let clientId = "";
|
|
109
|
+
const answer = await waitForAnswer({ attempt, issuer: meta.issuer, port: port ?? savedPort ?? DEFAULT_PORT, fallback: port === undefined, ...(minutes ? { minutes } : {}) }, async (redirectUri) => {
|
|
110
|
+
const name = `LiteraryWorm AI command line on ${os.hostname()}`.slice(0, MAX_APP_NAME);
|
|
111
|
+
clientId = await client.register(meta, name, redirectUri);
|
|
112
|
+
const url = oauth.authorizeUrl(meta, clientId, redirectUri, attempt);
|
|
113
|
+
out(`Connector: ${new URL(client.url).host}. Sign-in server: ${new URL(meta.issuer).host}.`);
|
|
114
|
+
out("Opening LiteraryWorm AI in your browser. Sign in and allow this computer there, then come back.");
|
|
115
|
+
out("If nothing opens, go to:\n");
|
|
116
|
+
out(` ${url}\n`);
|
|
117
|
+
browser(url);
|
|
118
|
+
});
|
|
119
|
+
await client.exchange(meta, clientId, answer.code, attempt.verifier, answer.redirectUri);
|
|
120
|
+
out("Signed in. This computer can now read your books and, when you say so, save drafts. It can't publish, delete, buy or change your account.");
|
|
121
|
+
out("Disconnect it at any time in Settings › Connected AI apps on literaryworm.net.");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Reads all of standard input. */
|
|
125
|
+
function readStdin() {
|
|
126
|
+
return new Promise((resolve, reject) => {
|
|
127
|
+
let text = "";
|
|
128
|
+
process.stdin.setEncoding("utf8");
|
|
129
|
+
process.stdin.on("data", (chunk) => (text += chunk));
|
|
130
|
+
process.stdin.on("end", () => resolve(text));
|
|
131
|
+
process.stdin.on("error", reject);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Asks a yes-or-no question on the terminal. null (so a save needs --yes) when there is no terminal to ask on, when
|
|
137
|
+
* standard input already gave the text (--text -) or has ended, or when it closes before an answer.
|
|
138
|
+
*/
|
|
139
|
+
function askYesNo(question, { stdinUsed = false, input = process.stdin, output = process.stderr } = {}) {
|
|
140
|
+
if (!input.isTTY || stdinUsed || input.readableEnded) return Promise.resolve(null);
|
|
141
|
+
const rl = readline.createInterface({ input, output });
|
|
142
|
+
return new Promise((resolve) => {
|
|
143
|
+
let answered = false;
|
|
144
|
+
rl.on("close", () => {
|
|
145
|
+
if (!answered) resolve(null);
|
|
146
|
+
});
|
|
147
|
+
rl.question(`${question} [y/N] `, (a) => {
|
|
148
|
+
answered = true;
|
|
149
|
+
rl.close();
|
|
150
|
+
resolve(/^y(es)?$/i.test(a.trim()));
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Text options given as @file or - are read; @@ at the start stands for a single @. */
|
|
156
|
+
async function resolveTexts(options, { readFile, stdin, onStdin = () => {} }) {
|
|
157
|
+
const out = { ...options };
|
|
158
|
+
let usedStdin = false;
|
|
159
|
+
for (const name of TEXT_OPTIONS) {
|
|
160
|
+
const value = out[name];
|
|
161
|
+
if (typeof value !== "string") continue;
|
|
162
|
+
if (value === "-") {
|
|
163
|
+
if (usedStdin) throw new UsageError("Only one option can read standard input (-).");
|
|
164
|
+
usedStdin = true;
|
|
165
|
+
onStdin();
|
|
166
|
+
// One read, at most once per command line.
|
|
167
|
+
// eslint-disable-next-line no-await-in-loop
|
|
168
|
+
out[name] = await stdin();
|
|
169
|
+
} else if (value.startsWith("@@")) out[name] = value.slice(1);
|
|
170
|
+
else if (value.startsWith("@")) {
|
|
171
|
+
try {
|
|
172
|
+
out[name] = readFile(value.slice(1));
|
|
173
|
+
} catch {
|
|
174
|
+
throw new UsageError(`Couldn't read the file ${value.slice(1)}.`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const chars = (s) => `${s.length.toLocaleString("en-US")} characters`;
|
|
182
|
+
|
|
183
|
+
/** The tool, its arguments and the question asked before a draft is saved. */
|
|
184
|
+
function writeCall(command, words, o) {
|
|
185
|
+
switch (command) {
|
|
186
|
+
case "add-chapter":
|
|
187
|
+
return { tool: "add_chapter", args: { book_id: words[0], text: o.text, ...(o.title ? { title: o.title } : {}) }, question: `Add a chapter${o.title ? ` "${display.oneLine(o.title)}"` : ""} (${chars(o.text)}) to book ${words[0]}?` };
|
|
188
|
+
case "edit-chapter": {
|
|
189
|
+
const args = { book_id: words[0], chapter_id: words[1], revision: o.revision };
|
|
190
|
+
if (o.find !== undefined) Object.assign(args, { find: o.find, replace_with: o["replace-with"] });
|
|
191
|
+
if (o.append !== undefined) args.append = o.append;
|
|
192
|
+
if (o["new-text"] !== undefined) args.new_text = o["new-text"];
|
|
193
|
+
const what = o.find !== undefined ? `replace a passage (${chars(o.find)}) with ${chars(o["replace-with"])}` : o.append !== undefined ? `add ${chars(o.append)} at the end` : `replace the whole text with ${chars(o["new-text"])}`;
|
|
194
|
+
return { tool: "edit_chapter", args, question: `Change chapter ${words[1]}: ${what}? Its text before the change is kept in Version history.` };
|
|
195
|
+
}
|
|
196
|
+
case "add-note":
|
|
197
|
+
return {
|
|
198
|
+
tool: "add_research_note",
|
|
199
|
+
args: { ...(words[0] ? { book_id: words[0] } : {}), title: o.title, ...(o.text ? { text: o.text } : {}), ...(o.url ? { url: o.url } : {}), ...(o.kind ? { kind: o.kind } : {}) },
|
|
200
|
+
question: `Add the research ${o.kind === "source" ? "source" : "note"} "${display.oneLine(o.title)}"${words[0] ? ` to book ${words[0]}` : ""}?`,
|
|
201
|
+
};
|
|
202
|
+
case "add-entry":
|
|
203
|
+
return { tool: "add_story_bible_entry", args: { book_id: words[0], kind: o.kind, name: o.name, ...(o.notes !== undefined ? { notes: o.notes } : {}) }, question: `Add the ${o.kind} "${display.oneLine(o.name)}" to the story bible of book ${words[0]}?` };
|
|
204
|
+
default:
|
|
205
|
+
return {
|
|
206
|
+
tool: "edit_story_bible_entry",
|
|
207
|
+
args: { book_id: words[0], entry_id: words[1], ...(o.name !== undefined ? { name: o.name } : {}), ...(o.kind !== undefined ? { kind: o.kind } : {}), ...(o.notes !== undefined ? { notes: o.notes } : {}) },
|
|
208
|
+
question: `Change story bible entry ${words[1]}? What it said before is kept with it.`,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Reads every part of a chapter or note, one after another, joined. */
|
|
214
|
+
async function allParts(api, tool, args) {
|
|
215
|
+
const first = await api.callTool(tool, args);
|
|
216
|
+
const texts = [first.text || ""];
|
|
217
|
+
let next = first.next_part;
|
|
218
|
+
while (next) {
|
|
219
|
+
// Parts come one at a time: each answer says which part is next.
|
|
220
|
+
// eslint-disable-next-line no-await-in-loop
|
|
221
|
+
const more = await api.callTool(tool, { ...args, part: next });
|
|
222
|
+
texts.push(more.text || "");
|
|
223
|
+
next = more.next_part;
|
|
224
|
+
}
|
|
225
|
+
return { ...first, text: texts.join(""), part: 1, parts: 1, next_part: null };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Runs one command line and returns the exit code. Everything outside is passed in for tests: `client`, `confirm`
|
|
230
|
+
* (asks yes or no; null when it can't ask), `browser`, `readFile` and `stdin`.
|
|
231
|
+
*/
|
|
232
|
+
async function run(argv, deps = {}) {
|
|
233
|
+
const out = deps.out || ((line) => process.stdout.write(`${line}\n`));
|
|
234
|
+
const err = deps.err || ((line) => process.stderr.write(`${line}\n`));
|
|
235
|
+
let parsed;
|
|
236
|
+
try {
|
|
237
|
+
parsed = parseArgs(argv);
|
|
238
|
+
} catch (e) {
|
|
239
|
+
if (!(e instanceof UsageError)) throw e;
|
|
240
|
+
err(e.message);
|
|
241
|
+
return EXIT.usage;
|
|
242
|
+
}
|
|
243
|
+
const { command, words, json } = parsed;
|
|
244
|
+
if (command === "help") {
|
|
245
|
+
out(HELP);
|
|
246
|
+
return EXIT.ok;
|
|
247
|
+
}
|
|
248
|
+
if (command === "version") {
|
|
249
|
+
out(version);
|
|
250
|
+
return EXIT.ok;
|
|
251
|
+
}
|
|
252
|
+
const show = (value, pretty) => out(display.safe(json ? JSON.stringify(value, null, 2) : pretty(value)));
|
|
253
|
+
try {
|
|
254
|
+
const api = deps.client || createClient();
|
|
255
|
+
const other = overriddenHost(api.url);
|
|
256
|
+
if (other) err(`Note: using the connector at ${other} (LITERARYWORMAI_MCP_URL), not literaryworm.net.`);
|
|
257
|
+
let stdinUsed = false;
|
|
258
|
+
const options = await resolveTexts(parsed.options, {
|
|
259
|
+
readFile: deps.readFile || ((p) => fs.readFileSync(p, "utf8")), stdin: deps.stdin || readStdin, onStdin: () => { stdinUsed = true; },
|
|
260
|
+
});
|
|
261
|
+
if (isWrite(command)) {
|
|
262
|
+
const call = writeCall(command, words, options);
|
|
263
|
+
if (!options.yes) {
|
|
264
|
+
const yes = await (deps.confirm || askYesNo)(display.safe(call.question), { stdinUsed });
|
|
265
|
+
if (yes === null) throw new UsageError("This saves a draft. Add --yes to save it without being asked.");
|
|
266
|
+
if (!yes) {
|
|
267
|
+
err("Nothing was saved.");
|
|
268
|
+
return EXIT.ok;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
show(await api.callTool(call.tool, call.args), display.saved);
|
|
272
|
+
return EXIT.ok;
|
|
273
|
+
}
|
|
274
|
+
switch (command) {
|
|
275
|
+
case "login":
|
|
276
|
+
await login(api, out, { port: options.port, browser: deps.browser || openBrowser, minutes: deps.loginMinutes });
|
|
277
|
+
break;
|
|
278
|
+
case "logout":
|
|
279
|
+
out(api.logout()
|
|
280
|
+
? "Signed out on this computer. To end its access everywhere, Disconnect it in Settings › Connected AI apps on literaryworm.net."
|
|
281
|
+
: "This computer wasn't signed in.");
|
|
282
|
+
break;
|
|
283
|
+
case "whoami":
|
|
284
|
+
show(await api.whoami(), display.whoami);
|
|
285
|
+
if (!json) out(`The sign-in is kept in ${credentialsPath()}.`);
|
|
286
|
+
break;
|
|
287
|
+
case "tools":
|
|
288
|
+
show(await api.listTools(), display.tools);
|
|
289
|
+
break;
|
|
290
|
+
case "books":
|
|
291
|
+
show(await api.callTool("list_books", options.page ? { page: options.page } : {}), display.books);
|
|
292
|
+
break;
|
|
293
|
+
case "book":
|
|
294
|
+
show(await api.callTool("get_book", { book_id: words[0] }), display.book);
|
|
295
|
+
break;
|
|
296
|
+
case "chapters":
|
|
297
|
+
show(await api.callTool("get_book", { book_id: words[0] }), display.chapters);
|
|
298
|
+
break;
|
|
299
|
+
case "chapter": {
|
|
300
|
+
const args = { book_id: words[0], chapter_id: words[1] };
|
|
301
|
+
const answer = options.all ? await allParts(api, "read_chapter", args) : await api.callTool("read_chapter", { ...args, ...(options.part ? { part: options.part } : {}) });
|
|
302
|
+
show(answer, (r) => display.partText(r, `literarywormai chapter ${words[0]} ${words[1]}`));
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
305
|
+
case "bible":
|
|
306
|
+
show(await api.callTool("get_story_bible", { book_id: words[0], ...(options.page ? { page: options.page } : {}) }), display.bible);
|
|
307
|
+
break;
|
|
308
|
+
case "notes":
|
|
309
|
+
show(await api.callTool("get_research_notes", { ...(words[0] ? { book_id: words[0] } : {}), ...(options.page ? { page: options.page } : {}) }), display.notes);
|
|
310
|
+
break;
|
|
311
|
+
case "note": {
|
|
312
|
+
const args = { note_id: words[0] };
|
|
313
|
+
const answer = options.all ? await allParts(api, "read_research_note", args) : await api.callTool("read_research_note", { ...args, ...(options.part ? { part: options.part } : {}) });
|
|
314
|
+
show(answer, (r) => display.partText(r, `literarywormai note ${words[0]}`));
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
case "readiness":
|
|
318
|
+
show(await api.callTool("get_readiness", { book_id: words[0] }), display.readiness);
|
|
319
|
+
break;
|
|
320
|
+
default:
|
|
321
|
+
throw new UsageError(`Unknown command: ${command}.`);
|
|
322
|
+
}
|
|
323
|
+
return EXIT.ok;
|
|
324
|
+
} catch (e) {
|
|
325
|
+
err(display.safe(e instanceof Error ? e.message : String(e)));
|
|
326
|
+
if (e instanceof UsageError) return EXIT.usage;
|
|
327
|
+
if (e instanceof NotConnected) return EXIT.notSignedIn;
|
|
328
|
+
if (e instanceof Refused) return EXIT.refused;
|
|
329
|
+
if (e instanceof Offline) return EXIT.offline;
|
|
330
|
+
return EXIT.failed;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
module.exports = { run, askYesNo, waitForAnswer, writeCall, resolveTexts, EXIT, DEFAULT_PORT, LOGIN_MINUTES };
|
package/lib/oauth.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// The command line's side of signing in: OAuth 2.1 with PKCE, answered on this computer. No I/O.
|
|
3
|
+
// The authorization server is Supabase Auth of the project literaryworm.net uses, found the way MCP apps find it:
|
|
4
|
+
// the connector's protected-resource metadata (RFC 9728) names it, and its own metadata (RFC 8414) says where to go.
|
|
5
|
+
|
|
6
|
+
const crypto = require("node:crypto");
|
|
7
|
+
|
|
8
|
+
/** The scopes the connector asks for (app/api/_lib/mcpHttp.ts SCOPES). */
|
|
9
|
+
const SCOPES = "openid email profile";
|
|
10
|
+
|
|
11
|
+
const base64url = (buffer) => buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
12
|
+
|
|
13
|
+
/** RFC 7636's S256. */
|
|
14
|
+
function challengeFor(verifier) {
|
|
15
|
+
return base64url(crypto.createHash("sha256").update(verifier).digest());
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A fresh PKCE pair and state for one sign-in. */
|
|
19
|
+
function newAttempt(random = crypto.randomBytes) {
|
|
20
|
+
const verifier = base64url(random(48));
|
|
21
|
+
return { verifier, challenge: challengeFor(verifier), state: base64url(random(24)) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** https, or this computer (for development against a local copy). */
|
|
25
|
+
function safeAddress(value) {
|
|
26
|
+
let url;
|
|
27
|
+
try {
|
|
28
|
+
url = new URL(value);
|
|
29
|
+
} catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
|
|
33
|
+
return url.protocol === "https:" || (local && url.protocol === "http:");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** RFC 9728's address for a resource's metadata: the well-known path goes in front of the resource's own path. */
|
|
37
|
+
function resourceMetadataUrl(mcpUrl) {
|
|
38
|
+
const u = new URL(mcpUrl);
|
|
39
|
+
return `${u.origin}/.well-known/oauth-protected-resource${u.pathname.replace(/\/+$/, "")}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** RFC 8414's address for an authorization server's metadata (Supabase's issuer has a path: /auth/v1). */
|
|
43
|
+
function serverMetadataUrl(issuer) {
|
|
44
|
+
const u = new URL(issuer);
|
|
45
|
+
return `${u.origin}/.well-known/oauth-authorization-server${u.pathname.replace(/\/+$/, "")}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The authorization server the connector names, after checking the metadata is about this connector. */
|
|
49
|
+
function checkResource(metadata, mcpUrl) {
|
|
50
|
+
if (!metadata || typeof metadata !== "object") throw new Error("LiteraryWorm AI didn't say how to sign in. Try again later.");
|
|
51
|
+
if (metadata.resource !== mcpUrl) throw new Error(`The sign-in details are for another address (${String(metadata.resource)}); stopping.`);
|
|
52
|
+
const servers = metadata.authorization_servers;
|
|
53
|
+
if (!Array.isArray(servers) || typeof servers[0] !== "string" || !safeAddress(servers[0])) throw new Error("LiteraryWorm AI didn't name a safe place to sign in; stopping.");
|
|
54
|
+
return servers[0];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Checks the authorization server's description of itself before anything is sent to it: it must be the issuer the
|
|
59
|
+
* connector named, every endpoint on the issuer's own site over https, and PKCE (S256) supported.
|
|
60
|
+
*/
|
|
61
|
+
function checkServer(metadata, issuer) {
|
|
62
|
+
if (!metadata || typeof metadata !== "object") throw new Error("The sign-in server didn't describe itself. Try again later.");
|
|
63
|
+
if (metadata.issuer !== issuer) throw new Error("The sign-in server named itself differently from the one LiteraryWorm AI named; stopping.");
|
|
64
|
+
const home = new URL(issuer).origin;
|
|
65
|
+
for (const key of ["authorization_endpoint", "token_endpoint", "registration_endpoint"]) {
|
|
66
|
+
const value = metadata[key];
|
|
67
|
+
if (typeof value !== "string") throw new Error(`The sign-in server didn't say where its ${key} is.`);
|
|
68
|
+
if (!safeAddress(value) || new URL(value).origin !== home) throw new Error(`The sign-in server's ${key} is on another site; stopping.`);
|
|
69
|
+
}
|
|
70
|
+
if (!Array.isArray(metadata.code_challenge_methods_supported) || !metadata.code_challenge_methods_supported.includes("S256")) {
|
|
71
|
+
throw new Error("The sign-in server doesn't support PKCE (S256); stopping.");
|
|
72
|
+
}
|
|
73
|
+
return metadata;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Where the browser is sent to sign in and allow this computer. */
|
|
77
|
+
function authorizeUrl(metadata, clientId, redirectUri, attempt) {
|
|
78
|
+
const url = new URL(metadata.authorization_endpoint);
|
|
79
|
+
url.searchParams.set("response_type", "code");
|
|
80
|
+
url.searchParams.set("client_id", clientId);
|
|
81
|
+
url.searchParams.set("redirect_uri", redirectUri);
|
|
82
|
+
url.searchParams.set("code_challenge", attempt.challenge);
|
|
83
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
84
|
+
url.searchParams.set("state", attempt.state);
|
|
85
|
+
url.searchParams.set("scope", SCOPES);
|
|
86
|
+
return url.toString();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Reads the address the browser came back to. Returns { code }, or throws with the reason. The state must be ours
|
|
91
|
+
* and, when the server names itself (RFC 9207), it must be the one we asked.
|
|
92
|
+
*/
|
|
93
|
+
function readCallback(requestUrl, attempt, issuer) {
|
|
94
|
+
const q = new URL(requestUrl, "http://127.0.0.1").searchParams;
|
|
95
|
+
if (q.get("state") !== attempt.state) throw new Error('That answer wasn\'t for this sign-in. Run "literarywormai login" again.');
|
|
96
|
+
const iss = q.get("iss");
|
|
97
|
+
if (iss !== null && iss !== issuer) throw new Error('That answer came from another server. Run "literarywormai login" again.');
|
|
98
|
+
const error = q.get("error");
|
|
99
|
+
if (error === "access_denied") throw new Error("You chose not to allow it. Nothing was connected.");
|
|
100
|
+
if (error) throw new Error(q.get("error_description") || `LiteraryWorm AI answered: ${error}`);
|
|
101
|
+
const code = q.get("code");
|
|
102
|
+
if (!code) throw new Error('The answer had no code. Run "literarywormai login" again.');
|
|
103
|
+
return { code };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The claims in an access token, read without checking it (the connector checks it); null if unreadable. */
|
|
107
|
+
function claimsOf(token) {
|
|
108
|
+
const part = typeof token === "string" ? token.split(".")[1] : undefined;
|
|
109
|
+
if (!part) return null;
|
|
110
|
+
try {
|
|
111
|
+
const value = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
|
|
112
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
module.exports = { SCOPES, challengeFor, newAttempt, safeAddress, resourceMetadataUrl, serverMetadataUrl, checkResource, checkServer, authorizeUrl, readCallback, claimsOf };
|
package/package.json
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "literarywormai",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "LiteraryWorm AI from the command line: read your books, chapters, story bible, research notes and readiness, and save drafts when you say so, through the same connector your AI apps use.",
|
|
5
|
+
"homepage": "https://literaryworm.net/help#command-line",
|
|
6
|
+
"license": "UNLICENSED",
|
|
7
|
+
"bin": {
|
|
8
|
+
"literarywormai": "bin/literarywormai.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"lib",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "cd .. && npx --no-install jest cli/test"
|
|
20
|
+
}
|
|
21
|
+
}
|