@heywavie/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,47 @@
1
- # Temporary Holding Version
1
+ # heywavie CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
5
+
6
+ ## How it links
7
+
8
+ 1. Thinks with → Claude, in Wavie (web, Mac app or iPhone), shows one sentence: "Connect this computer to my Wavie so my
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/claude-setup.mjs`) and runs
11
+ `npx --yes @heywavie/cli@<version> link --url "<that address>" --yes` itself.
12
+ 3. `link` checks Claude Code (found, signed in), trades the token for this computer's own key
13
+ (`POST /plans/claude/hosts`), keeps it in `~/.heywavie/link.json` (mode 600), copies itself to `~/.heywavie/app` and
14
+ installs the background service: a launchd agent on a Mac (`com.heywavie.host`), a systemd user service on Linux
15
+ (`heywavie.service`, with lingering asked for so it outlives signing out), an entry in the user's own Run key on
16
+ Windows (`heywavie`, started now detached; a logon task would need an administrator). A computer that won't take a
17
+ service exits 2 with the reason; the setup page has Claude Code start `heywavie run` as a background process.
18
+
19
+ The token works once, for 30 minutes, and rides after `#`, so fetching the page never sends it.
20
+
21
+ ## What the service does
22
+
23
+ `heywavie run` waits on `GET /device/asks` by the computer's key, as its own device, for `claude` asks only, and runs
24
+ each turn with Claude Code here (`src/claude.mjs`), three at once: model only, Claude Code's own tools off (no shell, no
25
+ files, no web), none of the person's settings, hooks or plugins, an empty folder of its own, and only Wavie's tools,
26
+ reached over MCP by the turn's own token. What Claude Code says goes back to the server as it says it. The key reaches
27
+ its turns and `/plans/claude/host`, nothing else of their account; Claude's sign-in stays in Claude Code.
28
+
29
+ Disconnect in Wavie drops every computer's key: the service hears 401 on its next wait and takes itself off (service
30
+ and `~/.heywavie` gone), unless the computer was linked again since (a new key on disk), when it only exits.
31
+ `heywavie disconnect` does the same from the computer. A service with nothing linked takes itself off too; it restarts
32
+ after a crash, never after a clean exit.
33
+
34
+ ```bash
35
+ npm test # the runner, linking, the service files, the wait loop
36
+ node bin/heywavie.mjs status # linked to what, the service, Claude Code
37
+ node bin/heywavie.mjs disconnect
38
+ ```
39
+
40
+ `HEYWAVIE_HOME` points it at another folder, `HEYWAVIE_CLAUDE_BIN` at another Claude Code. On a dev server
41
+ (`cd server && npm run demo`) the setup page runs this checkout's `bin/heywavie.mjs` against `http://localhost:8787`
42
+ (`PLAN_CLI` and `WAVIE_API_URL` change either). The service's log is `~/.heywavie/host.log`.
43
+
44
+ ## Publishing
45
+
46
+ Raise `version` here and `CLI_VERSION` in `server/src/plans.mjs` together (a server test checks), then `npm publish`
47
+ 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.
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { forget, homeOf, pidPath, readLink } from '../src/home.mjs';
4
+ import { host } from '../src/host.mjs';
5
+ import { disconnect, link, status, Stop } from '../src/link.mjs';
6
+ import { uninstall } from '../src/service.mjs';
7
+
8
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
9
+ const HELP = `heywavie ${VERSION}: Claude on this computer, for Wavie
10
+
11
+ heywavie link --url "<the address from Wavie's sentence>" [--yes]
12
+ heywavie status [--json]
13
+ heywavie disconnect [--yes]
14
+ heywavie run the service itself (started for you)
15
+ `;
16
+
17
+ const [verb, ...rest] = process.argv.slice(2);
18
+ const flag = (name) => rest.includes(`--${name}`);
19
+ const value = (name) => {
20
+ const i = rest.indexOf(`--${name}`);
21
+ return i >= 0 ? rest[i + 1] : undefined;
22
+ };
23
+ const home = homeOf();
24
+ const stamp = (line) => console.log(`${new Date().toISOString()} ${line}`);
25
+
26
+ /**
27
+ * The service: until Wavie forgets this computer or it is stopped. Wavie forgetting this process's key takes heywavie off
28
+ * the computer only while that key is still the one linked here: a relink since then (a new key) is left alone. With
29
+ * nothing linked it takes its own service off, rather than being started again and again.
30
+ */
31
+ async function serve(log) {
32
+ const l = readLink(home);
33
+ if (!l) {
34
+ log('Not linked to Wavie: taking the heywavie service off this computer.');
35
+ await uninstall({ home, fromService: true });
36
+ process.exit(0);
37
+ }
38
+ writeFileSync(pidPath(home), String(process.pid));
39
+ const stopper = new AbortController();
40
+ let leaving = false;
41
+ // Stopping its own service (the last step of leaving) signals this process: it is done by then.
42
+ for (const sig of ['SIGTERM', 'SIGINT']) process.on(sig, () => (leaving ? process.exit(0) : stopper.abort()));
43
+ const onUnlinked = async () => {
44
+ if (readLink(home)?.key !== l.key) return;
45
+ leaving = true;
46
+ forget(home);
47
+ await uninstall({ home, fromService: true });
48
+ };
49
+ await host({ link: l, signal: stopper.signal, log, onUnlinked });
50
+ process.exit(0);
51
+ }
52
+
53
+ try {
54
+ if (verb === 'link') {
55
+ const { service } = await link({ url: value('url'), home });
56
+ if (service) {
57
+ console.log(`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.`);
58
+ process.exitCode = 2;
59
+ }
60
+ } else if (verb === 'run') {
61
+ await serve(stamp);
62
+ } else if (verb === 'status') {
63
+ const s = await status({ home });
64
+ if (flag('json')) console.log(JSON.stringify(s, null, 2));
65
+ else {
66
+ console.log(s.linked ? `Linked to ${s.api} as ${s.device}; Wavie ${s.wavie === 'linked' ? 'knows this computer' : s.wavie}.` : 'Not linked to Wavie.');
67
+ console.log(`Service: ${s.service.installed ? (s.service.running ? 'installed and running' : 'installed, not running') : 'not installed'}.`);
68
+ console.log(`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})`}.`);
69
+ }
70
+ } else if (verb === 'disconnect') {
71
+ await disconnect({ home });
72
+ } else if (verb === '--version' || verb === '-v') {
73
+ console.log(VERSION);
74
+ } else {
75
+ console.log(HELP);
76
+ if (verb && verb !== 'help' && verb !== '--help') process.exitCode = 1;
77
+ }
78
+ } catch (err) {
79
+ console.error(err instanceof Stop ? err.message : `heywavie: ${err?.stack ?? err}`);
80
+ process.exitCode = err?.exitCode ?? 1;
81
+ }
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@heywavie/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Claude on your computer, for Wavie: your agents think with your own Claude plan",
5
+ "homepage": "https://heywavie.com",
6
+ "license": "UNLICENSED",
7
+ "type": "module",
8
+ "bin": {
9
+ "heywavie": "bin/heywavie.mjs"
10
+ },
11
+ "files": [
12
+ "bin",
13
+ "src"
14
+ ],
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "engines": {
19
+ "node": ">=20.3"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test test/*.test.mjs"
23
+ }
24
+ }
package/src/claude.mjs ADDED
@@ -0,0 +1,198 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ /**
8
+ * Wavie's turns on the person's own Claude plan, run on their computer by the Claude Code they signed in to there. Model
9
+ * only: Claude Code's own tools are off (no shell, no files, no web), none of their settings, hooks or plugins load, and
10
+ * it runs in an empty folder of its own. Wavie's tools reach it from heywavie over MCP, by the turn's own token. The
11
+ * server sends words and that token's two addresses, never a command: the command is this file's.
12
+ */
13
+
14
+ const WINDOWS = process.platform === 'win32';
15
+ const where = (home, windows) => (windows
16
+ ? [path.join(home, '.local', 'bin', 'claude.exe')]
17
+ : [path.join(home, '.local/bin/claude'), path.join(home, '.claude/local/claude'), '/opt/homebrew/bin/claude', '/usr/local/bin/claude', '/usr/bin/claude']);
18
+
19
+ /**
20
+ * Claude Code on this computer: `HEYWAVIE_CLAUDE_BIN`, else where it was when they linked (`saved`), else on the PATH
21
+ * (linking runs in Claude Code's own shell: an npm install under nvm is only found there), else where its installers put
22
+ * it (a background service has no shell PATH), or null. A Windows npm install (`claude.cmd`) isn't run: it needs a shell.
23
+ */
24
+ export function findClaude({ env = process.env, home = os.homedir(), exists = existsSync, saved = null, windows = WINDOWS } = {}) {
25
+ const set = env.HEYWAVIE_CLAUDE_BIN?.trim();
26
+ if (set) return exists(set) ? set : null;
27
+ if (saved && exists(saved)) return saved;
28
+ const onPath = String(env.PATH ?? '').split(windows ? ';' : ':').filter(Boolean).map((dir) => path.join(dir, windows ? 'claude.exe' : 'claude'));
29
+ return [...onPath, ...where(home, windows)].find((p) => exists(p)) ?? null;
30
+ }
31
+
32
+ const UNIX_PATH = ['/usr/bin', '/bin', '/usr/sbin', '/sbin'];
33
+ const WINDOWS_KEEP = ['USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'SystemRoot', 'SystemDrive', 'ComSpec', 'PATHEXT'];
34
+
35
+ /**
36
+ * All Claude Code gets of the service's surroundings: who they are (its sign-in is in their Keychain on a Mac, in its own
37
+ * folder elsewhere), and its own folder on the PATH (an npm install of it is a script that needs the Node beside it).
38
+ */
39
+ export function claudeEnv(env = process.env, home = os.homedir(), bin = null, { windows = WINDOWS, user = null } = {}) {
40
+ const who = env.USER || env.USERNAME || user || '';
41
+ const own = bin ? [path.dirname(bin)] : [];
42
+ const base = { HOME: home, LANG: env.LANG || 'en_US.UTF-8', TMPDIR: env.TMPDIR ?? os.tmpdir(), DISABLE_AUTOUPDATER: '1' };
43
+ if (windows) {
44
+ const kept = Object.fromEntries(WINDOWS_KEEP.filter((k) => env[k]).map((k) => [k, env[k]]));
45
+ const system = env.SystemRoot ? [path.join(env.SystemRoot, 'System32'), env.SystemRoot] : [];
46
+ return { ...base, ...kept, USERNAME: who, PATH: [...own, ...system].join(';') };
47
+ }
48
+ return { ...base, USER: who, LOGNAME: env.LOGNAME || who, PATH: [...own, ...UNIX_PATH].join(':') };
49
+ }
50
+
51
+ /** The one command a turn runs: model only, Wavie's tools at `tools` its only ones. */
52
+ export function claudeArgs({ systemFile, tools, maxSteps }) {
53
+ const mcp = { mcpServers: { wavie: { type: 'http', url: tools } } };
54
+ return ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--input-format', 'text',
55
+ '--system-prompt-file', systemFile, '--tools', '', '--strict-mcp-config', '--mcp-config', JSON.stringify(mcp),
56
+ '--allowedTools', 'mcp__wavie', '--permission-prompts', 'none', '--no-session-persistence', '--disable-slash-commands',
57
+ // No --safe-mode: it turns off MCP servers too, Wavie's with them. Their CLAUDE.md stays out without it.
58
+ '--setting-sources', '', '--max-turns', String(maxSteps)];
59
+ }
60
+
61
+ const TURN_PATH = /^\/plan-turns\/([A-Za-z0-9_-]{32})\/(tools|events)$/;
62
+
63
+ /** A turn as the server asked for it, checked: its two addresses on Wavie's own API (`api`), its words, its steps. */
64
+ export function turnOf(input, api) {
65
+ const tools = TURN_PATH.exec(String(input?.tools ?? ''));
66
+ const events = TURN_PATH.exec(String(input?.events ?? ''));
67
+ if (!tools || !events || tools[2] !== 'tools' || events[2] !== 'events' || tools[1] !== events[1]) throw new Error('Not a turn of Wavie\'s.');
68
+ if (typeof input.system !== 'string' || typeof input.prompt !== 'string' || !input.prompt.trim()) throw new Error('A turn with nothing to answer.');
69
+ const steps = Number.isInteger(input.maxSteps) && input.maxSteps >= 1 && input.maxSteps <= 60 ? input.maxSteps : 24;
70
+ return { tools: `${api}${tools[0]}`, events: `${api}${events[0]}`, system: input.system, prompt: input.prompt, maxSteps: steps };
71
+ }
72
+
73
+ /** Who Claude Code on this computer is signed in as: `{ found, loggedIn, email, kind }`. */
74
+ export function claudeStatus(bin, { env = process.env, home = os.homedir() } = {}) {
75
+ if (!bin) return Promise.resolve({ found: false, loggedIn: false, email: null, kind: null });
76
+ return new Promise((resolve) => {
77
+ const child = spawn(bin, ['auth', 'status'], { env: claudeEnv(env, home, bin, { user: os.userInfo().username }), cwd: os.tmpdir(), stdio: ['ignore', 'pipe', 'ignore'] });
78
+ let out = '';
79
+ const timer = setTimeout(() => child.kill('SIGKILL'), 20_000);
80
+ child.stdout.on('data', (d) => { out += d; });
81
+ let settled = false;
82
+ const done = () => {
83
+ if (settled) return;
84
+ settled = true;
85
+ clearTimeout(timer);
86
+ let st = null;
87
+ try { st = JSON.parse(out.slice(out.indexOf('{'))); } catch { st = null; }
88
+ const kind = st?.subscriptionType ?? st?.account?.subscriptionType ?? null;
89
+ resolve({ found: true, loggedIn: st?.loggedIn === true, email: st?.email ?? st?.account?.email ?? null, kind: kind ? String(kind) : null });
90
+ };
91
+ child.on('error', done);
92
+ child.on('close', done);
93
+ });
94
+ }
95
+
96
+ // Claude Code running a turn now, to stop when the service stops.
97
+ const children = new Set();
98
+
99
+ /** Every turn running here stopped: the service is stopping. */
100
+ export function stopAll() {
101
+ for (const child of children) child.kill('SIGTERM');
102
+ }
103
+
104
+ const BATCH_LINES = 500;
105
+
106
+ /**
107
+ * Runs one turn: Claude Code reads the chat on its input and streams stream-json, which goes to the turn's `events`
108
+ * address in order, in numbered batches (one sent again is read once), with an empty one now and then so the server knows
109
+ * the computer is still there. The answer to each says whether to stop: a card or a started task ends the turn on the
110
+ * server's side. `ready` holds the turn while this computer is busy with others (it still says it's there). Resolves once Claude Code
111
+ * is done and the server was told how it ended.
112
+ */
113
+ export async function runTurn({ bin, turn, fetch = globalThis.fetch, env = process.env, home = os.homedir(), ready = null, flushMs = 150, beatMs = 10_000,
114
+ maxMs = 20 * 60_000, timeoutMs = 20_000 }) {
115
+ let child = null;
116
+ let stopping = false;
117
+ const stop = () => {
118
+ stopping = true;
119
+ if (!child) return;
120
+ child.kill('SIGTERM');
121
+ setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 5000).unref?.();
122
+ };
123
+ const send = async (body) => {
124
+ try {
125
+ const res = await fetch(turn.events, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) });
126
+ if (res.status === 404) { stop(); return true; }
127
+ if (!res.ok) return false;
128
+ if ((await res.json().catch(() => ({}))).stop) stop();
129
+ return true;
130
+ } catch {
131
+ return false;
132
+ }
133
+ };
134
+ // Lines not yet in a batch, and batches not yet through: one request at a time, in order, each the same when sent again.
135
+ let pending = [];
136
+ const batches = [];
137
+ let n = 0;
138
+ let lastSent = 0;
139
+ let chain = Promise.resolve();
140
+ const flush = (force = false) => {
141
+ chain = chain.then(async () => {
142
+ while (pending.length) batches.push({ n: ++n, lines: pending.splice(0, BATCH_LINES) });
143
+ if (!batches.length) {
144
+ if (force || Date.now() - lastSent >= beatMs) { if (await send({ lines: [] })) lastSent = Date.now(); }
145
+ return;
146
+ }
147
+ while (batches.length) {
148
+ if (!(await send(batches[0]))) return;
149
+ batches.shift();
150
+ lastSent = Date.now();
151
+ }
152
+ });
153
+ return chain;
154
+ };
155
+
156
+ const timer = setInterval(() => void flush(), flushMs);
157
+ void flush(true);
158
+ if (ready) await ready;
159
+ if (stopping) {
160
+ clearInterval(timer);
161
+ await chain;
162
+ await send({ end: { code: -1, error: 'stopped before it started' } });
163
+ return -1;
164
+ }
165
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'wavie-claude-'));
166
+ const systemFile = path.join(dir, 'system.md');
167
+ await writeFile(systemFile, turn.system, { mode: 0o600 });
168
+ child = spawn(bin, claudeArgs({ systemFile, tools: turn.tools, maxSteps: turn.maxSteps }), { cwd: dir, env: claudeEnv(env, home, bin, { user: os.userInfo().username }),
169
+ stdio: ['pipe', 'pipe', 'pipe'] });
170
+ children.add(child);
171
+ const ceiling = setTimeout(stop, maxMs);
172
+ let buffer = '';
173
+ let errText = '';
174
+ child.stdout.on('data', (d) => {
175
+ buffer += d;
176
+ let nl;
177
+ while ((nl = buffer.indexOf('\n')) >= 0) {
178
+ const line = buffer.slice(0, nl).trim();
179
+ buffer = buffer.slice(nl + 1);
180
+ if (line) pending.push(line);
181
+ }
182
+ });
183
+ child.stderr.on('data', (d) => { errText = (errText + d).slice(-4000); });
184
+ child.stdin.on('error', () => {});
185
+ child.stdin.end(turn.prompt);
186
+ const code = await new Promise((resolve) => {
187
+ child.on('error', (err) => { errText = `${errText}\n${err?.message ?? err}`; resolve(-1); });
188
+ child.on('close', (c) => resolve(c ?? -1));
189
+ });
190
+ children.delete(child);
191
+ clearInterval(timer);
192
+ clearTimeout(ceiling);
193
+ if (buffer.trim()) pending.push(buffer.trim());
194
+ for (let i = 0; i < 4 && (pending.length || batches.length || i === 0); i++) await flush(true);
195
+ for (let i = 0; i < 3; i++) if (await send({ end: { code, error: errText } })) break;
196
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
197
+ return code;
198
+ }
package/src/home.mjs ADDED
@@ -0,0 +1,69 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ /**
7
+ * heywavie's own folder on this computer (`~/.heywavie`, `HEYWAVIE_HOME` in tests): the link (`link.json`: Wavie's API,
8
+ * this computer's id, its key, where Claude Code was), the service's copy of this package (`app/`), and its log. Readable
9
+ * by them only: the key is the computer's way in to their Wavie.
10
+ */
11
+ export const homeOf = (env = process.env) => env.HEYWAVIE_HOME?.trim() || path.join(os.homedir(), '.heywavie');
12
+
13
+ /** The link, or null on a computer never linked. */
14
+ export function readLink(home) {
15
+ try {
16
+ const link = JSON.parse(readFileSync(path.join(home, 'link.json'), 'utf8'));
17
+ return link?.api && link?.device && link?.key ? link : null;
18
+ } catch {
19
+ return null;
20
+ }
21
+ }
22
+
23
+ export function writeLink(home, link) {
24
+ mkdirSync(home, { recursive: true, mode: 0o700 });
25
+ const file = path.join(home, 'link.json');
26
+ writeFileSync(file, `${JSON.stringify(link, null, 2)}\n`, { mode: 0o600 });
27
+ chmodSync(file, 0o600);
28
+ }
29
+
30
+ /** Null when heywavie's folder can be made and written here, else why not. */
31
+ export function canWrite(home) {
32
+ try {
33
+ mkdirSync(home, { recursive: true, mode: 0o700 });
34
+ const probe = path.join(home, `.probe-${process.pid}`);
35
+ writeFileSync(probe, '', { mode: 0o600 });
36
+ rmSync(probe, { force: true });
37
+ return null;
38
+ } catch (err) {
39
+ return err?.code ?? String(err?.message ?? err);
40
+ }
41
+ }
42
+
43
+ /** The service's own process id, for `status` and for stopping it where the OS keeps no track (Windows). */
44
+ export const pidPath = (home) => path.join(home, 'host.pid');
45
+ export function readPid(home) {
46
+ try {
47
+ const pid = Number(readFileSync(pidPath(home), 'utf8').trim());
48
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+ export function alive(pid) {
54
+ if (!pid) return false;
55
+ try {
56
+ process.kill(pid, 0);
57
+ return true;
58
+ } catch (err) {
59
+ return err?.code === 'EPERM';
60
+ }
61
+ }
62
+
63
+ /** Everything heywavie keeps here, gone. */
64
+ export function forget(home) {
65
+ if (existsSync(home)) rmSync(home, { recursive: true, force: true });
66
+ }
67
+
68
+ /** This computer's own id with Wavie: kept across links, so linking again replaces it rather than adding one. */
69
+ export const newDevice = () => `h-${randomBytes(12).toString('base64url')}`;
package/src/host.mjs ADDED
@@ -0,0 +1,99 @@
1
+ import { findClaude, runTurn, stopAll, turnOf } from './claude.mjs';
2
+
3
+ /**
4
+ * The service: waits on Wavie for turns on their Claude plan (`GET /device/asks`, a long poll, by this computer's key)
5
+ * and runs each with Claude Code here (claude.mjs), a few at once; the rest wait their place. A key Wavie no longer
6
+ * knows (they unlinked it in Wavie) ends it: `onUnlinked` takes heywavie off this computer.
7
+ */
8
+
9
+ export const TURNS_MAX = 3;
10
+ const WAIT_S = 20;
11
+
12
+ const PLATFORM = { darwin: 'darwin', linux: 'linux', win32: 'win32' }[process.platform] ?? 'linux';
13
+ const sleep = (ms, signal) => new Promise((resolve) => {
14
+ const t = setTimeout(resolve, ms);
15
+ signal?.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
16
+ });
17
+
18
+ /** Turns running here at once, at most `max`: `place()` resolves when there is room, `free()` hands it on. */
19
+ export function places(max = TURNS_MAX) {
20
+ let busy = 0;
21
+ const waiting = [];
22
+ return {
23
+ place: () => (busy < max ? (busy++, Promise.resolve()) : new Promise((resolve) => waiting.push(resolve))),
24
+ free: () => {
25
+ const next = waiting.shift();
26
+ if (next) next();
27
+ else busy--;
28
+ },
29
+ };
30
+ }
31
+
32
+ /**
33
+ * Runs until `signal` aborts or Wavie no longer knows this key. `log` gets one line per thing worth knowing; nothing of
34
+ * a chat is ever in it.
35
+ */
36
+ export async function host({ link, fetch = globalThis.fetch, signal = null, log = console.log, onUnlinked = async () => {}, run = runTurn, find = findClaude,
37
+ platform = PLATFORM, waitS = WAIT_S }) {
38
+ const { api, device, key } = link;
39
+ const headers = { authorization: `Bearer ${key}`, 'content-type': 'application/json' };
40
+ const room = places();
41
+ const turns = new Set();
42
+ let backoff = 1000;
43
+ const answer = (id, body) => fetch(`${api}/device/asks/${id}`, { method: 'POST', headers, body: JSON.stringify({ device, ...body }), signal: AbortSignal.timeout(20_000) })
44
+ .catch(() => null);
45
+
46
+ const start = (ask) => {
47
+ const bin = find({ saved: link.claude ?? null });
48
+ if (!bin) {
49
+ log("Claude Code isn't on this computer any more: install it again and sign in (claude auth login).");
50
+ return answer(ask.id, { error: "Claude Code isn't on that computer any more. Install it again there and sign in (claude auth login), or pick heywavie under Thinks with." });
51
+ }
52
+ let turn;
53
+ try {
54
+ turn = turnOf(ask.input, api);
55
+ } catch (err) {
56
+ return answer(ask.id, { error: String(err?.message ?? err) });
57
+ }
58
+ const ready = room.place();
59
+ const t = run({ bin, turn, ready }).then((code) => log(`turn ended (${code})`), (err) => log(`turn broke: ${err?.message ?? err}`))
60
+ .finally(() => { void ready.then(room.free); turns.delete(t); });
61
+ turns.add(t);
62
+ log('turn started');
63
+ return answer(ask.id, { answer: { started: true } });
64
+ };
65
+
66
+ log(`waiting for Wavie's turns at ${api}`);
67
+ while (!signal?.aborted) {
68
+ let res;
69
+ try {
70
+ const q = new URLSearchParams({ device, platform, can: 'claude', wait: String(waitS) });
71
+ res = await fetch(`${api}/device/asks?${q}`, { headers, signal: AbortSignal.any([AbortSignal.timeout((waitS + 30) * 1000), ...(signal ? [signal] : [])]) });
72
+ } catch (err) {
73
+ if (signal?.aborted) break;
74
+ log(`can't reach Wavie (${err?.cause?.code ?? err?.message ?? err}), trying again`);
75
+ await sleep(backoff, signal);
76
+ backoff = Math.min(backoff * 2, 30_000);
77
+ continue;
78
+ }
79
+ if (res.status === 401) {
80
+ log('Wavie no longer knows this computer: it was unlinked in Wavie. Taking heywavie off it.');
81
+ stopAll();
82
+ await Promise.allSettled([...turns]);
83
+ await onUnlinked();
84
+ return 'unlinked';
85
+ }
86
+ if (!res.ok) {
87
+ log(`Wavie answered ${res.status}, trying again`);
88
+ await sleep(backoff, signal);
89
+ backoff = Math.min(backoff * 2, 30_000);
90
+ continue;
91
+ }
92
+ backoff = 1000;
93
+ const { asks = [] } = await res.json().catch(() => ({}));
94
+ for (const ask of asks) if (ask?.ability === 'claude') await start(ask);
95
+ }
96
+ stopAll();
97
+ await Promise.allSettled([...turns]);
98
+ return 'stopped';
99
+ }
package/src/link.mjs ADDED
@@ -0,0 +1,113 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import os from 'node:os';
3
+ import { claudeStatus, findClaude } from './claude.mjs';
4
+ import { canWrite, forget, newDevice, readLink, writeLink } from './home.mjs';
5
+ import { install, serviceState, uninstall } from './service.mjs';
6
+
7
+ /**
8
+ * Linking this computer to their Wavie, from the one-time address Wavie gave them (`<api>/claude/setup#token=…`), and
9
+ * unlinking it. What each says is for the Claude Code running it as much as for them: one plain line per outcome.
10
+ */
11
+
12
+ export class Stop extends Error {
13
+ constructor(message, code = 1) {
14
+ super(message);
15
+ this.exitCode = code;
16
+ }
17
+ }
18
+
19
+ /** Wavie's API and the one-time token, from the address in the sentence they pasted. */
20
+ export function parseLinkUrl(raw) {
21
+ let url;
22
+ try {
23
+ url = new URL(String(raw ?? ''));
24
+ } catch {
25
+ throw new Stop('The URL is not a Wavie link: pass the address from the sentence, in double quotes.');
26
+ }
27
+ if (url.pathname.replace(/\/+$/, '') !== '/claude/setup') throw new Stop('The URL is not a Wavie link: its path must be /claude/setup.');
28
+ const token = new URLSearchParams(url.hash.replace(/^#/, '')).get('token');
29
+ if (!token || !/^[A-Za-z0-9_-]{20,100}$/.test(token)) throw new Stop('The Wavie link has no credential: keep #token=… inside the double quotes.');
30
+ if (url.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(url.hostname)) throw new Stop('The Wavie link must be https.');
31
+ return { api: url.origin, token };
32
+ }
33
+
34
+ const PLATFORM = { darwin: 'darwin', linux: 'linux', win32: 'win32' }[process.platform] ?? 'linux';
35
+
36
+ /** This computer as they call it ("Hoan's MacBook Pro" on a Mac), for Wavie to say where Claude runs. */
37
+ export function computerName({ platform = process.platform, run = execFileSync, host = os.hostname() } = {}) {
38
+ if (platform === 'darwin') {
39
+ try {
40
+ const name = String(run('scutil', ['--get', 'ComputerName'], { encoding: 'utf8', timeout: 5000 })).trim();
41
+ if (name) return name;
42
+ } catch { /* the host name below */ }
43
+ }
44
+ return host.replace(/\.local$/, '');
45
+ }
46
+
47
+ /**
48
+ * Links this computer: Claude Code checked, heywavie's folder writable, the token traded for this computer's own key
49
+ * (it works once: nothing that can fail locally comes after it but the service), the service installed and started.
50
+ * Resolves `{ service: reason }` when the service couldn't be installed.
51
+ */
52
+ export async function link({ url, home, fetch = globalThis.fetch, log = console.log, status = claudeStatus, find = findClaude, installer = install, platform = PLATFORM,
53
+ name = computerName() }) {
54
+ const { api, token } = parseLinkUrl(url);
55
+ const before = readLink(home);
56
+ if (before && before.api !== api) throw new Stop(`This computer is already connected to a different Wavie (${before.api}). Run heywavie disconnect first.`);
57
+
58
+ log('Checking Claude Code on this computer...');
59
+ const bin = find();
60
+ if (!bin) throw new Stop("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.");
61
+ const who = await status(bin);
62
+ if (!who.found) throw new Stop(`Claude Code is installed but could not be run (${bin}). Reinstall it, then run this again.`);
63
+ if (!who.loggedIn) throw new Stop("Claude Code is not signed in. Run 'claude auth login' in an interactive terminal, then run this again.");
64
+
65
+ const unwritable = canWrite(home);
66
+ if (unwritable) throw new Stop(`heywavie can't write its folder ${home} (${unwritable}). Approve writing there, then run this again: the link wasn't used.`);
67
+
68
+ const device = before?.device ?? newDevice();
69
+ let res;
70
+ try {
71
+ res = await fetch(`${api}/plans/claude/hosts`, { method: 'POST', headers: { 'content-type': 'application/json' },
72
+ body: JSON.stringify({ token, device, platform, name: name.slice(0, 80), email: who.email, kind: who.kind }), signal: AbortSignal.timeout(30_000) });
73
+ } catch (err) {
74
+ throw new Stop(`Failed to reach Wavie at ${api} (${err?.cause?.code ?? err?.message ?? err}). Check this computer's network, then run this again.`);
75
+ }
76
+ const body = await res.json().catch(() => ({}));
77
+ if (!res.ok) {
78
+ if (body?.code === 'BAD_LINK') throw new Stop('The link is expired, already used, or invalid. Get a new sentence from Wavie (Thinks with, Claude).');
79
+ throw new Stop(`Wavie refused the link (${res.status}${body?.message ? `: ${body.message}` : ''}).`);
80
+ }
81
+ writeLink(home, { api, device, key: body.key, claude: bin, name, linkedAt: new Date().toISOString() });
82
+
83
+ const service = await installer({ home });
84
+ log(`Claude on this computer is connected to Wavie${who.email ? ` (Claude Code signed in as ${who.email})` : ''}.`);
85
+ if (!service.ok) return { service: service.reason };
86
+ log('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.');
87
+ return { service: null };
88
+ }
89
+
90
+ /** This computer unlinked: Wavie told (when it still knows it), the service gone, heywavie's folder gone. */
91
+ export async function disconnect({ home, fetch = globalThis.fetch, log = console.log, remover = uninstall }) {
92
+ const was = readLink(home);
93
+ if (was) {
94
+ await fetch(`${was.api}/plans/claude/host`, { method: 'DELETE', headers: { authorization: `Bearer ${was.key}` }, signal: AbortSignal.timeout(15_000) }).catch(() => null);
95
+ }
96
+ await remover({ home, fromService: false });
97
+ forget(home);
98
+ log(was ? 'This computer is disconnected from Wavie.' : 'heywavie was not connected on this computer.');
99
+ }
100
+
101
+ /** How heywavie stands here: linked to what, the service, Claude Code, and whether Wavie still knows this computer. */
102
+ export async function status({ home, fetch = globalThis.fetch, state = serviceState, find = findClaude, who = claudeStatus }) {
103
+ const l = readLink(home);
104
+ const service = await state({ home });
105
+ const bin = find({ saved: l?.claude ?? null });
106
+ const claude = await who(bin);
107
+ let wavie = null;
108
+ if (l) {
109
+ const res = await fetch(`${l.api}/plans/claude/host`, { headers: { authorization: `Bearer ${l.key}` }, signal: AbortSignal.timeout(15_000) }).catch(() => null);
110
+ wavie = !res ? 'unreachable' : res.status === 401 ? 'unlinked' : res.ok ? 'linked' : `answered ${res.status}`;
111
+ }
112
+ return { linked: Boolean(l), api: l?.api ?? null, device: l?.device ?? null, service, claude: { bin, ...claude }, wavie };
113
+ }
@@ -0,0 +1,192 @@
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { cpSync, existsSync, mkdirSync, openSync, rmSync, writeFileSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { promisify } from 'node:util';
7
+ import { alive, readPid } from './home.mjs';
8
+
9
+ /**
10
+ * The background service that keeps Claude on this computer answering Wavie after the terminal closes: a launchd agent on
11
+ * a Mac, a systemd user service on Linux, a sign-in entry on Windows (the user's own Run key: a logon task needs an
12
+ * administrator). It runs this package's own copy in heywavie's folder (`app/`, so clearing npx's cache never breaks it)
13
+ * with the Node that linked it, as the signed-in person, never root. It restarts after a crash, not after a clean exit
14
+ * (unlinked, or nothing to run).
15
+ */
16
+
17
+ export const LABEL = 'com.heywavie.host';
18
+ const UNIT = 'heywavie.service';
19
+ const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
20
+ const PACKAGE = fileURLToPath(new URL('..', import.meta.url));
21
+
22
+ const run = promisify(execFile);
23
+ const quiet = (p) => p.then(() => true, () => false);
24
+ const xml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
25
+
26
+ /** What starts the service: this Node, heywavie's copy of this package, `run`. */
27
+ export const commandOf = ({ home, node = process.execPath }) => [node, path.join(home, 'app', 'bin', 'heywavie.mjs'), 'run'];
28
+
29
+ /** The launchd agent's plist. */
30
+ export function plistOf({ home, node = process.execPath, env = {} }) {
31
+ const args = commandOf({ home, node }).map((a) => ` <string>${xml(a)}</string>`).join('\n');
32
+ const vars = Object.entries({ HEYWAVIE_HOME: home, ...env }).map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}</string>`).join('\n');
33
+ return `<?xml version="1.0" encoding="UTF-8"?>
34
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
35
+ <plist version="1.0">
36
+ <dict>
37
+ <key>Label</key><string>${LABEL}</string>
38
+ <key>ProgramArguments</key>
39
+ <array>
40
+ ${args}
41
+ </array>
42
+ <key>EnvironmentVariables</key>
43
+ <dict>
44
+ ${vars}
45
+ </dict>
46
+ <key>RunAtLoad</key><true/>
47
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
48
+ <key>ThrottleInterval</key><integer>10</integer>
49
+ <key>ProcessType</key><string>Background</string>
50
+ <key>StandardOutPath</key><string>${xml(path.join(home, 'host.log'))}</string>
51
+ <key>StandardErrorPath</key><string>${xml(path.join(home, 'host.log'))}</string>
52
+ </dict>
53
+ </plist>
54
+ `;
55
+ }
56
+
57
+ /** The systemd user unit. */
58
+ export function unitOf({ home, node = process.execPath, env = {} }) {
59
+ const quote = (a) => `"${String(a).replace(/(["\\])/g, '\\$1')}"`;
60
+ const vars = Object.entries({ HEYWAVIE_HOME: home, ...env }).map(([k, v]) => `Environment=${quote(`${k}=${v}`)}`).join('\n');
61
+ return `[Unit]
62
+ Description=heywavie: Claude on this computer for Wavie
63
+
64
+ [Service]
65
+ ExecStart=${commandOf({ home, node }).map(quote).join(' ')}
66
+ ${vars}
67
+ Restart=on-failure
68
+ RestartSec=10
69
+
70
+ [Install]
71
+ WantedBy=default.target
72
+ `;
73
+ }
74
+
75
+ /** The Windows Run entry's command line. */
76
+ export const runEntryOf = ({ home, node = process.execPath }) => commandOf({ home, node }).map((a, i) => (i < 2 ? `"${a}"` : a)).join(' ');
77
+
78
+ const plistPath = () => path.join(os.homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
79
+ const unitPath = () => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'systemd', 'user', UNIT);
80
+ const domain = () => `gui/${process.getuid()}`;
81
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
82
+
83
+ /**
84
+ * The launchd agent replaced: `bootout` returns before the old one has gone, and `bootstrap` fails while it is still
85
+ * there, so this waits for it to go and tries a few times.
86
+ */
87
+ async function replaceAgent(exec, { home, env }) {
88
+ const target = `${domain()}/${LABEL}`;
89
+ await quiet(exec('launchctl', ['bootout', target]));
90
+ for (let i = 0; i < 50 && (await quiet(exec('launchctl', ['print', target]))); i++) await sleep(100);
91
+ writeFileSync(plistPath(), plistOf({ home, env }));
92
+ for (let i = 0; ; i++) {
93
+ try {
94
+ return await exec('launchctl', ['bootstrap', domain(), plistPath()]);
95
+ } catch (err) {
96
+ if (i >= 4) throw err;
97
+ await sleep(500);
98
+ }
99
+ }
100
+ }
101
+
102
+ /** This package copied into heywavie's folder, for the service to run whatever happens to npx's cache. */
103
+ function copyApp(home) {
104
+ const app = path.join(home, 'app');
105
+ rmSync(app, { recursive: true, force: true });
106
+ mkdirSync(app, { recursive: true });
107
+ for (const part of ['bin', 'src', 'package.json']) cpSync(path.join(PACKAGE, part), path.join(app, part), { recursive: true });
108
+ }
109
+
110
+ /** The service on Windows, started now, apart from this process, with no window; its output to its log. */
111
+ function startDetached(home) {
112
+ const [node, ...args] = commandOf({ home });
113
+ const log = openSync(path.join(home, 'host.log'), 'a');
114
+ spawn(node, args, { detached: true, windowsHide: true, stdio: ['ignore', log, log], env: { ...process.env, HEYWAVIE_HOME: home } }).unref();
115
+ }
116
+
117
+ /** The service's own process stopped, where only its pid file knows it. */
118
+ function stopByPid(home) {
119
+ const pid = readPid(home);
120
+ if (pid && pid !== process.pid && alive(pid)) {
121
+ try { process.kill(pid); } catch { /* gone already */ }
122
+ }
123
+ }
124
+
125
+ /**
126
+ * The service installed and started (a running one replaced). Resolves `{ ok: true }`, or `{ ok: false, reason }` when
127
+ * this computer won't take one.
128
+ */
129
+ export async function install({ home, platform = process.platform, exec = run, env = {} }) {
130
+ copyApp(home);
131
+ try {
132
+ if (platform === 'darwin') {
133
+ mkdirSync(path.dirname(plistPath()), { recursive: true });
134
+ await replaceAgent(exec, { home, env });
135
+ } else if (platform === 'linux') {
136
+ mkdirSync(path.dirname(unitPath()), { recursive: true });
137
+ writeFileSync(unitPath(), unitOf({ home, env }));
138
+ await exec('systemctl', ['--user', 'daemon-reload']);
139
+ await exec('systemctl', ['--user', 'enable', UNIT]);
140
+ await exec('systemctl', ['--user', 'restart', UNIT]);
141
+ // A user service otherwise stops when they sign out; allowed for one's own account on most systems.
142
+ await quiet(exec('loginctl', ['enable-linger']));
143
+ } else if (platform === 'win32') {
144
+ await exec('reg', ['add', RUN_KEY, '/v', 'heywavie', '/t', 'REG_SZ', '/d', runEntryOf({ home }), '/f']);
145
+ stopByPid(home);
146
+ startDetached(home);
147
+ } else {
148
+ return { ok: false, reason: `heywavie has no background service for ${platform}.` };
149
+ }
150
+ return { ok: true };
151
+ } catch (err) {
152
+ const said = String(err?.stderr || err?.message || err).trim().split('\n').filter(Boolean).at(-1) ?? 'it failed';
153
+ return { ok: false, reason: said.slice(0, 300) };
154
+ }
155
+ }
156
+
157
+ /** Whether the service is installed here, and running. */
158
+ export async function serviceState({ home, platform = process.platform, exec = run } = {}) {
159
+ if (platform === 'darwin') {
160
+ if (!existsSync(plistPath())) return { installed: false, running: false };
161
+ const out = await exec('launchctl', ['print', `${domain()}/${LABEL}`]).then((r) => r.stdout, () => '');
162
+ return { installed: true, running: /state = running/.test(out) };
163
+ }
164
+ if (platform === 'linux') {
165
+ if (!existsSync(unitPath())) return { installed: false, running: false };
166
+ return { installed: true, running: await quiet(exec('systemctl', ['--user', 'is-active', '--quiet', UNIT])) };
167
+ }
168
+ if (platform === 'win32') {
169
+ return { installed: await quiet(exec('reg', ['query', RUN_KEY, '/v', 'heywavie'])), running: Boolean(home) && alive(readPid(home)) };
170
+ }
171
+ return { installed: false, running: false };
172
+ }
173
+
174
+ /**
175
+ * The service stopped and gone. From a terminal (`heywavie disconnect`) it is stopped first; from the service itself
176
+ * (unlinked in Wavie, `fromService`) its files go first and stopping it is its last act.
177
+ */
178
+ export async function uninstall({ home = null, fromService = false, platform = process.platform, exec = run } = {}) {
179
+ if (platform === 'darwin') {
180
+ if (!fromService) await quiet(exec('launchctl', ['bootout', `${domain()}/${LABEL}`]));
181
+ if (existsSync(plistPath())) rmSync(plistPath(), { force: true });
182
+ if (fromService) await quiet(exec('launchctl', ['bootout', `${domain()}/${LABEL}`]));
183
+ } else if (platform === 'linux') {
184
+ await quiet(exec('systemctl', ['--user', 'disable', ...(fromService ? [] : ['--now']), UNIT]));
185
+ if (existsSync(unitPath())) rmSync(unitPath(), { force: true });
186
+ await quiet(exec('systemctl', ['--user', 'daemon-reload']));
187
+ if (fromService) await quiet(exec('systemctl', ['--user', 'stop', UNIT]));
188
+ } else if (platform === 'win32') {
189
+ if (!fromService && home) stopByPid(home);
190
+ await quiet(exec('reg', ['delete', RUN_KEY, '/v', 'heywavie', '/f']));
191
+ }
192
+ }