@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/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) => (windows
17
- ? [path.join(home, '.local', 'bin', 'claude.exe')]
18
- : [path.join(home, '.local/bin/claude'), path.join(home, '.claude/local/claude'), '/opt/homebrew/bin/claude', '/usr/local/bin/claude', '/usr/bin/claude']);
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({ env = process.env, home = os.homedir(), exists = existsSync, saved = null, windows = WINDOWS } = {}) {
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 ?? '').split(windows ? ';' : ':').filter(Boolean).map((dir) => path.join(dir, windows ? 'claude.exe' : 'claude'));
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 = { HOME: home, LANG: env.LANG || 'en_US.UTF-8', TMPDIR: env.TMPDIR ?? os.tmpdir(), DISABLE_AUTOUPDATER: '1' };
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 ['-p', ...(model ? ['--model', model] : []), ...(effort ? ['--effort', effort] : []), '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--input-format', 'stream-json',
76
- '--system-prompt-file', systemFile, '--tools', '', '--strict-mcp-config', '--mcp-config', mcpFile,
77
- '--allowedTools', 'mcp__wavie', '--permission-prompts', 'none', '--no-session-persistence', '--disable-slash-commands',
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', '', '--max-turns', String(maxSteps)];
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).then((s) => s.mtimeMs).catch(() => null);
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 }).then(() => { cleared += 1; }).catch(() => {});
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]) throw new Error('Not a turn of Wavie\'s.');
110
- if (typeof input.system !== 'string' || typeof input.prompt !== 'string' || !input.prompt.trim()) throw new Error('A turn with nothing to answer.');
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 files = (Array.isArray(input.files) ? input.files : []).slice(0, 10).map((f) => {
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('Not a turn of Wavie\'s.');
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 { tools: `${api}${tools[0]}`, events: `${api}${events[0]}`, system: input.system, prompt: input.prompt, files, maxSteps: steps, model, effort };
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'], { env: claudeEnv(env, home, bin, { user: os.userInfo().username }), cwd: os.tmpdir(), stdio: ['ignore', 'pipe', 'ignore'] });
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) => { out += 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 { st = JSON.parse(out.slice(out.indexOf('{'))); } catch { st = null; }
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({ found: true, loggedIn: st?.loggedIn === true, email: st?.email ?? st?.account?.email ?? null, kind: kind ? String(kind) : null });
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) throw new Error(String(res.status));
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({ type: 'text', text: `Attached: ${f.name}` },
155
- { type: f.mediaType === 'application/pdf' ? 'document' : 'image', source: { type: 'base64', media_type: f.mediaType, data } });
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({ bin, turn, fetch = globalThis.fetch, env = process.env, home = os.homedir(), ready = null, flushMs = 150, beatMs = 10_000,
181
- maxMs = 20 * 60_000, timeoutMs = 20_000 }) {
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(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); }, 5000).unref?.();
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, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) });
193
- if (res.status === 404) { stop(); return true; }
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) { if (await send({ lines: [] })) lastSent = Date.now(); }
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(bin, claudeArgs({ systemFile, mcpFile, maxSteps: turn.maxSteps, model, effort: turn.effort ?? null }), { cwd: dir, env: claudeEnv(env, home, bin, { user: os.userInfo().username }),
246
- stdio: ['pipe', 'pipe', 'pipe'] });
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) { pending.push(line); return; }
382
+ if (!held) {
383
+ pending.push(line);
384
+ return;
385
+ }
254
386
  let item = null;
255
- try { item = JSON.parse(line); } catch { /* not JSON: shown as it is */ }
256
- if (item?.type === 'system') { held.push(line); return; }
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))) { refused = true; held = null; return; }
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) => { errText = (errText + d).slice(-4000); });
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) => { errText = `${errText}\n${err?.message ?? err}`; resolve(-1); });
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,27 +1,44 @@
1
+ import { chatgptHere } from './chatgpt-relay.mjs';
1
2
  import { findClaude, runTurn, stopAll, turnOf } from './claude.mjs';
3
+ import { CLIENT_HEADER, routesOf, updateLine } from './wavie.mjs';
2
4
 
3
5
  /**
4
6
  * 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
+ * and runs each with Claude Code here (claude.mjs), a few at once; the rest wait their place. With ChatGPT signed in
8
+ * here it takes ChatGPT's calls too (chatgpt-relay.mjs). A key Wavie no longer knows (they unlinked it in Wavie) ends it:
9
+ * `onUnlinked` takes heywavie off this computer.
7
10
  */
8
11
 
9
12
  export const TURNS_MAX = 3;
10
13
  const WAIT_S = 20;
14
+ // How often the service asks Wavie whether ChatGPT is still connected (a disconnect on the web ends the sign-in here).
15
+ const CHATGPT_CHECK_MS = 5 * 60_000;
11
16
 
12
17
  const PLATFORM = { darwin: 'darwin', linux: 'linux', win32: 'win32' }[process.platform] ?? 'linux';
13
- const sleep = (ms, signal) => new Promise((resolve) => {
14
- if (signal?.aborted) return resolve();
15
- const t = setTimeout(resolve, ms);
16
- signal?.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
17
- });
18
+ const sleep = (ms, signal) =>
19
+ new Promise((resolve) => {
20
+ if (signal?.aborted) return resolve();
21
+ const t = setTimeout(resolve, ms);
22
+ signal?.addEventListener(
23
+ 'abort',
24
+ () => {
25
+ clearTimeout(t);
26
+ resolve();
27
+ },
28
+ { once: true },
29
+ );
30
+ });
18
31
  // 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) => new Promise((resolve) => {
20
- if (signal?.aborted) return resolve({});
21
- const stop = () => resolve({});
22
- signal?.addEventListener('abort', stop, { once: true });
23
- res.json().then(resolve, () => resolve({})).finally(() => signal?.removeEventListener('abort', stop));
24
- });
32
+ const bodyOf = (res, signal) =>
33
+ new Promise((resolve) => {
34
+ if (signal?.aborted) return resolve({});
35
+ const stop = () => resolve({});
36
+ signal?.addEventListener('abort', stop, { once: true });
37
+ res
38
+ .json()
39
+ .then(resolve, () => resolve({}))
40
+ .finally(() => signal?.removeEventListener('abort', stop));
41
+ });
25
42
 
26
43
  /** Turns running here at once, at most `max`: `place()` resolves when there is room, `free()` hands it on. */
27
44
  export function places(max = TURNS_MAX) {
@@ -41,21 +58,42 @@ export function places(max = TURNS_MAX) {
41
58
  * Runs until `signal` aborts or Wavie no longer knows this key. `log` gets one line per thing worth knowing; nothing of
42
59
  * a chat is ever in it.
43
60
  */
44
- export async function host({ link, fetch = globalThis.fetch, signal = null, log = console.log, onUnlinked = async () => {}, run = runTurn, find = findClaude,
45
- platform = PLATFORM, waitS = WAIT_S }) {
61
+ export async function host({
62
+ link,
63
+ fetch = globalThis.fetch,
64
+ signal = null,
65
+ log = console.log,
66
+ onUnlinked = async () => {},
67
+ run = runTurn,
68
+ find = findClaude,
69
+ platform = PLATFORM,
70
+ waitS = WAIT_S,
71
+ tooOldMs = 30 * 60_000,
72
+ home = null,
73
+ chatgpt = home ? chatgptHere({ home, link, fetch, log }) : null,
74
+ chatgptCheckMs = CHATGPT_CHECK_MS,
75
+ }) {
46
76
  const { api, device, key } = link;
47
- const headers = { authorization: `Bearer ${key}`, 'content-type': 'application/json' };
77
+ const headers = { authorization: `Bearer ${key}`, 'content-type': 'application/json', ...CLIENT_HEADER };
48
78
  const room = places();
49
79
  const turns = new Set();
50
80
  let backoff = 1000;
51
- const answer = (id, body) => fetch(`${api}/device/asks/${id}`, { method: 'POST', headers, body: JSON.stringify({ device, ...body }), signal: AbortSignal.timeout(20_000) })
52
- .catch(() => null);
81
+ const answer = (id, body) =>
82
+ fetch(`${routesOf(api)}/device/asks/${id}`, {
83
+ method: 'POST',
84
+ headers,
85
+ body: JSON.stringify({ device, ...body }),
86
+ signal: AbortSignal.timeout(20_000),
87
+ }).catch(() => null);
53
88
 
54
89
  const start = (ask) => {
55
90
  const bin = find({ saved: link.claude ?? null });
56
91
  if (!bin) {
57
92
  log("Claude Code isn't on this computer any more: install it again and sign in (claude auth login).");
58
- 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." });
93
+ return answer(ask.id, {
94
+ error:
95
+ "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.",
96
+ });
59
97
  }
60
98
  let turn;
61
99
  try {
@@ -64,19 +102,45 @@ export async function host({ link, fetch = globalThis.fetch, signal = null, log
64
102
  return answer(ask.id, { error: String(err?.message ?? err) });
65
103
  }
66
104
  const ready = room.place();
67
- const t = run({ bin, turn, ready }).then((code) => log(`turn ended (${code})`), (err) => log(`turn broke: ${err?.message ?? err}`))
68
- .finally(() => { void ready.then(room.free); turns.delete(t); });
105
+ const t = run({ bin, turn, ready })
106
+ .then(
107
+ (code) => log(`turn ended (${code})`),
108
+ (err) => log(`turn broke: ${err?.message ?? err}`),
109
+ )
110
+ .finally(() => {
111
+ void ready.then(room.free);
112
+ turns.delete(t);
113
+ });
69
114
  turns.add(t);
70
115
  log('turn started');
71
116
  return answer(ask.id, { answer: { started: true } });
72
117
  };
73
118
 
119
+ // ChatGPT's calls, relayed: not Claude Code's turns, so they take no place of theirs.
120
+ const relay = (ask) => {
121
+ const t = Promise.resolve(chatgpt.relay(ask, answer))
122
+ .catch((err) => log(`ChatGPT call broke: ${err?.message ?? err}`))
123
+ .finally(() => turns.delete(t));
124
+ turns.add(t);
125
+ };
126
+ let checkedAt = -Infinity;
127
+ // Linked again since ChatGPT signed in here: Wavie hears it by this key before the first wait.
128
+ await chatgpt?.announce?.().catch((err) => log(`ChatGPT couldn't be connected again: ${err?.message ?? err}`));
129
+
74
130
  log(`waiting for Wavie's turns at ${api}`);
75
131
  while (!signal?.aborted) {
132
+ if (chatgpt && Date.now() - checkedAt >= chatgptCheckMs) {
133
+ checkedAt = Date.now();
134
+ await chatgpt.check().catch(() => {});
135
+ }
76
136
  let res;
77
137
  try {
78
- const q = new URLSearchParams({ device, platform, can: 'claude', wait: String(waitS) });
79
- res = await fetch(`${api}/device/asks?${q}`, { headers, signal: AbortSignal.any([AbortSignal.timeout((waitS + 30) * 1000), ...(signal ? [signal] : [])]) });
138
+ const can = chatgpt?.signedIn() ? 'claude,chatgpt' : 'claude';
139
+ const q = new URLSearchParams({ device, platform, can, wait: String(waitS) });
140
+ res = await fetch(`${routesOf(api)}/device/asks?${q}`, {
141
+ headers,
142
+ signal: AbortSignal.any([AbortSignal.timeout((waitS + 30) * 1000), ...(signal ? [signal] : [])]),
143
+ });
80
144
  } catch (err) {
81
145
  if (signal?.aborted) break;
82
146
  log(`can't reach Wavie (${err?.cause?.code ?? err?.message ?? err}), trying again`);
@@ -87,10 +151,17 @@ export async function host({ link, fetch = globalThis.fetch, signal = null, log
87
151
  if (res.status === 401) {
88
152
  log('Wavie no longer knows this computer: it was unlinked in Wavie. Taking heywavie off it.');
89
153
  stopAll();
154
+ chatgpt?.stopAll();
90
155
  await Promise.allSettled([...turns]);
91
156
  await onUnlinked();
92
157
  return 'unlinked';
93
158
  }
159
+ // Too old for Wavie: nothing here can fix it, so say how and look again only now and then.
160
+ if (res.status === 426) {
161
+ log(updateLine(await bodyOf(res, signal)));
162
+ await sleep(tooOldMs, signal);
163
+ continue;
164
+ }
94
165
  if (!res.ok) {
95
166
  log(`Wavie answered ${res.status}, trying again`);
96
167
  await sleep(backoff, signal);
@@ -100,9 +171,13 @@ export async function host({ link, fetch = globalThis.fetch, signal = null, log
100
171
  backoff = 1000;
101
172
  const { asks = [] } = await bodyOf(res, signal);
102
173
  if (signal?.aborted) break;
103
- for (const ask of asks) if (ask?.ability === 'claude') await start(ask);
174
+ for (const ask of asks) {
175
+ if (ask?.ability === 'claude') await start(ask);
176
+ else if (ask?.ability === 'chatgpt' && chatgpt) relay(ask);
177
+ }
104
178
  }
105
179
  stopAll();
180
+ chatgpt?.stopAll();
106
181
  await Promise.allSettled([...turns]);
107
182
  return 'stopped';
108
183
  }