@heywavie/cli 0.2.5 → 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 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 (`server/src/app/claude-setup.ts`) and runs
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
@@ -40,6 +40,21 @@ Its calls go under `/v1` and name it (`x-wavie-client: cli/<version>`, `src/wavi
40
40
  takes gets 426: `link` and `status` say to update (`npm i -g @heywavie/cli@latest`, then connect again), and the
41
41
  service logs the same and looks again every 30 minutes.
42
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
+
43
58
  ```bash
44
59
  npm test # the runner, linking, the service files, the wait loop
45
60
  node bin/heywavie.mjs status # linked to what, the service, Claude Code
@@ -47,10 +62,10 @@ node bin/heywavie.mjs disconnect
47
62
  ```
48
63
 
49
64
  `HEYWAVIE_HOME` points it at another folder, `HEYWAVIE_CLAUDE_BIN` at another Claude Code. On a dev server
50
- (`cd server && npm run demo`) the setup page runs this checkout's `bin/heywavie.mjs` against `http://localhost:8787`
51
- (`PLAN_CLI` and `WAVIE_API_URL` change either). The service's log is `~/.heywavie/host.log`.
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`.
52
67
 
53
68
  ## Publishing
54
69
 
55
- Raise `version` here and `CLI_VERSION` in `server/src/app/plans.ts` together (a server test checks), then `npm publish`
70
+ Raise `version` here and `CLI_VERSION` in heywavie-server's `src/app/config.ts` together, then `npm publish`
56
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,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
+ import { execFile } from 'node:child_process';
2
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';
7
10
  import { VERSION } from '../src/wavie.mjs';
8
11
 
9
12
  const HELP = `heywavie ${VERSION}: Claude on this computer, for Wavie
@@ -11,6 +14,8 @@ const HELP = `heywavie ${VERSION}: Claude on this computer, for Wavie
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
 
@@ -62,7 +79,8 @@ try {
62
79
  } else if (verb === 'run') {
63
80
  await serve(stamp);
64
81
  } else if (verb === 'status') {
65
- const s = await status({ home });
82
+ const t = readTokens(home);
83
+ const s = { ...(await status({ home })), chatgpt: t ? { email: t.email ?? null } : null };
66
84
  if (flag('json')) console.log(JSON.stringify(s, null, 2));
67
85
  else {
68
86
  console.log(
@@ -73,10 +91,14 @@ try {
73
91
  console.log(
74
92
  `Service: ${s.service.installed ? (s.service.running ? 'installed and running' : 'installed, not running') : 'not installed'}.`,
75
93
  );
94
+ console.log(`ChatGPT: ${s.chatgpt ? `signed in${s.chatgpt.email ? ` as ${s.chatgpt.email}` : ''}` : 'not signed in'}.`);
76
95
  console.log(
77
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})`}.`,
78
97
  );
79
98
  }
99
+ } else if (verb === 'chatgpt') {
100
+ if (flag('off')) await chatgptOff({ home });
101
+ else await chatgptSignIn({ home, open: openBrowser, installer: install });
80
102
  } else if (verb === 'disconnect') {
81
103
  await disconnect({ home });
82
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.2.5",
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
+ }
@@ -0,0 +1,330 @@
1
+ import { createHash, createPublicKey, randomBytes, randomUUID, verify } from 'node:crypto';
2
+ import http from 'node:http';
3
+ import {
4
+ AUTH,
5
+ appVersion,
6
+ discovery,
7
+ dropTokens,
8
+ OPENAI_API,
9
+ readClient,
10
+ readTokens,
11
+ revoke,
12
+ tokenCall,
13
+ writeClient,
14
+ writeTokens,
15
+ } from './chatgpt-tokens.mjs';
16
+ import { readLink } from './home.mjs';
17
+ import { Stop } from './link.mjs';
18
+ import { CLIENT_HEADER, routesOf, updateLine, VERSION } from './wavie.mjs';
19
+
20
+ /**
21
+ * Their ChatGPT plan on this computer: OpenAI's open-source "Sign in with ChatGPT" (developers.openai.com/siwc). The
22
+ * sign-in runs here on 127.0.0.1, OpenAI issues this person a client id of their own at first sign-in (no secret), and
23
+ * the tokens stay in heywavie's folder, readable by them only. Wavie hears only that it is connected, who, and the models.
24
+ */
25
+
26
+ const AUTHORIZE = `${AUTH}/api/accounts/authorize`;
27
+ export const SCOPE = 'openid profile email offline_access resource.invoke chatgpt.tokens.use.direct';
28
+ const PLAN_SCOPE = 'chatgpt.tokens.use.direct';
29
+ // The first sign-in's client id: OpenAI issues the real one in the callback. Never saved.
30
+ const FIRST = 'dynamic_agent_client';
31
+ const PORT = 1455;
32
+ const CALLBACK = '/auth/callback';
33
+ const WAIT_MS = 10 * 60_000;
34
+
35
+ const b64url = (buf) => Buffer.from(buf).toString('base64url');
36
+
37
+ /** OpenAI's sign-in page for this attempt: the saved issued client id, else a first registration. */
38
+ export function authorizeUrl({ clientId, hostId, redirectUri, state, nonce, challenge }) {
39
+ const q = new URLSearchParams({
40
+ response_type: 'code',
41
+ client_id: clientId ?? FIRST,
42
+ // Only on the first registration, as OpenAI asks.
43
+ ...(clientId ? {} : { agent_name_hint: 'heywavie' }),
44
+ ext_agent_host_id: hostId,
45
+ redirect_uri: redirectUri,
46
+ scope: SCOPE,
47
+ resource: OPENAI_API,
48
+ state,
49
+ nonce,
50
+ code_challenge: challenge,
51
+ code_challenge_method: 'S256',
52
+ });
53
+ return `${AUTHORIZE}?${q}`;
54
+ }
55
+
56
+ /**
57
+ * The client id this sign-in goes on with: the one OpenAI issued in the callback on a first registration (an answer
58
+ * without one is an incomplete registration), else the saved one, which a callback may leave out but never change.
59
+ */
60
+ export function issuedClientId(saved, callback) {
61
+ const sent = callback.get('client_id');
62
+ if (!saved) {
63
+ if (!sent || sent === FIRST)
64
+ throw new Stop("ChatGPT's sign-in didn't finish registering heywavie for you. Run this again.");
65
+ return sent;
66
+ }
67
+ if (sent && sent !== saved) throw new Stop("ChatGPT answered for another registration than this computer's. Run this again.");
68
+ return saved;
69
+ }
70
+
71
+ /** The ID token checked as OpenAI asks (its signature by OpenAI's keys, issuer, audience, expiry, nonce): its claims. */
72
+ export async function checkIdToken(idToken, { clientId, nonce, fetch, now = Date.now() }) {
73
+ const [h, p, s] = String(idToken ?? '').split('.');
74
+ if (!h || !p || !s) throw new Stop("ChatGPT's sign-in sent no identity. Run this again.");
75
+ const header = JSON.parse(Buffer.from(h, 'base64url').toString('utf8'));
76
+ const claims = JSON.parse(Buffer.from(p, 'base64url').toString('utf8'));
77
+ const conf = await discovery(fetch);
78
+ const keys = (await (await fetch(conf.jwks_uri, { signal: AbortSignal.timeout(15_000) })).json())?.keys ?? [];
79
+ const jwk = keys.find((k) => k.kid === header.kid) ?? (keys.length === 1 ? keys[0] : null);
80
+ const data = Buffer.from(`${h}.${p}`);
81
+ const sig = Buffer.from(s, 'base64url');
82
+ let good = false;
83
+ if (jwk && header.alg === 'RS256') good = verify('sha256', data, createPublicKey({ key: jwk, format: 'jwk' }), sig);
84
+ else if (jwk && header.alg === 'ES256')
85
+ good = verify('sha256', data, { key: createPublicKey({ key: jwk, format: 'jwk' }), dsaEncoding: 'ieee-p1363' }, sig);
86
+ const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
87
+ if (
88
+ !good ||
89
+ claims.iss !== (conf.issuer ?? AUTH) ||
90
+ !aud.includes(clientId) ||
91
+ !(claims.exp * 1000 > now) ||
92
+ claims.nonce !== nonce
93
+ )
94
+ throw new Stop("ChatGPT's sign-in came back with an identity heywavie can't trust. Run this again.");
95
+ return claims;
96
+ }
97
+
98
+ /**
99
+ * Waits on 127.0.0.1 (port 1455, else any free one) for OpenAI to send the browser back. A callback of another attempt
100
+ * (a wrong state) is refused and the wait goes on. Resolves `{ query, reply }`: `reply(words)` answers the browser.
101
+ */
102
+ export async function callbackServer({ state, signal = null, port = PORT, waitMs = WAIT_MS }) {
103
+ let done;
104
+ let failed;
105
+ const got = new Promise((resolve, reject) => {
106
+ done = resolve;
107
+ failed = reject;
108
+ });
109
+ const server = http.createServer((req, res) => {
110
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
111
+ if (url.pathname !== CALLBACK) {
112
+ res.writeHead(404).end();
113
+ return;
114
+ }
115
+ if (url.searchParams.get('state') !== state) {
116
+ res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
117
+ res.end("This isn't the sign-in heywavie started. Close this tab.");
118
+ return;
119
+ }
120
+ const reply = (words) => {
121
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
122
+ res.end(`<!doctype html><meta charset="utf-8"><title>heywavie</title><p style="font:15px system-ui;margin:40px">${words.replace(/</g, '&lt;')}</p>`);
123
+ };
124
+ done({ query: url.searchParams, reply });
125
+ });
126
+ const listen = (p) =>
127
+ new Promise((resolve, reject) => {
128
+ server.once('error', reject);
129
+ server.listen(p, '127.0.0.1', () => {
130
+ server.off('error', reject);
131
+ resolve(server.address().port);
132
+ });
133
+ });
134
+ let at;
135
+ try {
136
+ at = await listen(port);
137
+ } catch {
138
+ at = await listen(0);
139
+ }
140
+ const timer = setTimeout(() => failed(new Stop("ChatGPT's sign-in took too long. Run this again.")), waitMs);
141
+ const stop = () => failed(new Stop('The ChatGPT sign-in was stopped.'));
142
+ signal?.addEventListener('abort', stop, { once: true });
143
+ const close = () => {
144
+ clearTimeout(timer);
145
+ signal?.removeEventListener('abort', stop);
146
+ server.close();
147
+ server.closeAllConnections?.();
148
+ };
149
+ return { redirectUri: `http://127.0.0.1:${at}${CALLBACK}`, next: got, close };
150
+ }
151
+
152
+ /** The models this ChatGPT plan offers, in OpenAI's order: the slugs it lists. */
153
+ export async function planModels(fetch, access) {
154
+ const res = await fetch(`${OPENAI_API}/models`, {
155
+ headers: { authorization: `Bearer ${access}` },
156
+ signal: AbortSignal.timeout(30_000),
157
+ });
158
+ if (!res.ok) throw new Stop(`OpenAI didn't list your ChatGPT plan's models (${res.status}). Run this again.`);
159
+ const body = await res.json().catch(() => ({}));
160
+ return (body?.models ?? [])
161
+ .filter((m) => m?.visibility === 'list')
162
+ .map((m) => m.slug)
163
+ .filter((m) => typeof m === 'string');
164
+ }
165
+
166
+ /** Which of this computer's keys Wavie last heard ChatGPT from: a relink makes a new key, which Wavie must hear again. */
167
+ export const keyMark = (key) => createHash('sha256').update(String(key)).digest('base64url').slice(0, 16);
168
+
169
+ /** Wavie told this computer holds their ChatGPT plan, by its key: true once saved, else the Stop that says why. */
170
+ export async function tellWavie({ link, fetch, email, kind, models }) {
171
+ let res;
172
+ try {
173
+ res = await fetch(deviceChatgpt(link), {
174
+ method: 'POST',
175
+ headers: wavieHeaders(link),
176
+ body: JSON.stringify({ device: link.device, email, kind, models }),
177
+ signal: AbortSignal.timeout(30_000),
178
+ });
179
+ } catch (err) {
180
+ throw new Stop(`Failed to reach Wavie at ${link.api} (${err?.cause?.code ?? err?.message ?? err}). Run this again.`);
181
+ }
182
+ if (res.ok) return true;
183
+ const body = await res.json().catch(() => ({}));
184
+ if (res.status === 426) throw new Stop(updateLine(body));
185
+ if (res.status === 401)
186
+ throw new Stop('Wavie no longer knows this computer. Connect it again from Wavie (Thinks with, Claude).');
187
+ throw new Stop(`Wavie refused the ChatGPT plan (${res.status}${body?.message ? `: ${body.message}` : ''}).`);
188
+ }
189
+
190
+ const wavieHeaders = (link) => ({ authorization: `Bearer ${link.key}`, 'content-type': 'application/json', ...CLIENT_HEADER });
191
+ const deviceChatgpt = (link) => `${routesOf(link.api)}/device/chatgpt`;
192
+
193
+ /**
194
+ * Signs in with ChatGPT here and tells Wavie: on a computer linked already. `open(url)` opens their browser. The tokens
195
+ * are written only once Wavie took it, so a web disconnect check never finds a half-made sign-in.
196
+ */
197
+ export async function chatgptSignIn({
198
+ home,
199
+ open,
200
+ fetch = globalThis.fetch,
201
+ log = console.log,
202
+ signal = null,
203
+ port = PORT,
204
+ waitMs = WAIT_MS,
205
+ installer = null,
206
+ now = Date.now,
207
+ }) {
208
+ const link = readLink(home);
209
+ if (!link)
210
+ throw new Stop(
211
+ 'This computer is not connected to Wavie yet. Connect it first (Thinks with, Claude, in Wavie), then run this again.',
212
+ );
213
+ const client = readClient(home);
214
+ const hostId = client?.hostId ?? `urn:uuid:${randomUUID()}`;
215
+ if (!client?.hostId) writeClient(home, { hostId, clientId: null });
216
+ const saved = client?.clientId ?? null;
217
+ const state = b64url(randomBytes(24));
218
+ const nonce = b64url(randomBytes(24));
219
+ const verifier = b64url(randomBytes(48));
220
+ const challenge = b64url(createHash('sha256').update(verifier).digest());
221
+
222
+ const cb = await callbackServer({ state, signal, port, waitMs });
223
+ let reply = () => {};
224
+ try {
225
+ const url = authorizeUrl({ clientId: saved, hostId, redirectUri: cb.redirectUri, state, nonce, challenge });
226
+ log('Opening ChatGPT in your browser to sign in.');
227
+ log(`If it didn't open, go to: ${url}`);
228
+ await Promise.resolve(open(url)).catch(() => {});
229
+ const back = await cb.next;
230
+ reply = back.reply;
231
+ const q = back.query;
232
+ if (q.get('error') === 'access_denied') throw new Stop('You declined in ChatGPT, so nothing was connected.');
233
+ if (q.get('error')) throw new Stop(`ChatGPT's sign-in failed (${q.get('error')}). Run this again.`);
234
+ const clientId = issuedClientId(saved, q);
235
+ writeClient(home, { hostId, clientId });
236
+ const code = q.get('code');
237
+ if (!code) throw new Stop("ChatGPT's sign-in sent no code. Run this again.");
238
+
239
+ let tokens;
240
+ try {
241
+ tokens = await tokenCall(fetch, {
242
+ grant_type: 'authorization_code',
243
+ client_id: clientId,
244
+ code,
245
+ code_verifier: verifier,
246
+ redirect_uri: cb.redirectUri,
247
+ resource: OPENAI_API,
248
+ });
249
+ } catch (err) {
250
+ throw new Stop(`${err.message}. Run this again.`);
251
+ }
252
+ const scopes = String(tokens.scope ?? q.get('scope') ?? '').split(/\s+/).filter(Boolean);
253
+ if (!scopes.includes(PLAN_SCOPE))
254
+ throw new Stop(
255
+ "This ChatGPT account didn't allow its plan to be used by heywavie. Turn it on when ChatGPT asks, or use another account, then run this again.",
256
+ );
257
+ const claims = tokens.id_token ? await checkIdToken(tokens.id_token, { clientId, nonce, fetch, now: now() }) : {};
258
+ const before = readTokens(home);
259
+ if (before?.sub && claims.sub && before.sub !== claims.sub)
260
+ throw new Stop('This computer has another ChatGPT account connected. Run heywavie chatgpt --off first.');
261
+ const email = typeof claims.email === 'string' ? claims.email : null;
262
+ const kind = claims['https://api.openai.com/auth']?.chatgpt_plan_type ?? null;
263
+ const models = await planModels(fetch, tokens.access_token);
264
+
265
+ await tellWavie({ link, fetch, email, kind, models });
266
+ writeTokens(home, {
267
+ clientId,
268
+ hostId,
269
+ sub: claims.sub ?? null,
270
+ email,
271
+ kind,
272
+ idToken: tokens.id_token ?? null,
273
+ access: tokens.access_token,
274
+ refresh: tokens.refresh_token,
275
+ expiresAt: now() + Number(tokens.expires_in ?? 3600) * 1000,
276
+ scopes,
277
+ models,
278
+ wavieKey: keyMark(link.key),
279
+ savedAt: new Date(now()).toISOString(),
280
+ });
281
+ reply('ChatGPT is connected to Wavie on this computer. You can close this tab.');
282
+
283
+ // The service relays ChatGPT only from this version on: an older copy of it is replaced.
284
+ if (installer && appVersion(home) && appVersion(home) !== VERSION) {
285
+ const s = await installer({ home });
286
+ if (!s.ok) log(`The heywavie service couldn't be updated (${s.reason}). Run heywavie run, or connect again.`);
287
+ }
288
+ log(
289
+ `Your ChatGPT plan is connected to Wavie${email ? ` (${email})` : ''}. Sign-in and plan stay on this computer; Wavie uses it while this computer is on.`,
290
+ );
291
+ return { email, kind, models };
292
+ } catch (err) {
293
+ reply(err instanceof Stop ? err.message : "ChatGPT couldn't be connected. Run heywavie chatgpt again.");
294
+ throw err;
295
+ } finally {
296
+ cb.close();
297
+ }
298
+ }
299
+
300
+ /** ChatGPT off this computer: revoked at OpenAI, the tokens gone, Wavie told (`tellWavie`). */
301
+ export async function chatgptOff({ home, fetch = globalThis.fetch, log = console.log, tellWavie = true, waitMs = 1000 }) {
302
+ const t = readTokens(home);
303
+ const confirmed = t ? await revoke(t, { fetch, waitMs }) : true;
304
+ dropTokens(home);
305
+ const link = readLink(home);
306
+ if (link && tellWavie) {
307
+ await fetch(deviceChatgpt(link), {
308
+ method: 'DELETE',
309
+ headers: wavieHeaders(link),
310
+ signal: AbortSignal.timeout(15_000),
311
+ }).catch(() => null);
312
+ }
313
+ if (!t) log('ChatGPT was not signed in on this computer.');
314
+ else if (confirmed) log('ChatGPT is signed out on this computer and disconnected from Wavie.');
315
+ else
316
+ log(
317
+ "ChatGPT's sign-in is gone from this computer, but OpenAI didn't confirm it ended. To be sure, remove heywavie under Connected apps in ChatGPT's settings.",
318
+ );
319
+ return { revoked: confirmed };
320
+ }
321
+
322
+ /** Whether Wavie still has this computer's ChatGPT plan: false only when it said so. */
323
+ export async function wavieHasChatgpt({ link, fetch = globalThis.fetch }) {
324
+ const res = await fetch(deviceChatgpt(link), { headers: wavieHeaders(link), signal: AbortSignal.timeout(15_000) }).catch(
325
+ () => null,
326
+ );
327
+ if (!res?.ok) return null;
328
+ const body = await res.json().catch(() => null);
329
+ return typeof body?.connected === 'boolean' ? body.connected : null;
330
+ }
package/src/host.mjs CHANGED
@@ -1,14 +1,18 @@
1
+ import { chatgptHere } from './chatgpt-relay.mjs';
1
2
  import { findClaude, runTurn, stopAll, turnOf } from './claude.mjs';
2
3
  import { CLIENT_HEADER, routesOf, updateLine } from './wavie.mjs';
3
4
 
4
5
  /**
5
6
  * The service: waits on Wavie for turns on their Claude plan (`GET /device/asks`, a long poll, by this computer's key)
6
- * and runs each with Claude Code here (claude.mjs), a few at once; the rest wait their place. A key Wavie no longer
7
- * knows (they unlinked it in Wavie) ends it: `onUnlinked` takes heywavie off this computer.
7
+ * and runs each with Claude Code here (claude.mjs), a few at once; the rest wait their place. With ChatGPT signed in
8
+ * here it takes ChatGPT's calls too (chatgpt-relay.mjs). A key Wavie no longer knows (they unlinked it in Wavie) ends it:
9
+ * `onUnlinked` takes heywavie off this computer.
8
10
  */
9
11
 
10
12
  export const TURNS_MAX = 3;
11
13
  const WAIT_S = 20;
14
+ // How often the service asks Wavie whether ChatGPT is still connected (a disconnect on the web ends the sign-in here).
15
+ const CHATGPT_CHECK_MS = 5 * 60_000;
12
16
 
13
17
  const PLATFORM = { darwin: 'darwin', linux: 'linux', win32: 'win32' }[process.platform] ?? 'linux';
14
18
  const sleep = (ms, signal) =>
@@ -65,6 +69,9 @@ export async function host({
65
69
  platform = PLATFORM,
66
70
  waitS = WAIT_S,
67
71
  tooOldMs = 30 * 60_000,
72
+ home = null,
73
+ chatgpt = home ? chatgptHere({ home, link, fetch, log }) : null,
74
+ chatgptCheckMs = CHATGPT_CHECK_MS,
68
75
  }) {
69
76
  const { api, device, key } = link;
70
77
  const headers = { authorization: `Bearer ${key}`, 'content-type': 'application/json', ...CLIENT_HEADER };
@@ -109,11 +116,27 @@ export async function host({
109
116
  return answer(ask.id, { answer: { started: true } });
110
117
  };
111
118
 
119
+ // ChatGPT's calls, relayed: not Claude Code's turns, so they take no place of theirs.
120
+ const relay = (ask) => {
121
+ const t = Promise.resolve(chatgpt.relay(ask, answer))
122
+ .catch((err) => log(`ChatGPT call broke: ${err?.message ?? err}`))
123
+ .finally(() => turns.delete(t));
124
+ turns.add(t);
125
+ };
126
+ let checkedAt = -Infinity;
127
+ // Linked again since ChatGPT signed in here: Wavie hears it by this key before the first wait.
128
+ await chatgpt?.announce?.().catch((err) => log(`ChatGPT couldn't be connected again: ${err?.message ?? err}`));
129
+
112
130
  log(`waiting for Wavie's turns at ${api}`);
113
131
  while (!signal?.aborted) {
132
+ if (chatgpt && Date.now() - checkedAt >= chatgptCheckMs) {
133
+ checkedAt = Date.now();
134
+ await chatgpt.check().catch(() => {});
135
+ }
114
136
  let res;
115
137
  try {
116
- const q = new URLSearchParams({ device, platform, can: 'claude', wait: String(waitS) });
138
+ const can = chatgpt?.signedIn() ? 'claude,chatgpt' : 'claude';
139
+ const q = new URLSearchParams({ device, platform, can, wait: String(waitS) });
117
140
  res = await fetch(`${routesOf(api)}/device/asks?${q}`, {
118
141
  headers,
119
142
  signal: AbortSignal.any([AbortSignal.timeout((waitS + 30) * 1000), ...(signal ? [signal] : [])]),
@@ -128,6 +151,7 @@ export async function host({
128
151
  if (res.status === 401) {
129
152
  log('Wavie no longer knows this computer: it was unlinked in Wavie. Taking heywavie off it.');
130
153
  stopAll();
154
+ chatgpt?.stopAll();
131
155
  await Promise.allSettled([...turns]);
132
156
  await onUnlinked();
133
157
  return 'unlinked';
@@ -147,9 +171,13 @@ export async function host({
147
171
  backoff = 1000;
148
172
  const { asks = [] } = await bodyOf(res, signal);
149
173
  if (signal?.aborted) break;
150
- for (const ask of asks) if (ask?.ability === 'claude') await start(ask);
174
+ for (const ask of asks) {
175
+ if (ask?.ability === 'claude') await start(ask);
176
+ else if (ask?.ability === 'chatgpt' && chatgpt) relay(ask);
177
+ }
151
178
  }
152
179
  stopAll();
180
+ chatgpt?.stopAll();
153
181
  await Promise.allSettled([...turns]);
154
182
  return 'stopped';
155
183
  }
package/src/link.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import os from 'node:os';
3
+ import { chatgptOff } from './chatgpt.mjs';
4
+ import { readTokens } from './chatgpt-tokens.mjs';
3
5
  import { claudeStatus, findClaude } from './claude.mjs';
4
6
  import { canWrite, forget, newDevice, readLink, writeLink } from './home.mjs';
5
7
  import { install, serviceState, uninstall } from './service.mjs';
@@ -130,6 +132,8 @@ export async function link({
130
132
  /** This computer unlinked: Wavie told (when it still knows it), the service gone, heywavie's folder gone. */
131
133
  export async function disconnect({ home, fetch = globalThis.fetch, log = console.log, remover = uninstall }) {
132
134
  const was = readLink(home);
135
+ // Their ChatGPT sign-in here ends at OpenAI too, before its tokens go with the folder.
136
+ if (readTokens(home)) await chatgptOff({ home, fetch, log: () => {} });
133
137
  if (was) {
134
138
  await fetch(`${routesOf(was.api)}/plans/claude/host`, {
135
139
  method: 'DELETE',