@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/src/link.mjs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
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';
|
|
8
|
+
import { CLIENT_HEADER, routesOf, updateLine } from './wavie.mjs';
|
|
6
9
|
|
|
7
10
|
/**
|
|
8
11
|
* Linking this computer to their Wavie, from the one-time address Wavie gave them (`<api>/claude/setup#token=…`), and
|
|
@@ -24,10 +27,13 @@ export function parseLinkUrl(raw) {
|
|
|
24
27
|
} catch {
|
|
25
28
|
throw new Stop('The URL is not a Wavie link: pass the address from the sentence, in double quotes.');
|
|
26
29
|
}
|
|
27
|
-
if (url.pathname.replace(/\/+$/, '') !== '/claude/setup')
|
|
30
|
+
if (url.pathname.replace(/\/+$/, '') !== '/claude/setup')
|
|
31
|
+
throw new Stop('The URL is not a Wavie link: its path must be /claude/setup.');
|
|
28
32
|
const token = new URLSearchParams(url.hash.replace(/^#/, '')).get('token');
|
|
29
|
-
if (!token || !/^[A-Za-z0-9_-]{20,100}$/.test(token))
|
|
30
|
-
|
|
33
|
+
if (!token || !/^[A-Za-z0-9_-]{20,100}$/.test(token))
|
|
34
|
+
throw new Stop('The Wavie link has no credential: keep #token=… inside the double quotes.');
|
|
35
|
+
if (url.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(url.hostname))
|
|
36
|
+
throw new Stop('The Wavie link must be https.');
|
|
31
37
|
return { api: url.origin, token };
|
|
32
38
|
}
|
|
33
39
|
|
|
@@ -39,7 +45,9 @@ export function computerName({ platform = process.platform, run = execFileSync,
|
|
|
39
45
|
try {
|
|
40
46
|
const name = String(run('scutil', ['--get', 'ComputerName'], { encoding: 'utf8', timeout: 5000 })).trim();
|
|
41
47
|
if (name) return name;
|
|
42
|
-
} catch {
|
|
48
|
+
} catch {
|
|
49
|
+
/* the host name below */
|
|
50
|
+
}
|
|
43
51
|
}
|
|
44
52
|
return host.replace(/\.local$/, '');
|
|
45
53
|
}
|
|
@@ -49,33 +57,65 @@ export function computerName({ platform = process.platform, run = execFileSync,
|
|
|
49
57
|
* (it works once: nothing that can fail locally comes after it but the service), the service installed and started.
|
|
50
58
|
* Resolves `{ service: reason }` when the service couldn't be installed.
|
|
51
59
|
*/
|
|
52
|
-
export async function link({
|
|
53
|
-
|
|
60
|
+
export async function link({
|
|
61
|
+
url,
|
|
62
|
+
home,
|
|
63
|
+
fetch = globalThis.fetch,
|
|
64
|
+
log = console.log,
|
|
65
|
+
status = claudeStatus,
|
|
66
|
+
find = findClaude,
|
|
67
|
+
installer = install,
|
|
68
|
+
platform = PLATFORM,
|
|
69
|
+
name = computerName(),
|
|
70
|
+
}) {
|
|
54
71
|
const { api, token } = parseLinkUrl(url);
|
|
55
72
|
const before = readLink(home);
|
|
56
|
-
if (before && before.api !== api)
|
|
73
|
+
if (before && before.api !== api)
|
|
74
|
+
throw new Stop(
|
|
75
|
+
`This computer is already connected to a different Wavie (${before.api}). Run heywavie disconnect first.`,
|
|
76
|
+
);
|
|
57
77
|
|
|
58
78
|
log('Checking Claude Code on this computer...');
|
|
59
79
|
const bin = find();
|
|
60
|
-
if (!bin)
|
|
80
|
+
if (!bin)
|
|
81
|
+
throw new Stop(
|
|
82
|
+
"Claude Code is not installed in this environment. Install it (https://claude.com/claude-code), sign in with 'claude auth login', then run this again.",
|
|
83
|
+
);
|
|
61
84
|
const who = await status(bin);
|
|
62
|
-
if (!who.found)
|
|
63
|
-
|
|
85
|
+
if (!who.found)
|
|
86
|
+
throw new Stop(`Claude Code is installed but could not be run (${bin}). Reinstall it, then run this again.`);
|
|
87
|
+
if (!who.loggedIn)
|
|
88
|
+
throw new Stop(
|
|
89
|
+
"Claude Code is not signed in. Run 'claude auth login' in an interactive terminal, then run this again.",
|
|
90
|
+
);
|
|
64
91
|
|
|
65
92
|
const unwritable = canWrite(home);
|
|
66
|
-
if (unwritable)
|
|
93
|
+
if (unwritable)
|
|
94
|
+
throw new Stop(
|
|
95
|
+
`heywavie can't write its folder ${home} (${unwritable}). Approve writing there, then run this again: the link wasn't used.`,
|
|
96
|
+
);
|
|
67
97
|
|
|
68
98
|
const device = before?.device ?? newDevice();
|
|
69
99
|
let res;
|
|
70
100
|
try {
|
|
71
|
-
res = await fetch(`${api}/plans/claude/hosts`, {
|
|
72
|
-
|
|
101
|
+
res = await fetch(`${routesOf(api)}/plans/claude/hosts`, {
|
|
102
|
+
method: 'POST',
|
|
103
|
+
headers: { 'content-type': 'application/json', ...CLIENT_HEADER },
|
|
104
|
+
body: JSON.stringify({ token, device, platform, name: name.slice(0, 80), email: who.email, kind: who.kind }),
|
|
105
|
+
signal: AbortSignal.timeout(30_000),
|
|
106
|
+
});
|
|
73
107
|
} catch (err) {
|
|
74
|
-
throw new Stop(
|
|
108
|
+
throw new Stop(
|
|
109
|
+
`Failed to reach Wavie at ${api} (${err?.cause?.code ?? err?.message ?? err}). Check this computer's network, then run this again.`,
|
|
110
|
+
);
|
|
75
111
|
}
|
|
76
112
|
const body = await res.json().catch(() => ({}));
|
|
77
113
|
if (!res.ok) {
|
|
78
|
-
if (
|
|
114
|
+
if (res.status === 426) throw new Stop(updateLine(body));
|
|
115
|
+
if (body?.code === 'BAD_LINK')
|
|
116
|
+
throw new Stop(
|
|
117
|
+
'The link is expired, already used, or invalid. Get a new sentence from Wavie (Thinks with, Claude).',
|
|
118
|
+
);
|
|
79
119
|
throw new Stop(`Wavie refused the link (${res.status}${body?.message ? `: ${body.message}` : ''}).`);
|
|
80
120
|
}
|
|
81
121
|
writeLink(home, { api, device, key: body.key, claude: bin, name, linkedAt: new Date().toISOString() });
|
|
@@ -83,15 +123,23 @@ export async function link({ url, home, fetch = globalThis.fetch, log = console.
|
|
|
83
123
|
const service = await installer({ home });
|
|
84
124
|
log(`Claude on this computer is connected to Wavie${who.email ? ` (Claude Code signed in as ${who.email})` : ''}.`);
|
|
85
125
|
if (!service.ok) return { service: service.reason };
|
|
86
|
-
log(
|
|
126
|
+
log(
|
|
127
|
+
'The heywavie service is installed and running. It keeps going after this terminal closes; the computer must stay on and awake for Wavie to use it.',
|
|
128
|
+
);
|
|
87
129
|
return { service: null };
|
|
88
130
|
}
|
|
89
131
|
|
|
90
132
|
/** This computer unlinked: Wavie told (when it still knows it), the service gone, heywavie's folder gone. */
|
|
91
133
|
export async function disconnect({ home, fetch = globalThis.fetch, log = console.log, remover = uninstall }) {
|
|
92
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: () => {} });
|
|
93
137
|
if (was) {
|
|
94
|
-
await fetch(`${was.api}/plans/claude/host`, {
|
|
138
|
+
await fetch(`${routesOf(was.api)}/plans/claude/host`, {
|
|
139
|
+
method: 'DELETE',
|
|
140
|
+
headers: { authorization: `Bearer ${was.key}`, ...CLIENT_HEADER },
|
|
141
|
+
signal: AbortSignal.timeout(15_000),
|
|
142
|
+
}).catch(() => null);
|
|
95
143
|
}
|
|
96
144
|
await remover({ home, fromService: false });
|
|
97
145
|
forget(home);
|
|
@@ -99,15 +147,39 @@ export async function disconnect({ home, fetch = globalThis.fetch, log = console
|
|
|
99
147
|
}
|
|
100
148
|
|
|
101
149
|
/** How heywavie stands here: linked to what, the service, Claude Code, and whether Wavie still knows this computer. */
|
|
102
|
-
export async function status({
|
|
150
|
+
export async function status({
|
|
151
|
+
home,
|
|
152
|
+
fetch = globalThis.fetch,
|
|
153
|
+
state = serviceState,
|
|
154
|
+
find = findClaude,
|
|
155
|
+
who = claudeStatus,
|
|
156
|
+
}) {
|
|
103
157
|
const l = readLink(home);
|
|
104
158
|
const service = await state({ home });
|
|
105
159
|
const bin = find({ saved: l?.claude ?? null });
|
|
106
160
|
const claude = await who(bin);
|
|
107
161
|
let wavie = null;
|
|
108
162
|
if (l) {
|
|
109
|
-
const res = await fetch(`${l.api}/plans/claude/host`, {
|
|
110
|
-
|
|
163
|
+
const res = await fetch(`${routesOf(l.api)}/plans/claude/host`, {
|
|
164
|
+
headers: { authorization: `Bearer ${l.key}`, ...CLIENT_HEADER },
|
|
165
|
+
signal: AbortSignal.timeout(15_000),
|
|
166
|
+
}).catch(() => null);
|
|
167
|
+
wavie = !res
|
|
168
|
+
? 'unreachable'
|
|
169
|
+
: res.status === 401
|
|
170
|
+
? 'unlinked'
|
|
171
|
+
: res.status === 426
|
|
172
|
+
? updateLine(await res.json().catch(() => null))
|
|
173
|
+
: res.ok
|
|
174
|
+
? 'linked'
|
|
175
|
+
: `answered ${res.status}`;
|
|
111
176
|
}
|
|
112
|
-
return {
|
|
177
|
+
return {
|
|
178
|
+
linked: Boolean(l),
|
|
179
|
+
api: l?.api ?? null,
|
|
180
|
+
device: l?.device ?? null,
|
|
181
|
+
service,
|
|
182
|
+
claude: { bin, ...claude },
|
|
183
|
+
wavie,
|
|
184
|
+
};
|
|
113
185
|
}
|
package/src/service.mjs
CHANGED
|
@@ -20,16 +20,28 @@ const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
|
|
|
20
20
|
const PACKAGE = fileURLToPath(new URL('..', import.meta.url));
|
|
21
21
|
|
|
22
22
|
const run = promisify(execFile);
|
|
23
|
-
const quiet = (p) =>
|
|
23
|
+
const quiet = (p) =>
|
|
24
|
+
p.then(
|
|
25
|
+
() => true,
|
|
26
|
+
() => false,
|
|
27
|
+
);
|
|
24
28
|
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
25
29
|
|
|
26
30
|
/** What starts the service: this Node, heywavie's copy of this package, `run`. */
|
|
27
|
-
export const commandOf = ({ home, node = process.execPath }) => [
|
|
31
|
+
export const commandOf = ({ home, node = process.execPath }) => [
|
|
32
|
+
node,
|
|
33
|
+
path.join(home, 'app', 'bin', 'heywavie.mjs'),
|
|
34
|
+
'run',
|
|
35
|
+
];
|
|
28
36
|
|
|
29
37
|
/** The launchd agent's plist. */
|
|
30
38
|
export function plistOf({ home, node = process.execPath, env = {} }) {
|
|
31
|
-
const args = commandOf({ home, node })
|
|
32
|
-
|
|
39
|
+
const args = commandOf({ home, node })
|
|
40
|
+
.map((a) => ` <string>${xml(a)}</string>`)
|
|
41
|
+
.join('\n');
|
|
42
|
+
const vars = Object.entries({ HEYWAVIE_HOME: home, ...env })
|
|
43
|
+
.map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}</string>`)
|
|
44
|
+
.join('\n');
|
|
33
45
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
34
46
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
35
47
|
<plist version="1.0">
|
|
@@ -57,7 +69,9 @@ ${vars}
|
|
|
57
69
|
/** The systemd user unit. */
|
|
58
70
|
export function unitOf({ home, node = process.execPath, env = {} }) {
|
|
59
71
|
const quote = (a) => `"${String(a).replace(/(["\\])/g, '\\$1')}"`;
|
|
60
|
-
const vars = Object.entries({ HEYWAVIE_HOME: home, ...env })
|
|
72
|
+
const vars = Object.entries({ HEYWAVIE_HOME: home, ...env })
|
|
73
|
+
.map(([k, v]) => `Environment=${quote(`${k}=${v}`)}`)
|
|
74
|
+
.join('\n');
|
|
61
75
|
return `[Unit]
|
|
62
76
|
Description=heywavie: Claude on this computer for Wavie
|
|
63
77
|
|
|
@@ -73,10 +87,14 @@ WantedBy=default.target
|
|
|
73
87
|
}
|
|
74
88
|
|
|
75
89
|
/** The Windows Run entry's command line. */
|
|
76
|
-
export const runEntryOf = ({ home, node = process.execPath }) =>
|
|
90
|
+
export const runEntryOf = ({ home, node = process.execPath }) =>
|
|
91
|
+
commandOf({ home, node })
|
|
92
|
+
.map((a, i) => (i < 2 ? `"${a}"` : a))
|
|
93
|
+
.join(' ');
|
|
77
94
|
|
|
78
95
|
const plistPath = () => path.join(os.homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
|
|
79
|
-
const unitPath = () =>
|
|
96
|
+
const unitPath = () =>
|
|
97
|
+
path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'systemd', 'user', UNIT);
|
|
80
98
|
const domain = () => `gui/${process.getuid()}`;
|
|
81
99
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
82
100
|
|
|
@@ -104,21 +122,31 @@ function copyApp(home) {
|
|
|
104
122
|
const app = path.join(home, 'app');
|
|
105
123
|
rmSync(app, { recursive: true, force: true });
|
|
106
124
|
mkdirSync(app, { recursive: true });
|
|
107
|
-
for (const part of ['bin', 'src', 'package.json'])
|
|
125
|
+
for (const part of ['bin', 'src', 'package.json'])
|
|
126
|
+
cpSync(path.join(PACKAGE, part), path.join(app, part), { recursive: true });
|
|
108
127
|
}
|
|
109
128
|
|
|
110
129
|
/** The service on Windows, started now, apart from this process, with no window; its output to its log. */
|
|
111
130
|
function startDetached(home) {
|
|
112
131
|
const [node, ...args] = commandOf({ home });
|
|
113
132
|
const log = openSync(path.join(home, 'host.log'), 'a');
|
|
114
|
-
spawn(node, args, {
|
|
133
|
+
spawn(node, args, {
|
|
134
|
+
detached: true,
|
|
135
|
+
windowsHide: true,
|
|
136
|
+
stdio: ['ignore', log, log],
|
|
137
|
+
env: { ...process.env, HEYWAVIE_HOME: home },
|
|
138
|
+
}).unref();
|
|
115
139
|
}
|
|
116
140
|
|
|
117
141
|
/** The service's own process stopped, where only its pid file knows it. */
|
|
118
142
|
function stopByPid(home) {
|
|
119
143
|
const pid = readPid(home);
|
|
120
144
|
if (pid && pid !== process.pid && alive(pid)) {
|
|
121
|
-
try {
|
|
145
|
+
try {
|
|
146
|
+
process.kill(pid);
|
|
147
|
+
} catch {
|
|
148
|
+
/* gone already */
|
|
149
|
+
}
|
|
122
150
|
}
|
|
123
151
|
}
|
|
124
152
|
|
|
@@ -149,7 +177,12 @@ export async function install({ home, platform = process.platform, exec = run, e
|
|
|
149
177
|
}
|
|
150
178
|
return { ok: true };
|
|
151
179
|
} catch (err) {
|
|
152
|
-
const said =
|
|
180
|
+
const said =
|
|
181
|
+
String(err?.stderr || err?.message || err)
|
|
182
|
+
.trim()
|
|
183
|
+
.split('\n')
|
|
184
|
+
.filter(Boolean)
|
|
185
|
+
.at(-1) ?? 'it failed';
|
|
153
186
|
return { ok: false, reason: said.slice(0, 300) };
|
|
154
187
|
}
|
|
155
188
|
}
|
|
@@ -158,7 +191,10 @@ export async function install({ home, platform = process.platform, exec = run, e
|
|
|
158
191
|
export async function serviceState({ home, platform = process.platform, exec = run } = {}) {
|
|
159
192
|
if (platform === 'darwin') {
|
|
160
193
|
if (!existsSync(plistPath())) return { installed: false, running: false };
|
|
161
|
-
const out = await exec('launchctl', ['print', `${domain()}/${LABEL}`]).then(
|
|
194
|
+
const out = await exec('launchctl', ['print', `${domain()}/${LABEL}`]).then(
|
|
195
|
+
(r) => r.stdout,
|
|
196
|
+
() => '',
|
|
197
|
+
);
|
|
162
198
|
return { installed: true, running: /state = running/.test(out) };
|
|
163
199
|
}
|
|
164
200
|
if (platform === 'linux') {
|
|
@@ -166,7 +202,10 @@ export async function serviceState({ home, platform = process.platform, exec = r
|
|
|
166
202
|
return { installed: true, running: await quiet(exec('systemctl', ['--user', 'is-active', '--quiet', UNIT])) };
|
|
167
203
|
}
|
|
168
204
|
if (platform === 'win32') {
|
|
169
|
-
return {
|
|
205
|
+
return {
|
|
206
|
+
installed: await quiet(exec('reg', ['query', RUN_KEY, '/v', 'heywavie'])),
|
|
207
|
+
running: Boolean(home) && alive(readPid(home)),
|
|
208
|
+
};
|
|
170
209
|
}
|
|
171
210
|
return { installed: false, running: false };
|
|
172
211
|
}
|
package/src/wavie.mjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
4
|
+
|
|
5
|
+
/** This copy's version. */
|
|
6
|
+
export const VERSION = pkg.version;
|
|
7
|
+
|
|
8
|
+
/** Sent on every call to Wavie: the server refuses a copy older than it takes (426 UPDATE_NEEDED). */
|
|
9
|
+
export const CLIENT_HEADER = Object.freeze({ 'x-wavie-client': `cli/${VERSION}` });
|
|
10
|
+
|
|
11
|
+
/** Wavie's app routes on the server a link names (its origin), under the API's version. */
|
|
12
|
+
export const routesOf = (api) => `${api}/v1`;
|
|
13
|
+
|
|
14
|
+
/** Wavie answered 426: what this copy is, the version Wavie names, and how to get it. */
|
|
15
|
+
export const updateLine = (body) =>
|
|
16
|
+
`This heywavie (${VERSION}) is too old for Wavie${body?.minVersion ? `, which needs ${body.minVersion} or later` : ''}. ` +
|
|
17
|
+
`Update it with "npm i -g ${pkg.name}@latest", then connect this computer again from Wavie (Thinks with, Claude).`;
|