@heywavie/cli 0.2.4 → 0.3.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 +24 -5
- package/bin/heywavie.mjs +41 -9
- package/package.json +2 -2
- package/src/chatgpt-relay.mjs +146 -0
- package/src/chatgpt-tokens.mjs +154 -0
- package/src/chatgpt.mjs +330 -0
- package/src/claude.mjs +187 -39
- package/src/host.mjs +99 -24
- package/src/link.mjs +93 -21
- package/src/service.mjs +52 -13
- package/src/wavie.mjs +17 -0
package/README.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
# heywavie CLI
|
|
2
2
|
|
|
3
3
|
Claude on the person's own computer, for Wavie: their agents think with their own Claude Pro or Max plan, through the
|
|
4
|
-
Claude Code they use there. Published to npm as `@heywavie/cli` (its command is `heywavie`); no dependencies, Node 20.3 or newer.
|
|
4
|
+
Claude Code they use there, or with their ChatGPT plan, signed in there (below). Published to npm as `@heywavie/cli` (its command is `heywavie`); no dependencies, Node 20.3 or newer.
|
|
5
5
|
|
|
6
6
|
## How it links
|
|
7
7
|
|
|
8
8
|
1. Thinks with → Claude, in Wavie (web, Mac app or iPhone), shows one sentence: "Connect this computer to my Wavie so my
|
|
9
9
|
agents think with Claude here. Follow `<api>/claude/setup#token=<one-time token>`".
|
|
10
|
-
2. They paste it into Claude Code on that computer. Claude Code reads the page (`
|
|
10
|
+
2. They paste it into Claude Code on that computer. Claude Code reads the page (heywavie-server's `src/domains/turn/prompts/claude-setup.md`) and runs
|
|
11
11
|
`npx --yes @heywavie/cli@<version> link --url "<that address>" --yes` itself.
|
|
12
12
|
3. `link` checks Claude Code (found, signed in), trades the token for this computer's own key
|
|
13
13
|
(`POST /plans/claude/hosts`), keeps it in `~/.heywavie/link.json` (mode 600), copies itself to `~/.heywavie/app` and
|
|
@@ -36,6 +36,25 @@ and `~/.heywavie` gone), unless the computer was linked again since (a new key o
|
|
|
36
36
|
`heywavie disconnect` does the same from the computer. A service with nothing linked takes itself off too; it restarts
|
|
37
37
|
after a crash, never after a clean exit.
|
|
38
38
|
|
|
39
|
+
Its calls go under `/v1` and name it (`x-wavie-client: cli/<version>`, `src/wavie.mjs`). A copy older than the server
|
|
40
|
+
takes gets 426: `link` and `status` say to update (`npm i -g @heywavie/cli@latest`, then connect again), and the
|
|
41
|
+
service logs the same and looks again every 30 minutes.
|
|
42
|
+
|
|
43
|
+
## ChatGPT on this computer
|
|
44
|
+
|
|
45
|
+
`heywavie chatgpt`, on a computer linked already, signs in to their ChatGPT plan with OpenAI's open-source "Sign in with
|
|
46
|
+
ChatGPT" (https://developers.openai.com/siwc/token-sharing-open-source): a sign-in on `127.0.0.1` (port 1455, else a
|
|
47
|
+
free one), a client id OpenAI issues them at first sign-in (`dynamic_agent_client` asks for one; the issued id and this
|
|
48
|
+
computer's host id are kept in `~/.heywavie/chatgpt-client.json`), no secret. The tokens stay in
|
|
49
|
+
`~/.heywavie/chatgpt.json` (mode 600, never logged; the refresh token rotates and is written before the new access token
|
|
50
|
+
is used), and Wavie hears only who, the plan's models and this computer (`POST /v1/device/chatgpt`). The Mac app runs the
|
|
51
|
+
same sign-in in one tap (`desktop/src/chatgpt-plan.mjs`).
|
|
52
|
+
|
|
53
|
+
With it signed in, the service waits for `can=claude,chatgpt`: a ChatGPT ask is one Responses call (`src/chatgpt-relay.mjs`),
|
|
54
|
+
which it makes with the token and relays to the turn as it comes (`POST /plan-turns/{token}/relay`: status, text, end).
|
|
55
|
+
A 401 refreshes once and tries again. Disconnect in Wavie: the service hears `{ connected: false }` (it asks every few
|
|
56
|
+
minutes), revokes the sign-in at OpenAI and deletes it here. `heywavie chatgpt --off` does the same from the computer.
|
|
57
|
+
|
|
39
58
|
```bash
|
|
40
59
|
npm test # the runner, linking, the service files, the wait loop
|
|
41
60
|
node bin/heywavie.mjs status # linked to what, the service, Claude Code
|
|
@@ -43,10 +62,10 @@ node bin/heywavie.mjs disconnect
|
|
|
43
62
|
```
|
|
44
63
|
|
|
45
64
|
`HEYWAVIE_HOME` points it at another folder, `HEYWAVIE_CLAUDE_BIN` at another Claude Code. On a dev server
|
|
46
|
-
(
|
|
47
|
-
|
|
65
|
+
(heywavie-server's `npm run demo`, `http://localhost:8787`) the setup page names the published package; the server's
|
|
66
|
+
`PLAN_CLI` points it at this checkout's `bin/heywavie.mjs` instead, and `WAVIE_API_URL` changes the address. The service's log is `~/.heywavie/host.log`.
|
|
48
67
|
|
|
49
68
|
## Publishing
|
|
50
69
|
|
|
51
|
-
Raise `version` here and `CLI_VERSION` in `
|
|
70
|
+
Raise `version` here and `CLI_VERSION` in heywavie-server's `src/app/config.ts` together, then `npm publish`
|
|
52
71
|
from this folder (signed in to npm as a member of the `heywavie` org). The setup page names that exact version, so publish before the server that names it deploys.
|
package/bin/heywavie.mjs
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { writeFileSync } from 'node:fs';
|
|
4
|
+
import { chatgptOff, chatgptSignIn } from '../src/chatgpt.mjs';
|
|
5
|
+
import { readTokens } from '../src/chatgpt-tokens.mjs';
|
|
3
6
|
import { forget, homeOf, pidPath, readLink } from '../src/home.mjs';
|
|
4
7
|
import { host } from '../src/host.mjs';
|
|
5
8
|
import { disconnect, link, status, Stop } from '../src/link.mjs';
|
|
6
|
-
import { uninstall } from '../src/service.mjs';
|
|
9
|
+
import { install, uninstall } from '../src/service.mjs';
|
|
10
|
+
import { VERSION } from '../src/wavie.mjs';
|
|
7
11
|
|
|
8
|
-
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
9
12
|
const HELP = `heywavie ${VERSION}: Claude on this computer, for Wavie
|
|
10
13
|
|
|
11
14
|
heywavie link --url "<the address from Wavie's sentence>" [--yes]
|
|
12
15
|
heywavie status [--json]
|
|
13
16
|
heywavie disconnect [--yes]
|
|
17
|
+
heywavie chatgpt your ChatGPT plan on this computer, for Wavie (sign in)
|
|
18
|
+
heywavie chatgpt --off
|
|
14
19
|
heywavie run the service itself (started for you)
|
|
15
20
|
`;
|
|
16
21
|
|
|
@@ -23,6 +28,17 @@ const value = (name) => {
|
|
|
23
28
|
const home = homeOf();
|
|
24
29
|
const stamp = (line) => console.log(`${new Date().toISOString()} ${line}`);
|
|
25
30
|
|
|
31
|
+
/** Their browser, at OpenAI's sign-in page. */
|
|
32
|
+
const openBrowser = (url) => {
|
|
33
|
+
const [cmd, args] =
|
|
34
|
+
process.platform === 'darwin'
|
|
35
|
+
? ['open', [url]]
|
|
36
|
+
: process.platform === 'win32'
|
|
37
|
+
? ['rundll32', ['url.dll,FileProtocolHandler', url]]
|
|
38
|
+
: ['xdg-open', [url]];
|
|
39
|
+
execFile(cmd, args, () => {});
|
|
40
|
+
};
|
|
41
|
+
|
|
26
42
|
/**
|
|
27
43
|
* The service: until Wavie forgets this computer or it is stopped. Wavie forgetting this process's key takes heywavie off
|
|
28
44
|
* the computer only while that key is still the one linked here: a relink since then (a new key) is left alone. With
|
|
@@ -43,10 +59,11 @@ async function serve(log) {
|
|
|
43
59
|
const onUnlinked = async () => {
|
|
44
60
|
if (readLink(home)?.key !== l.key) return;
|
|
45
61
|
leaving = true;
|
|
62
|
+
await chatgptOff({ home, log: () => {}, tellWavie: false, waitMs: 200 }).catch(() => {});
|
|
46
63
|
forget(home);
|
|
47
64
|
await uninstall({ home, fromService: true });
|
|
48
65
|
};
|
|
49
|
-
await host({ link: l, signal: stopper.signal, log, onUnlinked });
|
|
66
|
+
await host({ link: l, signal: stopper.signal, log, onUnlinked, home });
|
|
50
67
|
process.exit(0);
|
|
51
68
|
}
|
|
52
69
|
|
|
@@ -54,19 +71,34 @@ try {
|
|
|
54
71
|
if (verb === 'link') {
|
|
55
72
|
const { service } = await link({ url: value('url'), home });
|
|
56
73
|
if (service) {
|
|
57
|
-
console.log(
|
|
74
|
+
console.log(
|
|
75
|
+
`The background service could not be installed (${service}). Start it yourself with "heywavie run" as a process that keeps running; Wavie uses Claude here only while it runs.`,
|
|
76
|
+
);
|
|
58
77
|
process.exitCode = 2;
|
|
59
78
|
}
|
|
60
79
|
} else if (verb === 'run') {
|
|
61
80
|
await serve(stamp);
|
|
62
81
|
} else if (verb === 'status') {
|
|
63
|
-
const
|
|
82
|
+
const t = readTokens(home);
|
|
83
|
+
const s = { ...(await status({ home })), chatgpt: t ? { email: t.email ?? null } : null };
|
|
64
84
|
if (flag('json')) console.log(JSON.stringify(s, null, 2));
|
|
65
85
|
else {
|
|
66
|
-
console.log(
|
|
67
|
-
|
|
68
|
-
|
|
86
|
+
console.log(
|
|
87
|
+
s.linked
|
|
88
|
+
? `Linked to ${s.api} as ${s.device}; Wavie ${s.wavie === 'linked' ? 'knows this computer' : s.wavie}.`
|
|
89
|
+
: 'Not linked to Wavie.',
|
|
90
|
+
);
|
|
91
|
+
console.log(
|
|
92
|
+
`Service: ${s.service.installed ? (s.service.running ? 'installed and running' : 'installed, not running') : 'not installed'}.`,
|
|
93
|
+
);
|
|
94
|
+
console.log(`ChatGPT: ${s.chatgpt ? `signed in${s.chatgpt.email ? ` as ${s.chatgpt.email}` : ''}` : 'not signed in'}.`);
|
|
95
|
+
console.log(
|
|
96
|
+
`Claude Code: ${!s.claude.bin ? 'not found' : !s.claude.loggedIn ? `signed out (${s.claude.bin})` : `signed in${s.claude.email ? ` as ${s.claude.email}` : ''} (${s.claude.bin})`}.`,
|
|
97
|
+
);
|
|
69
98
|
}
|
|
99
|
+
} else if (verb === 'chatgpt') {
|
|
100
|
+
if (flag('off')) await chatgptOff({ home });
|
|
101
|
+
else await chatgptSignIn({ home, open: openBrowser, installer: install });
|
|
70
102
|
} else if (verb === 'disconnect') {
|
|
71
103
|
await disconnect({ home });
|
|
72
104
|
} else if (verb === '--version' || verb === '-v') {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@heywavie/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Claude on your computer, for Wavie: your agents think with your own Claude plan",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Claude and ChatGPT on your computer, for Wavie: your agents think with your own Claude or ChatGPT plan",
|
|
5
5
|
"homepage": "https://heywavie.com",
|
|
6
6
|
"license": "AGPL-3.0-only",
|
|
7
7
|
"type": "module",
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { chatgptOff, keyMark, planModels, tellWavie, wavieHasChatgpt } from './chatgpt.mjs';
|
|
2
|
+
import { accessToken, OPENAI_API, readTokens, SignedOut, writeTokens } from './chatgpt-tokens.mjs';
|
|
3
|
+
import { CLIENT_HEADER } from './wavie.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Wavie's model calls on their ChatGPT plan, made here: the server hands the service a call (`ability: 'chatgpt'`), this
|
|
7
|
+
* computer adds its token, calls OpenAI and relays the answer to the turn as it comes (`/plan-turns/{token}/relay`):
|
|
8
|
+
* its status, its text in order, then the end. Only OpenAI's Responses call: the token is never spent on anything else.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const TURN = /^[A-Za-z0-9_-]{32}$/;
|
|
12
|
+
const PATHS = new Set(['/responses']);
|
|
13
|
+
const TRIES = 3;
|
|
14
|
+
|
|
15
|
+
/** ChatGPT on this computer for the service: whether it is signed in, each call relayed, Wavie's disconnect heard. */
|
|
16
|
+
export function chatgptHere({ home, link, fetch = globalThis.fetch, log = console.log, now = Date.now }) {
|
|
17
|
+
const running = new Set();
|
|
18
|
+
|
|
19
|
+
async function call(ask) {
|
|
20
|
+
const { token, method = 'POST', path, body } = ask.input;
|
|
21
|
+
const relayAt = `${link.api}/plan-turns/${token}/relay`;
|
|
22
|
+
const stop = new AbortController();
|
|
23
|
+
running.add(stop);
|
|
24
|
+
// One relay request at a time, in order; one that doesn't get through is sent again as it was.
|
|
25
|
+
const send = async (part) => {
|
|
26
|
+
for (let i = 0; i < TRIES; i++) {
|
|
27
|
+
try {
|
|
28
|
+
const res = await fetch(relayAt, {
|
|
29
|
+
method: 'POST',
|
|
30
|
+
headers: { 'content-type': 'application/json', ...CLIENT_HEADER },
|
|
31
|
+
body: JSON.stringify(part),
|
|
32
|
+
signal: AbortSignal.timeout(20_000),
|
|
33
|
+
});
|
|
34
|
+
// The turn is gone, or the server stopped it: the call to OpenAI stops.
|
|
35
|
+
if (res.status === 404) return stop.abort(), true;
|
|
36
|
+
if (res.ok) {
|
|
37
|
+
if ((await res.json().catch(() => ({}))).stop) stop.abort();
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
} catch {
|
|
41
|
+
/* sent again */
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return false;
|
|
45
|
+
};
|
|
46
|
+
let pending = '';
|
|
47
|
+
let pump = Promise.resolve();
|
|
48
|
+
const push = (text) => {
|
|
49
|
+
pending += text;
|
|
50
|
+
pump = pump.then(async () => {
|
|
51
|
+
if (!pending) return;
|
|
52
|
+
const part = pending;
|
|
53
|
+
pending = '';
|
|
54
|
+
await send({ text: part });
|
|
55
|
+
});
|
|
56
|
+
};
|
|
57
|
+
try {
|
|
58
|
+
const openai = (access) =>
|
|
59
|
+
fetch(`${OPENAI_API}${path}`, {
|
|
60
|
+
method,
|
|
61
|
+
headers: { authorization: `Bearer ${access}`, 'content-type': 'application/json' },
|
|
62
|
+
body: typeof body === 'string' ? body : JSON.stringify(body),
|
|
63
|
+
signal: stop.signal,
|
|
64
|
+
});
|
|
65
|
+
let res = await openai(await accessToken({ home, fetch, now }));
|
|
66
|
+
if (res.status === 401) {
|
|
67
|
+
await res.body?.cancel().catch(() => {});
|
|
68
|
+
res = await openai(await accessToken({ home, fetch, now, force: true }));
|
|
69
|
+
}
|
|
70
|
+
await send({ status: res.status, headers: { 'content-type': res.headers.get('content-type') ?? 'application/json' } });
|
|
71
|
+
if (res.body) {
|
|
72
|
+
const reader = res.body.getReader();
|
|
73
|
+
const words = new TextDecoder();
|
|
74
|
+
for (;;) {
|
|
75
|
+
const { done, value } = await reader.read();
|
|
76
|
+
if (done) break;
|
|
77
|
+
push(words.decode(value, { stream: true }));
|
|
78
|
+
}
|
|
79
|
+
push(words.decode());
|
|
80
|
+
}
|
|
81
|
+
await pump;
|
|
82
|
+
await send({ end: true });
|
|
83
|
+
log(`ChatGPT call relayed (${res.status})`);
|
|
84
|
+
} catch (err) {
|
|
85
|
+
await pump;
|
|
86
|
+
const why = stop.signal.aborted
|
|
87
|
+
? 'Stopped.'
|
|
88
|
+
: err instanceof SignedOut
|
|
89
|
+
? err.message
|
|
90
|
+
: `The call to ChatGPT broke on this computer (${err?.cause?.code ?? err?.message ?? err}).`;
|
|
91
|
+
await send({ end: true, error: why });
|
|
92
|
+
log(stop.signal.aborted ? 'ChatGPT call stopped' : `ChatGPT call broke: ${err?.cause?.code ?? err?.message ?? err}`);
|
|
93
|
+
} finally {
|
|
94
|
+
running.delete(stop);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
/** Whether this computer can take ChatGPT's calls now: signed in here. */
|
|
100
|
+
signedIn: () => Boolean(readTokens(home)),
|
|
101
|
+
|
|
102
|
+
/** One of Wavie's asks: refused in words, or taken (`answer`) and relayed. Resolves once the call is over. */
|
|
103
|
+
async relay(ask, answer) {
|
|
104
|
+
const input = ask?.input ?? {};
|
|
105
|
+
if (!TURN.test(String(input.token ?? '')) || !PATHS.has(input.path) || (input.method ?? 'POST') !== 'POST')
|
|
106
|
+
return answer(ask.id, { error: "Not a ChatGPT call of Wavie's." });
|
|
107
|
+
if (!readTokens(home))
|
|
108
|
+
return answer(ask.id, {
|
|
109
|
+
error: "ChatGPT isn't signed in on that computer. Run heywavie chatgpt there, or pick heywavie under Thinks with.",
|
|
110
|
+
});
|
|
111
|
+
await answer(ask.id, { answer: { started: true } });
|
|
112
|
+
return call(ask);
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* This computer linked again since ChatGPT signed in here (a new key): Wavie hears it again, by the new key, with the
|
|
117
|
+
* plan's models as OpenAI lists them now. The same key is left alone, so a disconnect on the web isn't undone.
|
|
118
|
+
*/
|
|
119
|
+
async announce() {
|
|
120
|
+
const t = readTokens(home);
|
|
121
|
+
if (!t || t.wavieKey === keyMark(link.key)) return;
|
|
122
|
+
const models = await planModels(fetch, await accessToken({ home, fetch, now })).catch(() => t.models ?? []);
|
|
123
|
+
await tellWavie({ link, fetch, email: t.email ?? null, kind: t.kind ?? null, models });
|
|
124
|
+
const now2 = readTokens(home);
|
|
125
|
+
if (now2) writeTokens(home, { ...now2, models, wavieKey: keyMark(link.key) });
|
|
126
|
+
log('ChatGPT on this computer is connected to Wavie again, by its new link.');
|
|
127
|
+
},
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Wavie disconnected ChatGPT (from the web): its sign-in here ends too. A sign-in just made is left alone, in case
|
|
131
|
+
* Wavie's answer was read before it heard of it.
|
|
132
|
+
*/
|
|
133
|
+
async check() {
|
|
134
|
+
const t = readTokens(home);
|
|
135
|
+
if (!t || (t.savedAt && now() - Date.parse(t.savedAt) < 60_000)) return;
|
|
136
|
+
if ((await wavieHasChatgpt({ link, fetch })) !== false) return;
|
|
137
|
+
await chatgptOff({ home, fetch, log: () => {}, tellWavie: false });
|
|
138
|
+
log('ChatGPT was disconnected in Wavie: its sign-in on this computer is gone.');
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
/** Every call running now stopped: the service is stopping. */
|
|
142
|
+
stopAll() {
|
|
143
|
+
for (const c of running) c.abort();
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Their ChatGPT sign-in as kept on this computer (`chatgpt.json` in heywavie's folder, readable by them only): read,
|
|
6
|
+
* refreshed by OpenAI's rotating refresh token, revoked. Never logged.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const AUTH = 'https://auth.openai.com';
|
|
10
|
+
export const OPENAI_API = 'https://api.openai.com/v1';
|
|
11
|
+
const TOKEN = `${AUTH}/api/accounts/oauth/token`;
|
|
12
|
+
const DISCOVERY = `${AUTH}/.well-known/openid-configuration`;
|
|
13
|
+
// Refreshed this long before the access token ends.
|
|
14
|
+
const EARLY_MS = 2 * 60_000;
|
|
15
|
+
// OpenAI's refresh errors after which the sign-in can't be used again: sign in again.
|
|
16
|
+
const ENDED = new Set([
|
|
17
|
+
'invalid_grant',
|
|
18
|
+
'invalid_refresh_token',
|
|
19
|
+
'token_expired',
|
|
20
|
+
'refresh_token_expired',
|
|
21
|
+
'refresh_token_invalidated',
|
|
22
|
+
'refresh_token_reused',
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
const tokensPath = (home) => path.join(home, 'chatgpt.json');
|
|
26
|
+
// This computer's host id and the client id OpenAI issued: kept after --off, as OpenAI asks, for the next sign-in.
|
|
27
|
+
const clientPath = (home) => path.join(home, 'chatgpt-client.json');
|
|
28
|
+
|
|
29
|
+
const readJson = (file) => {
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
32
|
+
} catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
/** Written whole or not at all, readable by them only. */
|
|
37
|
+
function writeJson(home, file, value) {
|
|
38
|
+
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
39
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
40
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
41
|
+
chmodSync(tmp, 0o600);
|
|
42
|
+
renameSync(tmp, file);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The ChatGPT sign-in kept here, or null. */
|
|
46
|
+
export function readTokens(home) {
|
|
47
|
+
const t = readJson(tokensPath(home));
|
|
48
|
+
return t?.clientId && t?.access && t?.refresh ? t : null;
|
|
49
|
+
}
|
|
50
|
+
export const writeTokens = (home, t) => writeJson(home, tokensPath(home), t);
|
|
51
|
+
export const dropTokens = (home) => rmSync(tokensPath(home), { force: true });
|
|
52
|
+
export const readClient = (home) => readJson(clientPath(home));
|
|
53
|
+
export const writeClient = (home, c) => writeJson(home, clientPath(home), c);
|
|
54
|
+
/** The app copy the service runs, by its version. */
|
|
55
|
+
export const appVersion = (home) => readJson(path.join(home, 'app', 'package.json'))?.version ?? null;
|
|
56
|
+
|
|
57
|
+
const form = (fields) => new URLSearchParams(fields).toString();
|
|
58
|
+
const FORM = { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' };
|
|
59
|
+
|
|
60
|
+
let discovered = null;
|
|
61
|
+
export async function discovery(fetch) {
|
|
62
|
+
if (discovered) return discovered;
|
|
63
|
+
const res = await fetch(DISCOVERY, { signal: AbortSignal.timeout(15_000) });
|
|
64
|
+
if (!res.ok) throw new Error(`OpenAI's sign-in settings answered ${res.status}`);
|
|
65
|
+
discovered = await res.json();
|
|
66
|
+
return discovered;
|
|
67
|
+
}
|
|
68
|
+
/** For tests: OpenAI's settings read again. */
|
|
69
|
+
export const forgetDiscovery = () => {
|
|
70
|
+
discovered = null;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** OpenAI's token endpoint, by form: its answer, or a Stop/Error carrying its error code. */
|
|
74
|
+
export async function tokenCall(fetch, fields) {
|
|
75
|
+
const res = await fetch(TOKEN, { method: 'POST', headers: FORM, body: form(fields), signal: AbortSignal.timeout(30_000) });
|
|
76
|
+
const body = await res.json().catch(() => ({}));
|
|
77
|
+
if (!res.ok) {
|
|
78
|
+
const err = new Error(`OpenAI refused the sign-in (${body?.error ?? res.status})`);
|
|
79
|
+
err.code = body?.error ?? null;
|
|
80
|
+
err.status = res.status;
|
|
81
|
+
throw err;
|
|
82
|
+
}
|
|
83
|
+
return body;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A refresh running now, per heywavie folder: OpenAI rotates the refresh token, so two at once would spend it twice. */
|
|
87
|
+
const refreshing = new Map();
|
|
88
|
+
|
|
89
|
+
/** Thrown when the sign-in here can't be used again: the tokens are gone, they sign in again. */
|
|
90
|
+
export class SignedOut extends Error {}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* An access token to call OpenAI with: the kept one while it has a while left, else refreshed. The new refresh token
|
|
94
|
+
* is written before the new access token is handed out.
|
|
95
|
+
*/
|
|
96
|
+
export async function accessToken({ home, fetch = globalThis.fetch, force = false, now = Date.now }) {
|
|
97
|
+
const t = readTokens(home);
|
|
98
|
+
if (!t) throw new SignedOut("ChatGPT isn't signed in on this computer.");
|
|
99
|
+
if (!force && t.expiresAt - now() > EARLY_MS) return t.access;
|
|
100
|
+
if (!refreshing.has(home)) {
|
|
101
|
+
const run = (async () => {
|
|
102
|
+
let body;
|
|
103
|
+
try {
|
|
104
|
+
body = await tokenCall(fetch, {
|
|
105
|
+
grant_type: 'refresh_token',
|
|
106
|
+
client_id: t.clientId,
|
|
107
|
+
refresh_token: t.refresh,
|
|
108
|
+
resource: OPENAI_API,
|
|
109
|
+
});
|
|
110
|
+
} catch (err) {
|
|
111
|
+
if (ENDED.has(err.code)) {
|
|
112
|
+
dropTokens(home);
|
|
113
|
+
throw new SignedOut("ChatGPT's sign-in on this computer ended. Run heywavie chatgpt there to sign in again.");
|
|
114
|
+
}
|
|
115
|
+
throw err;
|
|
116
|
+
}
|
|
117
|
+
writeTokens(home, {
|
|
118
|
+
...t,
|
|
119
|
+
access: body.access_token,
|
|
120
|
+
refresh: body.refresh_token ?? t.refresh,
|
|
121
|
+
idToken: body.id_token ?? t.idToken,
|
|
122
|
+
expiresAt: now() + Number(body.expires_in ?? 3600) * 1000,
|
|
123
|
+
...(body.scope ? { scopes: String(body.scope).split(/\s+/).filter(Boolean) } : {}),
|
|
124
|
+
});
|
|
125
|
+
return body.access_token;
|
|
126
|
+
})().finally(() => refreshing.delete(home));
|
|
127
|
+
refreshing.set(home, run);
|
|
128
|
+
}
|
|
129
|
+
return refreshing.get(home);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The refresh token revoked at OpenAI (its revocation endpoint, from its settings), tried again on a network error or a
|
|
134
|
+
* 5xx: true once OpenAI confirmed it.
|
|
135
|
+
*/
|
|
136
|
+
export async function revoke(t, { fetch = globalThis.fetch, tries = 3, waitMs = 1000 } = {}) {
|
|
137
|
+
for (let i = 0; i < tries; i++) {
|
|
138
|
+
try {
|
|
139
|
+
const { revocation_endpoint: at } = await discovery(fetch);
|
|
140
|
+
const res = await fetch(at, {
|
|
141
|
+
method: 'POST',
|
|
142
|
+
headers: FORM,
|
|
143
|
+
body: form({ token: t.refresh, token_type_hint: 'refresh_token', client_id: t.clientId }),
|
|
144
|
+
signal: AbortSignal.timeout(15_000),
|
|
145
|
+
});
|
|
146
|
+
if (res.ok) return true;
|
|
147
|
+
if (res.status < 500) return false;
|
|
148
|
+
} catch {
|
|
149
|
+
/* tried again below */
|
|
150
|
+
}
|
|
151
|
+
if (i < tries - 1) await new Promise((r) => setTimeout(r, waitMs * 2 ** i));
|
|
152
|
+
}
|
|
153
|
+
return false;
|
|
154
|
+
}
|