@heywavie/cli 0.2.4 → 0.2.5
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 +6 -2
- package/bin/heywavie.mjs +16 -6
- package/package.json +1 -1
- package/src/claude.mjs +187 -39
- package/src/host.mjs +67 -20
- package/src/link.mjs +89 -21
- package/src/service.mjs +52 -13
- package/src/wavie.mjs +17 -0
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ Claude Code they use there. Published to npm as `@heywavie/cli` (its command is
|
|
|
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/claude-setup.
|
|
10
|
+
2. They paste it into Claude Code on that computer. Claude Code reads the page (`server/src/app/claude-setup.ts`) and runs
|
|
11
11
|
`npx --yes @heywavie/cli@<version> link --url "<that address>" --yes` itself.
|
|
12
12
|
3. `link` checks Claude Code (found, signed in), trades the token for this computer's own key
|
|
13
13
|
(`POST /plans/claude/hosts`), keeps it in `~/.heywavie/link.json` (mode 600), copies itself to `~/.heywavie/app` and
|
|
@@ -36,6 +36,10 @@ and `~/.heywavie` gone), unless the computer was linked again since (a new key o
|
|
|
36
36
|
`heywavie disconnect` does the same from the computer. A service with nothing linked takes itself off too; it restarts
|
|
37
37
|
after a crash, never after a clean exit.
|
|
38
38
|
|
|
39
|
+
Its calls go under `/v1` and name it (`x-wavie-client: cli/<version>`, `src/wavie.mjs`). A copy older than the server
|
|
40
|
+
takes gets 426: `link` and `status` say to update (`npm i -g @heywavie/cli@latest`, then connect again), and the
|
|
41
|
+
service logs the same and looks again every 30 minutes.
|
|
42
|
+
|
|
39
43
|
```bash
|
|
40
44
|
npm test # the runner, linking, the service files, the wait loop
|
|
41
45
|
node bin/heywavie.mjs status # linked to what, the service, Claude Code
|
|
@@ -48,5 +52,5 @@ node bin/heywavie.mjs disconnect
|
|
|
48
52
|
|
|
49
53
|
## Publishing
|
|
50
54
|
|
|
51
|
-
Raise `version` here and `CLI_VERSION` in `server/src/plans.
|
|
55
|
+
Raise `version` here and `CLI_VERSION` in `server/src/app/plans.ts` together (a server test checks), then `npm publish`
|
|
52
56
|
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,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { writeFileSync } from 'node:fs';
|
|
3
3
|
import { forget, homeOf, pidPath, readLink } from '../src/home.mjs';
|
|
4
4
|
import { host } from '../src/host.mjs';
|
|
5
5
|
import { disconnect, link, status, Stop } from '../src/link.mjs';
|
|
6
6
|
import { uninstall } from '../src/service.mjs';
|
|
7
|
+
import { VERSION } from '../src/wavie.mjs';
|
|
7
8
|
|
|
8
|
-
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
9
9
|
const HELP = `heywavie ${VERSION}: Claude on this computer, for Wavie
|
|
10
10
|
|
|
11
11
|
heywavie link --url "<the address from Wavie's sentence>" [--yes]
|
|
@@ -54,7 +54,9 @@ try {
|
|
|
54
54
|
if (verb === 'link') {
|
|
55
55
|
const { service } = await link({ url: value('url'), home });
|
|
56
56
|
if (service) {
|
|
57
|
-
console.log(
|
|
57
|
+
console.log(
|
|
58
|
+
`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.`,
|
|
59
|
+
);
|
|
58
60
|
process.exitCode = 2;
|
|
59
61
|
}
|
|
60
62
|
} else if (verb === 'run') {
|
|
@@ -63,9 +65,17 @@ try {
|
|
|
63
65
|
const s = await status({ home });
|
|
64
66
|
if (flag('json')) console.log(JSON.stringify(s, null, 2));
|
|
65
67
|
else {
|
|
66
|
-
console.log(
|
|
67
|
-
|
|
68
|
-
|
|
68
|
+
console.log(
|
|
69
|
+
s.linked
|
|
70
|
+
? `Linked to ${s.api} as ${s.device}; Wavie ${s.wavie === 'linked' ? 'knows this computer' : s.wavie}.`
|
|
71
|
+
: 'Not linked to Wavie.',
|
|
72
|
+
);
|
|
73
|
+
console.log(
|
|
74
|
+
`Service: ${s.service.installed ? (s.service.running ? 'installed and running' : 'installed, not running') : 'not installed'}.`,
|
|
75
|
+
);
|
|
76
|
+
console.log(
|
|
77
|
+
`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
|
+
);
|
|
69
79
|
}
|
|
70
80
|
} else if (verb === 'disconnect') {
|
|
71
81
|
await disconnect({ home });
|
package/package.json
CHANGED
package/src/claude.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { existsSync } from 'node:fs';
|
|
|
3
3
|
import { mkdtemp, readdir, rm, stat, writeFile } from 'node:fs/promises';
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
+
import { CLIENT_HEADER } from './wavie.mjs';
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* Wavie's turns on the person's own Claude plan, run on their computer by the Claude Code they signed in to there. Model
|
|
@@ -13,20 +14,36 @@ import path from 'node:path';
|
|
|
13
14
|
*/
|
|
14
15
|
|
|
15
16
|
const WINDOWS = process.platform === 'win32';
|
|
16
|
-
const where = (home, windows) =>
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
const where = (home, windows) =>
|
|
18
|
+
windows
|
|
19
|
+
? [path.join(home, '.local', 'bin', 'claude.exe')]
|
|
20
|
+
: [
|
|
21
|
+
path.join(home, '.local/bin/claude'),
|
|
22
|
+
path.join(home, '.claude/local/claude'),
|
|
23
|
+
'/opt/homebrew/bin/claude',
|
|
24
|
+
'/usr/local/bin/claude',
|
|
25
|
+
'/usr/bin/claude',
|
|
26
|
+
];
|
|
19
27
|
|
|
20
28
|
/**
|
|
21
29
|
* Claude Code on this computer: `HEYWAVIE_CLAUDE_BIN`, else where it was when they linked (`saved`), else on the PATH
|
|
22
30
|
* (linking runs in Claude Code's own shell: an npm install under nvm is only found there), else where its installers put
|
|
23
31
|
* it (a background service has no shell PATH), or null. A Windows npm install (`claude.cmd`) isn't run: it needs a shell.
|
|
24
32
|
*/
|
|
25
|
-
export function findClaude({
|
|
33
|
+
export function findClaude({
|
|
34
|
+
env = process.env,
|
|
35
|
+
home = os.homedir(),
|
|
36
|
+
exists = existsSync,
|
|
37
|
+
saved = null,
|
|
38
|
+
windows = WINDOWS,
|
|
39
|
+
} = {}) {
|
|
26
40
|
const set = env.HEYWAVIE_CLAUDE_BIN?.trim();
|
|
27
41
|
if (set) return exists(set) ? set : null;
|
|
28
42
|
if (saved && exists(saved)) return saved;
|
|
29
|
-
const onPath = String(env.PATH ?? '')
|
|
43
|
+
const onPath = String(env.PATH ?? '')
|
|
44
|
+
.split(windows ? ';' : ':')
|
|
45
|
+
.filter(Boolean)
|
|
46
|
+
.map((dir) => path.join(dir, windows ? 'claude.exe' : 'claude'));
|
|
30
47
|
return [...onPath, ...where(home, windows)].find((p) => exists(p)) ?? null;
|
|
31
48
|
}
|
|
32
49
|
|
|
@@ -40,7 +57,12 @@ const WINDOWS_KEEP = ['USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'SystemRoot', 'S
|
|
|
40
57
|
export function claudeEnv(env = process.env, home = os.homedir(), bin = null, { windows = WINDOWS, user = null } = {}) {
|
|
41
58
|
const who = env.USER || env.USERNAME || user || '';
|
|
42
59
|
const own = bin ? [path.dirname(bin)] : [];
|
|
43
|
-
const base = {
|
|
60
|
+
const base = {
|
|
61
|
+
HOME: home,
|
|
62
|
+
LANG: env.LANG || 'en_US.UTF-8',
|
|
63
|
+
TMPDIR: env.TMPDIR ?? os.tmpdir(),
|
|
64
|
+
DISABLE_AUTOUPDATER: '1',
|
|
65
|
+
};
|
|
44
66
|
if (windows) {
|
|
45
67
|
const kept = Object.fromEntries(WINDOWS_KEEP.filter((k) => env[k]).map((k) => [k, env[k]]));
|
|
46
68
|
const system = env.SystemRoot ? [path.join(env.SystemRoot, 'System32'), env.SystemRoot] : [];
|
|
@@ -72,11 +94,35 @@ export const mcpConfig = (tools) => ({ mcpServers: { wavie: { type: 'http', url:
|
|
|
72
94
|
* files only they can read (`systemFile`, `mcpFile`), never on the command line, where anyone on the computer sees it (ps).
|
|
73
95
|
*/
|
|
74
96
|
export function claudeArgs({ systemFile, mcpFile, maxSteps, model = CLAUDE_MODEL, effort = null }) {
|
|
75
|
-
return [
|
|
76
|
-
'
|
|
77
|
-
|
|
97
|
+
return [
|
|
98
|
+
'-p',
|
|
99
|
+
...(model ? ['--model', model] : []),
|
|
100
|
+
...(effort ? ['--effort', effort] : []),
|
|
101
|
+
'--output-format',
|
|
102
|
+
'stream-json',
|
|
103
|
+
'--verbose',
|
|
104
|
+
'--include-partial-messages',
|
|
105
|
+
'--input-format',
|
|
106
|
+
'stream-json',
|
|
107
|
+
'--system-prompt-file',
|
|
108
|
+
systemFile,
|
|
109
|
+
'--tools',
|
|
110
|
+
'',
|
|
111
|
+
'--strict-mcp-config',
|
|
112
|
+
'--mcp-config',
|
|
113
|
+
mcpFile,
|
|
114
|
+
'--allowedTools',
|
|
115
|
+
'mcp__wavie',
|
|
116
|
+
'--permission-prompts',
|
|
117
|
+
'none',
|
|
118
|
+
'--no-session-persistence',
|
|
119
|
+
'--disable-slash-commands',
|
|
78
120
|
// No --safe-mode: it turns off MCP servers too, Wavie's with them. Their CLAUDE.md stays out without it.
|
|
79
|
-
'--setting-sources',
|
|
121
|
+
'--setting-sources',
|
|
122
|
+
'',
|
|
123
|
+
'--max-turns',
|
|
124
|
+
String(maxSteps),
|
|
125
|
+
];
|
|
80
126
|
}
|
|
81
127
|
|
|
82
128
|
// A turn's own folder, with its instructions in it.
|
|
@@ -91,9 +137,15 @@ export async function clearLeftTurns({ tmp = os.tmpdir(), olderThanMs, now = Dat
|
|
|
91
137
|
let cleared = 0;
|
|
92
138
|
for (const name of names.filter((n) => TURN_DIR.test(n))) {
|
|
93
139
|
const dir = path.join(tmp, name);
|
|
94
|
-
const at = await stat(dir)
|
|
140
|
+
const at = await stat(dir)
|
|
141
|
+
.then((s) => s.mtimeMs)
|
|
142
|
+
.catch(() => null);
|
|
95
143
|
if (at === null || now - at < olderThanMs) continue;
|
|
96
|
-
await rm(dir, { recursive: true, force: true })
|
|
144
|
+
await rm(dir, { recursive: true, force: true })
|
|
145
|
+
.then(() => {
|
|
146
|
+
cleared += 1;
|
|
147
|
+
})
|
|
148
|
+
.catch(() => {});
|
|
97
149
|
}
|
|
98
150
|
return cleared;
|
|
99
151
|
}
|
|
@@ -101,42 +153,74 @@ export async function clearLeftTurns({ tmp = os.tmpdir(), olderThanMs, now = Dat
|
|
|
101
153
|
const TURN_PATH = /^\/plan-turns\/([A-Za-z0-9_-]{32})\/(tools|events)$/;
|
|
102
154
|
const FILE_PATH = /^\/plan-turns\/([A-Za-z0-9_-]{32})\/files\/([0-9a-f-]{36})$/;
|
|
103
155
|
const FILE_TYPES = new Set(['application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'image/webp']);
|
|
156
|
+
// The most files one turn hands Claude Code.
|
|
157
|
+
const FILES_MAX = 10;
|
|
104
158
|
|
|
105
159
|
/** A turn as the server asked for it, checked: its addresses on Wavie's own API (`api`), its words, its files, its steps. */
|
|
106
160
|
export function turnOf(input, api) {
|
|
107
161
|
const tools = TURN_PATH.exec(String(input?.tools ?? ''));
|
|
108
162
|
const events = TURN_PATH.exec(String(input?.events ?? ''));
|
|
109
|
-
if (!tools || !events || tools[2] !== 'tools' || events[2] !== 'events' || tools[1] !== events[1])
|
|
110
|
-
|
|
163
|
+
if (!tools || !events || tools[2] !== 'tools' || events[2] !== 'events' || tools[1] !== events[1])
|
|
164
|
+
throw new Error("Not a turn of Wavie's.");
|
|
165
|
+
if (typeof input.system !== 'string' || typeof input.prompt !== 'string' || !input.prompt.trim())
|
|
166
|
+
throw new Error('A turn with nothing to answer.');
|
|
111
167
|
const steps = Number.isInteger(input.maxSteps) && input.maxSteps >= 1 && input.maxSteps <= 60 ? input.maxSteps : 24;
|
|
112
|
-
const
|
|
168
|
+
const sent = Array.isArray(input.files) ? input.files : [];
|
|
169
|
+
const files = sent.slice(0, FILES_MAX).map((f) => {
|
|
113
170
|
const at = FILE_PATH.exec(String(f?.url ?? ''));
|
|
114
|
-
if (!at || at[1] !== tools[1] || !FILE_TYPES.has(f.mediaType)) throw new Error(
|
|
171
|
+
if (!at || at[1] !== tools[1] || !FILE_TYPES.has(f.mediaType)) throw new Error("Not a turn of Wavie's.");
|
|
115
172
|
return { url: `${api}${at[0]}`, name: String(f.name ?? 'file').slice(0, 200), mediaType: f.mediaType };
|
|
116
173
|
});
|
|
174
|
+
// Files past the most one turn hands over: named to Claude as not attached, never dropped unsaid.
|
|
175
|
+
const filesLeft = sent.slice(FILES_MAX).map((f) => String(f?.name ?? 'file').slice(0, 200));
|
|
117
176
|
// The model and effort they picked, only from Claude Code's own lists; anything else runs as if unpicked.
|
|
118
177
|
const model = CLAUDE_MODELS.includes(input.model) ? input.model : null;
|
|
119
178
|
const effort = CLAUDE_EFFORTS.includes(input.effort) ? input.effort : null;
|
|
120
|
-
return {
|
|
179
|
+
return {
|
|
180
|
+
tools: `${api}${tools[0]}`,
|
|
181
|
+
events: `${api}${events[0]}`,
|
|
182
|
+
system: input.system,
|
|
183
|
+
prompt: input.prompt,
|
|
184
|
+
files,
|
|
185
|
+
...(filesLeft.length ? { filesLeft } : {}),
|
|
186
|
+
maxSteps: steps,
|
|
187
|
+
model,
|
|
188
|
+
effort,
|
|
189
|
+
};
|
|
121
190
|
}
|
|
122
191
|
|
|
123
192
|
/** Who Claude Code on this computer is signed in as: `{ found, loggedIn, email, kind }`. */
|
|
124
193
|
export function claudeStatus(bin, { env = process.env, home = os.homedir() } = {}) {
|
|
125
194
|
if (!bin) return Promise.resolve({ found: false, loggedIn: false, email: null, kind: null });
|
|
126
195
|
return new Promise((resolve) => {
|
|
127
|
-
const child = spawn(bin, ['auth', 'status'], {
|
|
196
|
+
const child = spawn(bin, ['auth', 'status'], {
|
|
197
|
+
env: claudeEnv(env, home, bin, { user: os.userInfo().username }),
|
|
198
|
+
cwd: os.tmpdir(),
|
|
199
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
200
|
+
});
|
|
128
201
|
let out = '';
|
|
129
202
|
const timer = setTimeout(() => child.kill('SIGKILL'), 20_000);
|
|
130
|
-
child.stdout.on('data', (d) => {
|
|
203
|
+
child.stdout.on('data', (d) => {
|
|
204
|
+
out += d;
|
|
205
|
+
});
|
|
131
206
|
let settled = false;
|
|
132
207
|
const done = () => {
|
|
133
208
|
if (settled) return;
|
|
134
209
|
settled = true;
|
|
135
210
|
clearTimeout(timer);
|
|
136
211
|
let st = null;
|
|
137
|
-
try {
|
|
212
|
+
try {
|
|
213
|
+
st = JSON.parse(out.slice(out.indexOf('{')));
|
|
214
|
+
} catch {
|
|
215
|
+
st = null;
|
|
216
|
+
}
|
|
138
217
|
const kind = st?.subscriptionType ?? st?.account?.subscriptionType ?? null;
|
|
139
|
-
resolve({
|
|
218
|
+
resolve({
|
|
219
|
+
found: true,
|
|
220
|
+
loggedIn: st?.loggedIn === true,
|
|
221
|
+
email: st?.email ?? st?.account?.email ?? null,
|
|
222
|
+
kind: kind ? String(kind) : null,
|
|
223
|
+
});
|
|
140
224
|
};
|
|
141
225
|
child.on('error', done);
|
|
142
226
|
child.on('close', done);
|
|
@@ -148,15 +232,35 @@ async function messageOf(turn, fetch) {
|
|
|
148
232
|
const content = [{ type: 'text', text: turn.prompt }];
|
|
149
233
|
for (const f of turn.files ?? []) {
|
|
150
234
|
try {
|
|
151
|
-
const res = await fetch(f.url, { signal: AbortSignal.timeout(60_000) });
|
|
152
|
-
if (!res.ok)
|
|
235
|
+
const res = await fetch(f.url, { headers: CLIENT_HEADER, signal: AbortSignal.timeout(60_000) });
|
|
236
|
+
if (!res.ok) {
|
|
237
|
+
// The server's own words on why (too big: its size, the most, how to read it), where it gave any.
|
|
238
|
+
const said = (await res.json().catch(() => null))?.message;
|
|
239
|
+
if (typeof said !== 'string' || !said.trim()) throw new Error(String(res.status));
|
|
240
|
+
content.push({ type: 'text', text: `[${f.name} is not attached. Wavie's server says: ${said.trim()}]` });
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
153
243
|
const data = Buffer.from(await res.arrayBuffer()).toString('base64');
|
|
154
|
-
content.push(
|
|
155
|
-
{ type:
|
|
244
|
+
content.push(
|
|
245
|
+
{ type: 'text', text: `Attached: ${f.name}` },
|
|
246
|
+
{
|
|
247
|
+
type: f.mediaType === 'application/pdf' ? 'document' : 'image',
|
|
248
|
+
source: { type: 'base64', media_type: f.mediaType, data },
|
|
249
|
+
},
|
|
250
|
+
);
|
|
156
251
|
} catch {
|
|
157
252
|
content.push({ type: 'text', text: `[${f.name} could not be fetched from Wavie: tell them if it matters.]` });
|
|
158
253
|
}
|
|
159
254
|
}
|
|
255
|
+
const left = turn.filesLeft ?? [];
|
|
256
|
+
if (left.length) {
|
|
257
|
+
content.push({
|
|
258
|
+
type: 'text',
|
|
259
|
+
text:
|
|
260
|
+
`[Not attached: ${left.join(', ')}. One turn hands you ${FILES_MAX} files at most and their message had ${FILES_MAX + left.length}: ` +
|
|
261
|
+
'say which you have not seen, and ask for them in another message if they matter.]',
|
|
262
|
+
});
|
|
263
|
+
}
|
|
160
264
|
return `${JSON.stringify({ type: 'user', message: { role: 'user', content } })}\n`;
|
|
161
265
|
}
|
|
162
266
|
|
|
@@ -177,20 +281,40 @@ const BATCH_LINES = 500;
|
|
|
177
281
|
* server's side. `ready` holds the turn while this computer is busy with others (it still says it's there). Resolves once Claude Code
|
|
178
282
|
* is done and the server was told how it ended.
|
|
179
283
|
*/
|
|
180
|
-
export async function runTurn({
|
|
181
|
-
|
|
284
|
+
export async function runTurn({
|
|
285
|
+
bin,
|
|
286
|
+
turn,
|
|
287
|
+
fetch = globalThis.fetch,
|
|
288
|
+
env = process.env,
|
|
289
|
+
home = os.homedir(),
|
|
290
|
+
ready = null,
|
|
291
|
+
flushMs = 150,
|
|
292
|
+
beatMs = 10_000,
|
|
293
|
+
maxMs = 20 * 60_000,
|
|
294
|
+
timeoutMs = 20_000,
|
|
295
|
+
}) {
|
|
182
296
|
let child = null;
|
|
183
297
|
let stopping = false;
|
|
184
298
|
const stop = () => {
|
|
185
299
|
stopping = true;
|
|
186
300
|
if (!child) return;
|
|
187
301
|
child.kill('SIGTERM');
|
|
188
|
-
setTimeout(() => {
|
|
302
|
+
setTimeout(() => {
|
|
303
|
+
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
|
|
304
|
+
}, 5000).unref?.();
|
|
189
305
|
};
|
|
190
306
|
const send = async (body) => {
|
|
191
307
|
try {
|
|
192
|
-
const res = await fetch(turn.events, {
|
|
193
|
-
|
|
308
|
+
const res = await fetch(turn.events, {
|
|
309
|
+
method: 'POST',
|
|
310
|
+
headers: { 'content-type': 'application/json', ...CLIENT_HEADER },
|
|
311
|
+
body: JSON.stringify(body),
|
|
312
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
313
|
+
});
|
|
314
|
+
if (res.status === 404) {
|
|
315
|
+
stop();
|
|
316
|
+
return true;
|
|
317
|
+
}
|
|
194
318
|
if (!res.ok) return false;
|
|
195
319
|
if ((await res.json().catch(() => ({}))).stop) stop();
|
|
196
320
|
return true;
|
|
@@ -208,7 +332,9 @@ export async function runTurn({ bin, turn, fetch = globalThis.fetch, env = proce
|
|
|
208
332
|
chain = chain.then(async () => {
|
|
209
333
|
while (pending.length) batches.push({ n: ++n, lines: pending.splice(0, BATCH_LINES) });
|
|
210
334
|
if (!batches.length) {
|
|
211
|
-
if (force || Date.now() - lastSent >= beatMs) {
|
|
335
|
+
if (force || Date.now() - lastSent >= beatMs) {
|
|
336
|
+
if (await send({ lines: [] })) lastSent = Date.now();
|
|
337
|
+
}
|
|
212
338
|
return;
|
|
213
339
|
}
|
|
214
340
|
while (batches.length) {
|
|
@@ -242,20 +368,37 @@ export async function runTurn({ bin, turn, fetch = globalThis.fetch, env = proce
|
|
|
242
368
|
// with model_not_found) runs again on Claude Code's own default: Claude Code's opening lines wait until the first
|
|
243
369
|
// message shows which, and the refusal never reaches the server as an answer.
|
|
244
370
|
const once = async (model) => {
|
|
245
|
-
child = spawn(
|
|
246
|
-
|
|
371
|
+
child = spawn(
|
|
372
|
+
bin,
|
|
373
|
+
claudeArgs({ systemFile, mcpFile, maxSteps: turn.maxSteps, model, effort: turn.effort ?? null }),
|
|
374
|
+
{ cwd: dir, env: claudeEnv(env, home, bin, { user: os.userInfo().username }), stdio: ['pipe', 'pipe', 'pipe'] },
|
|
375
|
+
);
|
|
247
376
|
children.add(child);
|
|
248
377
|
let buffer = '';
|
|
249
378
|
let held = model ? [] : null;
|
|
250
379
|
let refused = false;
|
|
251
380
|
const take = (line) => {
|
|
252
381
|
if (refused) return;
|
|
253
|
-
if (!held) {
|
|
382
|
+
if (!held) {
|
|
383
|
+
pending.push(line);
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
254
386
|
let item = null;
|
|
255
|
-
try {
|
|
256
|
-
|
|
387
|
+
try {
|
|
388
|
+
item = JSON.parse(line);
|
|
389
|
+
} catch {
|
|
390
|
+
/* not JSON: shown as it is */
|
|
391
|
+
}
|
|
392
|
+
if (item?.type === 'system') {
|
|
393
|
+
held.push(line);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
257
396
|
const words = item?.type === 'assistant' ? (item.message?.content ?? []).map((b) => b?.text ?? '').join(' ') : '';
|
|
258
|
-
if (item?.type === 'assistant' && (item.error === 'model_not_found' || REFUSED.test(words))) {
|
|
397
|
+
if (item?.type === 'assistant' && (item.error === 'model_not_found' || REFUSED.test(words))) {
|
|
398
|
+
refused = true;
|
|
399
|
+
held = null;
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
259
402
|
pending.push(...held, line);
|
|
260
403
|
held = null;
|
|
261
404
|
};
|
|
@@ -269,11 +412,16 @@ export async function runTurn({ bin, turn, fetch = globalThis.fetch, env = proce
|
|
|
269
412
|
if (line) take(line);
|
|
270
413
|
}
|
|
271
414
|
});
|
|
272
|
-
child.stderr.on('data', (d) => {
|
|
415
|
+
child.stderr.on('data', (d) => {
|
|
416
|
+
errText = (errText + d).slice(-4000);
|
|
417
|
+
});
|
|
273
418
|
child.stdin.on('error', () => {});
|
|
274
419
|
child.stdin.end(message);
|
|
275
420
|
const exit = await new Promise((resolve) => {
|
|
276
|
-
child.on('error', (err) => {
|
|
421
|
+
child.on('error', (err) => {
|
|
422
|
+
errText = `${errText}\n${err?.message ?? err}`;
|
|
423
|
+
resolve(-1);
|
|
424
|
+
});
|
|
277
425
|
child.on('close', (c) => resolve(c ?? -1));
|
|
278
426
|
});
|
|
279
427
|
children.delete(child);
|
package/src/host.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { findClaude, runTurn, stopAll, turnOf } from './claude.mjs';
|
|
2
|
+
import { CLIENT_HEADER, routesOf, updateLine } from './wavie.mjs';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* The service: waits on Wavie for turns on their Claude plan (`GET /device/asks`, a long poll, by this computer's key)
|
|
@@ -10,18 +11,30 @@ export const TURNS_MAX = 3;
|
|
|
10
11
|
const WAIT_S = 20;
|
|
11
12
|
|
|
12
13
|
const PLATFORM = { darwin: 'darwin', linux: 'linux', win32: 'win32' }[process.platform] ?? 'linux';
|
|
13
|
-
const sleep = (ms, signal) =>
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
const sleep = (ms, signal) =>
|
|
15
|
+
new Promise((resolve) => {
|
|
16
|
+
if (signal?.aborted) return resolve();
|
|
17
|
+
const t = setTimeout(resolve, ms);
|
|
18
|
+
signal?.addEventListener(
|
|
19
|
+
'abort',
|
|
20
|
+
() => {
|
|
21
|
+
clearTimeout(t);
|
|
22
|
+
resolve();
|
|
23
|
+
},
|
|
24
|
+
{ once: true },
|
|
25
|
+
);
|
|
26
|
+
});
|
|
18
27
|
// A body that ends when the service stops: once its request is aborted, fetch can leave res.json() waiting for good.
|
|
19
|
-
const bodyOf = (res, signal) =>
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
28
|
+
const bodyOf = (res, signal) =>
|
|
29
|
+
new Promise((resolve) => {
|
|
30
|
+
if (signal?.aborted) return resolve({});
|
|
31
|
+
const stop = () => resolve({});
|
|
32
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
33
|
+
res
|
|
34
|
+
.json()
|
|
35
|
+
.then(resolve, () => resolve({}))
|
|
36
|
+
.finally(() => signal?.removeEventListener('abort', stop));
|
|
37
|
+
});
|
|
25
38
|
|
|
26
39
|
/** Turns running here at once, at most `max`: `place()` resolves when there is room, `free()` hands it on. */
|
|
27
40
|
export function places(max = TURNS_MAX) {
|
|
@@ -41,21 +54,39 @@ export function places(max = TURNS_MAX) {
|
|
|
41
54
|
* Runs until `signal` aborts or Wavie no longer knows this key. `log` gets one line per thing worth knowing; nothing of
|
|
42
55
|
* a chat is ever in it.
|
|
43
56
|
*/
|
|
44
|
-
export async function host({
|
|
45
|
-
|
|
57
|
+
export async function host({
|
|
58
|
+
link,
|
|
59
|
+
fetch = globalThis.fetch,
|
|
60
|
+
signal = null,
|
|
61
|
+
log = console.log,
|
|
62
|
+
onUnlinked = async () => {},
|
|
63
|
+
run = runTurn,
|
|
64
|
+
find = findClaude,
|
|
65
|
+
platform = PLATFORM,
|
|
66
|
+
waitS = WAIT_S,
|
|
67
|
+
tooOldMs = 30 * 60_000,
|
|
68
|
+
}) {
|
|
46
69
|
const { api, device, key } = link;
|
|
47
|
-
const headers = { authorization: `Bearer ${key}`, 'content-type': 'application/json' };
|
|
70
|
+
const headers = { authorization: `Bearer ${key}`, 'content-type': 'application/json', ...CLIENT_HEADER };
|
|
48
71
|
const room = places();
|
|
49
72
|
const turns = new Set();
|
|
50
73
|
let backoff = 1000;
|
|
51
|
-
const answer = (id, body) =>
|
|
52
|
-
|
|
74
|
+
const answer = (id, body) =>
|
|
75
|
+
fetch(`${routesOf(api)}/device/asks/${id}`, {
|
|
76
|
+
method: 'POST',
|
|
77
|
+
headers,
|
|
78
|
+
body: JSON.stringify({ device, ...body }),
|
|
79
|
+
signal: AbortSignal.timeout(20_000),
|
|
80
|
+
}).catch(() => null);
|
|
53
81
|
|
|
54
82
|
const start = (ask) => {
|
|
55
83
|
const bin = find({ saved: link.claude ?? null });
|
|
56
84
|
if (!bin) {
|
|
57
85
|
log("Claude Code isn't on this computer any more: install it again and sign in (claude auth login).");
|
|
58
|
-
return answer(ask.id, {
|
|
86
|
+
return answer(ask.id, {
|
|
87
|
+
error:
|
|
88
|
+
"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.",
|
|
89
|
+
});
|
|
59
90
|
}
|
|
60
91
|
let turn;
|
|
61
92
|
try {
|
|
@@ -64,8 +95,15 @@ export async function host({ link, fetch = globalThis.fetch, signal = null, log
|
|
|
64
95
|
return answer(ask.id, { error: String(err?.message ?? err) });
|
|
65
96
|
}
|
|
66
97
|
const ready = room.place();
|
|
67
|
-
const t = run({ bin, turn, ready })
|
|
68
|
-
.
|
|
98
|
+
const t = run({ bin, turn, ready })
|
|
99
|
+
.then(
|
|
100
|
+
(code) => log(`turn ended (${code})`),
|
|
101
|
+
(err) => log(`turn broke: ${err?.message ?? err}`),
|
|
102
|
+
)
|
|
103
|
+
.finally(() => {
|
|
104
|
+
void ready.then(room.free);
|
|
105
|
+
turns.delete(t);
|
|
106
|
+
});
|
|
69
107
|
turns.add(t);
|
|
70
108
|
log('turn started');
|
|
71
109
|
return answer(ask.id, { answer: { started: true } });
|
|
@@ -76,7 +114,10 @@ export async function host({ link, fetch = globalThis.fetch, signal = null, log
|
|
|
76
114
|
let res;
|
|
77
115
|
try {
|
|
78
116
|
const q = new URLSearchParams({ device, platform, can: 'claude', wait: String(waitS) });
|
|
79
|
-
res = await fetch(`${api}/device/asks?${q}`, {
|
|
117
|
+
res = await fetch(`${routesOf(api)}/device/asks?${q}`, {
|
|
118
|
+
headers,
|
|
119
|
+
signal: AbortSignal.any([AbortSignal.timeout((waitS + 30) * 1000), ...(signal ? [signal] : [])]),
|
|
120
|
+
});
|
|
80
121
|
} catch (err) {
|
|
81
122
|
if (signal?.aborted) break;
|
|
82
123
|
log(`can't reach Wavie (${err?.cause?.code ?? err?.message ?? err}), trying again`);
|
|
@@ -91,6 +132,12 @@ export async function host({ link, fetch = globalThis.fetch, signal = null, log
|
|
|
91
132
|
await onUnlinked();
|
|
92
133
|
return 'unlinked';
|
|
93
134
|
}
|
|
135
|
+
// Too old for Wavie: nothing here can fix it, so say how and look again only now and then.
|
|
136
|
+
if (res.status === 426) {
|
|
137
|
+
log(updateLine(await bodyOf(res, signal)));
|
|
138
|
+
await sleep(tooOldMs, signal);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
94
141
|
if (!res.ok) {
|
|
95
142
|
log(`Wavie answered ${res.status}, trying again`);
|
|
96
143
|
await sleep(backoff, signal);
|
package/src/link.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import os from 'node:os';
|
|
|
3
3
|
import { claudeStatus, findClaude } from './claude.mjs';
|
|
4
4
|
import { canWrite, forget, newDevice, readLink, writeLink } from './home.mjs';
|
|
5
5
|
import { install, serviceState, uninstall } from './service.mjs';
|
|
6
|
+
import { CLIENT_HEADER, routesOf, updateLine } from './wavie.mjs';
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* Linking this computer to their Wavie, from the one-time address Wavie gave them (`<api>/claude/setup#token=…`), and
|
|
@@ -24,10 +25,13 @@ export function parseLinkUrl(raw) {
|
|
|
24
25
|
} catch {
|
|
25
26
|
throw new Stop('The URL is not a Wavie link: pass the address from the sentence, in double quotes.');
|
|
26
27
|
}
|
|
27
|
-
if (url.pathname.replace(/\/+$/, '') !== '/claude/setup')
|
|
28
|
+
if (url.pathname.replace(/\/+$/, '') !== '/claude/setup')
|
|
29
|
+
throw new Stop('The URL is not a Wavie link: its path must be /claude/setup.');
|
|
28
30
|
const token = new URLSearchParams(url.hash.replace(/^#/, '')).get('token');
|
|
29
|
-
if (!token || !/^[A-Za-z0-9_-]{20,100}$/.test(token))
|
|
30
|
-
|
|
31
|
+
if (!token || !/^[A-Za-z0-9_-]{20,100}$/.test(token))
|
|
32
|
+
throw new Stop('The Wavie link has no credential: keep #token=… inside the double quotes.');
|
|
33
|
+
if (url.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(url.hostname))
|
|
34
|
+
throw new Stop('The Wavie link must be https.');
|
|
31
35
|
return { api: url.origin, token };
|
|
32
36
|
}
|
|
33
37
|
|
|
@@ -39,7 +43,9 @@ export function computerName({ platform = process.platform, run = execFileSync,
|
|
|
39
43
|
try {
|
|
40
44
|
const name = String(run('scutil', ['--get', 'ComputerName'], { encoding: 'utf8', timeout: 5000 })).trim();
|
|
41
45
|
if (name) return name;
|
|
42
|
-
} catch {
|
|
46
|
+
} catch {
|
|
47
|
+
/* the host name below */
|
|
48
|
+
}
|
|
43
49
|
}
|
|
44
50
|
return host.replace(/\.local$/, '');
|
|
45
51
|
}
|
|
@@ -49,33 +55,65 @@ export function computerName({ platform = process.platform, run = execFileSync,
|
|
|
49
55
|
* (it works once: nothing that can fail locally comes after it but the service), the service installed and started.
|
|
50
56
|
* Resolves `{ service: reason }` when the service couldn't be installed.
|
|
51
57
|
*/
|
|
52
|
-
export async function link({
|
|
53
|
-
|
|
58
|
+
export async function link({
|
|
59
|
+
url,
|
|
60
|
+
home,
|
|
61
|
+
fetch = globalThis.fetch,
|
|
62
|
+
log = console.log,
|
|
63
|
+
status = claudeStatus,
|
|
64
|
+
find = findClaude,
|
|
65
|
+
installer = install,
|
|
66
|
+
platform = PLATFORM,
|
|
67
|
+
name = computerName(),
|
|
68
|
+
}) {
|
|
54
69
|
const { api, token } = parseLinkUrl(url);
|
|
55
70
|
const before = readLink(home);
|
|
56
|
-
if (before && before.api !== api)
|
|
71
|
+
if (before && before.api !== api)
|
|
72
|
+
throw new Stop(
|
|
73
|
+
`This computer is already connected to a different Wavie (${before.api}). Run heywavie disconnect first.`,
|
|
74
|
+
);
|
|
57
75
|
|
|
58
76
|
log('Checking Claude Code on this computer...');
|
|
59
77
|
const bin = find();
|
|
60
|
-
if (!bin)
|
|
78
|
+
if (!bin)
|
|
79
|
+
throw new Stop(
|
|
80
|
+
"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.",
|
|
81
|
+
);
|
|
61
82
|
const who = await status(bin);
|
|
62
|
-
if (!who.found)
|
|
63
|
-
|
|
83
|
+
if (!who.found)
|
|
84
|
+
throw new Stop(`Claude Code is installed but could not be run (${bin}). Reinstall it, then run this again.`);
|
|
85
|
+
if (!who.loggedIn)
|
|
86
|
+
throw new Stop(
|
|
87
|
+
"Claude Code is not signed in. Run 'claude auth login' in an interactive terminal, then run this again.",
|
|
88
|
+
);
|
|
64
89
|
|
|
65
90
|
const unwritable = canWrite(home);
|
|
66
|
-
if (unwritable)
|
|
91
|
+
if (unwritable)
|
|
92
|
+
throw new Stop(
|
|
93
|
+
`heywavie can't write its folder ${home} (${unwritable}). Approve writing there, then run this again: the link wasn't used.`,
|
|
94
|
+
);
|
|
67
95
|
|
|
68
96
|
const device = before?.device ?? newDevice();
|
|
69
97
|
let res;
|
|
70
98
|
try {
|
|
71
|
-
res = await fetch(`${api}/plans/claude/hosts`, {
|
|
72
|
-
|
|
99
|
+
res = await fetch(`${routesOf(api)}/plans/claude/hosts`, {
|
|
100
|
+
method: 'POST',
|
|
101
|
+
headers: { 'content-type': 'application/json', ...CLIENT_HEADER },
|
|
102
|
+
body: JSON.stringify({ token, device, platform, name: name.slice(0, 80), email: who.email, kind: who.kind }),
|
|
103
|
+
signal: AbortSignal.timeout(30_000),
|
|
104
|
+
});
|
|
73
105
|
} catch (err) {
|
|
74
|
-
throw new Stop(
|
|
106
|
+
throw new Stop(
|
|
107
|
+
`Failed to reach Wavie at ${api} (${err?.cause?.code ?? err?.message ?? err}). Check this computer's network, then run this again.`,
|
|
108
|
+
);
|
|
75
109
|
}
|
|
76
110
|
const body = await res.json().catch(() => ({}));
|
|
77
111
|
if (!res.ok) {
|
|
78
|
-
if (
|
|
112
|
+
if (res.status === 426) throw new Stop(updateLine(body));
|
|
113
|
+
if (body?.code === 'BAD_LINK')
|
|
114
|
+
throw new Stop(
|
|
115
|
+
'The link is expired, already used, or invalid. Get a new sentence from Wavie (Thinks with, Claude).',
|
|
116
|
+
);
|
|
79
117
|
throw new Stop(`Wavie refused the link (${res.status}${body?.message ? `: ${body.message}` : ''}).`);
|
|
80
118
|
}
|
|
81
119
|
writeLink(home, { api, device, key: body.key, claude: bin, name, linkedAt: new Date().toISOString() });
|
|
@@ -83,7 +121,9 @@ export async function link({ url, home, fetch = globalThis.fetch, log = console.
|
|
|
83
121
|
const service = await installer({ home });
|
|
84
122
|
log(`Claude on this computer is connected to Wavie${who.email ? ` (Claude Code signed in as ${who.email})` : ''}.`);
|
|
85
123
|
if (!service.ok) return { service: service.reason };
|
|
86
|
-
log(
|
|
124
|
+
log(
|
|
125
|
+
'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.',
|
|
126
|
+
);
|
|
87
127
|
return { service: null };
|
|
88
128
|
}
|
|
89
129
|
|
|
@@ -91,7 +131,11 @@ export async function link({ url, home, fetch = globalThis.fetch, log = console.
|
|
|
91
131
|
export async function disconnect({ home, fetch = globalThis.fetch, log = console.log, remover = uninstall }) {
|
|
92
132
|
const was = readLink(home);
|
|
93
133
|
if (was) {
|
|
94
|
-
await fetch(`${was.api}/plans/claude/host`, {
|
|
134
|
+
await fetch(`${routesOf(was.api)}/plans/claude/host`, {
|
|
135
|
+
method: 'DELETE',
|
|
136
|
+
headers: { authorization: `Bearer ${was.key}`, ...CLIENT_HEADER },
|
|
137
|
+
signal: AbortSignal.timeout(15_000),
|
|
138
|
+
}).catch(() => null);
|
|
95
139
|
}
|
|
96
140
|
await remover({ home, fromService: false });
|
|
97
141
|
forget(home);
|
|
@@ -99,15 +143,39 @@ export async function disconnect({ home, fetch = globalThis.fetch, log = console
|
|
|
99
143
|
}
|
|
100
144
|
|
|
101
145
|
/** How heywavie stands here: linked to what, the service, Claude Code, and whether Wavie still knows this computer. */
|
|
102
|
-
export async function status({
|
|
146
|
+
export async function status({
|
|
147
|
+
home,
|
|
148
|
+
fetch = globalThis.fetch,
|
|
149
|
+
state = serviceState,
|
|
150
|
+
find = findClaude,
|
|
151
|
+
who = claudeStatus,
|
|
152
|
+
}) {
|
|
103
153
|
const l = readLink(home);
|
|
104
154
|
const service = await state({ home });
|
|
105
155
|
const bin = find({ saved: l?.claude ?? null });
|
|
106
156
|
const claude = await who(bin);
|
|
107
157
|
let wavie = null;
|
|
108
158
|
if (l) {
|
|
109
|
-
const res = await fetch(`${l.api}/plans/claude/host`, {
|
|
110
|
-
|
|
159
|
+
const res = await fetch(`${routesOf(l.api)}/plans/claude/host`, {
|
|
160
|
+
headers: { authorization: `Bearer ${l.key}`, ...CLIENT_HEADER },
|
|
161
|
+
signal: AbortSignal.timeout(15_000),
|
|
162
|
+
}).catch(() => null);
|
|
163
|
+
wavie = !res
|
|
164
|
+
? 'unreachable'
|
|
165
|
+
: res.status === 401
|
|
166
|
+
? 'unlinked'
|
|
167
|
+
: res.status === 426
|
|
168
|
+
? updateLine(await res.json().catch(() => null))
|
|
169
|
+
: res.ok
|
|
170
|
+
? 'linked'
|
|
171
|
+
: `answered ${res.status}`;
|
|
111
172
|
}
|
|
112
|
-
return {
|
|
173
|
+
return {
|
|
174
|
+
linked: Boolean(l),
|
|
175
|
+
api: l?.api ?? null,
|
|
176
|
+
device: l?.device ?? null,
|
|
177
|
+
service,
|
|
178
|
+
claude: { bin, ...claude },
|
|
179
|
+
wavie,
|
|
180
|
+
};
|
|
113
181
|
}
|
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).`;
|