@zhigang1992/happy-cli 0.12.1

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.
Files changed (47) hide show
  1. package/README.md +60 -0
  2. package/bin/happy-mcp.mjs +32 -0
  3. package/bin/happy.mjs +35 -0
  4. package/dist/codex/happyMcpStdioBridge.cjs +80 -0
  5. package/dist/codex/happyMcpStdioBridge.d.cts +2 -0
  6. package/dist/codex/happyMcpStdioBridge.d.mts +2 -0
  7. package/dist/codex/happyMcpStdioBridge.mjs +78 -0
  8. package/dist/index-BOBrKhX5.cjs +6655 -0
  9. package/dist/index-DsHtmQqP.mjs +6624 -0
  10. package/dist/index.cjs +42 -0
  11. package/dist/index.d.cts +1 -0
  12. package/dist/index.d.mts +1 -0
  13. package/dist/index.mjs +39 -0
  14. package/dist/lib.cjs +31 -0
  15. package/dist/lib.d.cts +817 -0
  16. package/dist/lib.d.mts +817 -0
  17. package/dist/lib.mjs +21 -0
  18. package/dist/list-BW6QBLa1.cjs +328 -0
  19. package/dist/list-hET5tyMc.mjs +326 -0
  20. package/dist/prompt-DXkgjktW.cjs +203 -0
  21. package/dist/prompt-Dz7G8yGx.mjs +201 -0
  22. package/dist/runCodex-CLGYMNs2.mjs +1335 -0
  23. package/dist/runCodex-CylcX5Ug.cjs +1338 -0
  24. package/dist/types-BsjUgWOx.cjs +2264 -0
  25. package/dist/types-CGco5Y-r.mjs +2213 -0
  26. package/package.json +126 -0
  27. package/scripts/claude_local_launcher.cjs +98 -0
  28. package/scripts/claude_remote_launcher.cjs +13 -0
  29. package/scripts/ripgrep_launcher.cjs +33 -0
  30. package/scripts/unpack-tools.cjs +163 -0
  31. package/tools/archives/difftastic-LICENSE +21 -0
  32. package/tools/archives/difftastic-arm64-darwin.tar.gz +0 -0
  33. package/tools/archives/difftastic-arm64-linux.tar.gz +0 -0
  34. package/tools/archives/difftastic-x64-darwin.tar.gz +0 -0
  35. package/tools/archives/difftastic-x64-linux.tar.gz +0 -0
  36. package/tools/archives/difftastic-x64-win32.tar.gz +0 -0
  37. package/tools/archives/ripgrep-LICENSE +3 -0
  38. package/tools/archives/ripgrep-arm64-darwin.tar.gz +0 -0
  39. package/tools/archives/ripgrep-arm64-linux.tar.gz +0 -0
  40. package/tools/archives/ripgrep-x64-darwin.tar.gz +0 -0
  41. package/tools/archives/ripgrep-x64-linux.tar.gz +0 -0
  42. package/tools/archives/ripgrep-x64-win32.tar.gz +0 -0
  43. package/tools/licenses/difftastic-LICENSE +21 -0
  44. package/tools/licenses/ripgrep-LICENSE +3 -0
  45. package/tools/unpacked/difft +0 -0
  46. package/tools/unpacked/rg +0 -0
  47. package/tools/unpacked/ripgrep.node +0 -0
@@ -0,0 +1,2213 @@
1
+ import axios from 'axios';
2
+ import chalk from 'chalk';
3
+ import { appendFileSync } from 'fs';
4
+ import { existsSync, mkdirSync, constants, readFileSync, unlinkSync, writeFileSync, readdirSync, statSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { join, basename } from 'node:path';
7
+ import { readFile, open, stat, unlink, mkdir, writeFile, rename } from 'node:fs/promises';
8
+ import * as z from 'zod';
9
+ import { z as z$1 } from 'zod';
10
+ import { createHash, createDecipheriv, createCipheriv, randomBytes, randomUUID } from 'node:crypto';
11
+ import tweetnacl from 'tweetnacl';
12
+ import { EventEmitter } from 'node:events';
13
+ import { io } from 'socket.io-client';
14
+ import { spawn, exec } from 'child_process';
15
+ import { promisify } from 'util';
16
+ import { readFile as readFile$1, stat as stat$1, writeFile as writeFile$1, readdir } from 'fs/promises';
17
+ import { createHash as createHash$1 } from 'crypto';
18
+ import { dirname, resolve, join as join$1 } from 'path';
19
+ import { fileURLToPath } from 'url';
20
+ import { platform } from 'os';
21
+ import { Expo } from 'expo-server-sdk';
22
+
23
+ var name = "@zhigang1992/happy-cli";
24
+ var version = "0.12.1";
25
+ var description = "Mobile and Web client for Claude Code and Codex";
26
+ var author = "Kirill Dubovitskiy";
27
+ var license = "MIT";
28
+ var type = "module";
29
+ var homepage = "https://github.com/slopus/happy-cli";
30
+ var bugs = "https://github.com/slopus/happy-cli/issues";
31
+ var repository = "slopus/happy-cli";
32
+ var bin = {
33
+ happy: "./bin/happy.mjs",
34
+ "happy-mcp": "./bin/happy-mcp.mjs"
35
+ };
36
+ var main = "./dist/index.cjs";
37
+ var module = "./dist/index.mjs";
38
+ var types = "./dist/index.d.cts";
39
+ var exports = {
40
+ ".": {
41
+ require: {
42
+ types: "./dist/index.d.cts",
43
+ "default": "./dist/index.cjs"
44
+ },
45
+ "import": {
46
+ types: "./dist/index.d.mts",
47
+ "default": "./dist/index.mjs"
48
+ }
49
+ },
50
+ "./lib": {
51
+ require: {
52
+ types: "./dist/lib.d.cts",
53
+ "default": "./dist/lib.cjs"
54
+ },
55
+ "import": {
56
+ types: "./dist/lib.d.mts",
57
+ "default": "./dist/lib.mjs"
58
+ }
59
+ },
60
+ "./codex/happyMcpStdioBridge": {
61
+ require: {
62
+ types: "./dist/codex/happyMcpStdioBridge.d.cts",
63
+ "default": "./dist/codex/happyMcpStdioBridge.cjs"
64
+ },
65
+ "import": {
66
+ types: "./dist/codex/happyMcpStdioBridge.d.mts",
67
+ "default": "./dist/codex/happyMcpStdioBridge.mjs"
68
+ }
69
+ }
70
+ };
71
+ var files = [
72
+ "dist",
73
+ "bin",
74
+ "scripts",
75
+ "tools",
76
+ "package.json"
77
+ ];
78
+ var scripts = {
79
+ "why do we need to build before running tests / dev?": "We need the binary to be built so we run daemon commands which directly run the binary - we don't want them to go out of sync or have custom spawn logic depending how we started happy",
80
+ typecheck: "tsc --noEmit",
81
+ build: "shx rm -rf dist && npx tsc --noEmit && pkgroll",
82
+ test: "yarn build && tsx --env-file .env.integration-test node_modules/.bin/vitest run",
83
+ start: "yarn build && ./bin/happy.mjs",
84
+ dev: "tsx src/index.ts",
85
+ "dev:local-server": "yarn build && tsx --env-file .env.dev-local-server src/index.ts",
86
+ "dev:integration-test-env": "yarn build && tsx --env-file .env.integration-test src/index.ts",
87
+ prepublishOnly: "yarn build && yarn test",
88
+ release: "release-it",
89
+ postinstall: "node scripts/unpack-tools.cjs"
90
+ };
91
+ var dependencies = {
92
+ "@anthropic-ai/claude-code": "2.0.55",
93
+ "@anthropic-ai/sdk": "0.65.0",
94
+ "@elevenlabs/elevenlabs-js": "^2.25.1",
95
+ "@modelcontextprotocol/sdk": "^1.15.1",
96
+ "@stablelib/base64": "^2.0.1",
97
+ "@stablelib/hex": "^2.0.1",
98
+ "@types/cross-spawn": "^6.0.6",
99
+ "@types/http-proxy": "^1.17.16",
100
+ "@types/ps-list": "^6.2.1",
101
+ "@types/qrcode-terminal": "^0.12.2",
102
+ "@types/react": "^19.1.9",
103
+ "@types/tmp": "^0.2.6",
104
+ axios: "^1.10.0",
105
+ chalk: "^5.4.1",
106
+ "cross-spawn": "^7.0.6",
107
+ "expo-server-sdk": "^3.15.0",
108
+ fastify: "^5.5.0",
109
+ "fastify-type-provider-zod": "4.0.2",
110
+ "http-proxy": "^1.18.1",
111
+ "http-proxy-middleware": "^3.0.5",
112
+ ink: "^6.1.0",
113
+ open: "^10.2.0",
114
+ "ps-list": "^8.1.1",
115
+ "qrcode-terminal": "^0.12.0",
116
+ react: "^19.1.1",
117
+ "socket.io-client": "^4.8.1",
118
+ tar: "^7.4.3",
119
+ tmp: "^0.2.5",
120
+ tweetnacl: "^1.0.3",
121
+ zod: "^3.23.8"
122
+ };
123
+ var devDependencies = {
124
+ "@eslint/compat": "^1",
125
+ "@types/node": ">=20",
126
+ "cross-env": "^10.0.0",
127
+ dotenv: "^16.6.1",
128
+ eslint: "^9",
129
+ "eslint-config-prettier": "^10",
130
+ pkgroll: "^2.14.2",
131
+ "release-it": "^19.0.4",
132
+ shx: "^0.3.3",
133
+ "ts-node": "^10",
134
+ tsx: "^4.20.3",
135
+ typescript: "^5",
136
+ vitest: "^3.2.4"
137
+ };
138
+ var resolutions = {
139
+ "whatwg-url": "14.2.0",
140
+ "parse-path": "7.0.3",
141
+ "@types/parse-path": "7.0.3"
142
+ };
143
+ var publishConfig = {
144
+ registry: "https://registry.npmjs.org"
145
+ };
146
+ var packageManager = "yarn@1.22.22";
147
+ var packageJson = {
148
+ name: name,
149
+ version: version,
150
+ description: description,
151
+ author: author,
152
+ license: license,
153
+ type: type,
154
+ homepage: homepage,
155
+ bugs: bugs,
156
+ repository: repository,
157
+ bin: bin,
158
+ main: main,
159
+ module: module,
160
+ types: types,
161
+ exports: exports,
162
+ files: files,
163
+ scripts: scripts,
164
+ dependencies: dependencies,
165
+ devDependencies: devDependencies,
166
+ resolutions: resolutions,
167
+ publishConfig: publishConfig,
168
+ packageManager: packageManager
169
+ };
170
+
171
+ class Configuration {
172
+ serverUrl;
173
+ webappUrl;
174
+ isDaemonProcess;
175
+ // Directories and paths (from persistence)
176
+ happyHomeDir;
177
+ logsDir;
178
+ settingsFile;
179
+ privateKeyFile;
180
+ daemonStateFile;
181
+ daemonLockFile;
182
+ currentCliVersion;
183
+ isExperimentalEnabled;
184
+ disableCaffeinate;
185
+ constructor() {
186
+ this.serverUrl = process.env.HAPPY_SERVER_URL || "https://api.cluster-fluster.com";
187
+ this.webappUrl = process.env.HAPPY_WEBAPP_URL || "https://app.happy.engineering";
188
+ const args = process.argv.slice(2);
189
+ this.isDaemonProcess = args.length >= 2 && args[0] === "daemon" && args[1] === "start-sync";
190
+ if (process.env.HAPPY_HOME_DIR) {
191
+ const expandedPath = process.env.HAPPY_HOME_DIR.replace(/^~/, homedir());
192
+ this.happyHomeDir = expandedPath;
193
+ } else {
194
+ this.happyHomeDir = join(homedir(), ".happy");
195
+ }
196
+ this.logsDir = join(this.happyHomeDir, "logs");
197
+ this.settingsFile = join(this.happyHomeDir, "settings.json");
198
+ this.privateKeyFile = join(this.happyHomeDir, "access.key");
199
+ this.daemonStateFile = join(this.happyHomeDir, "daemon.state.json");
200
+ this.daemonLockFile = join(this.happyHomeDir, "daemon.state.json.lock");
201
+ this.isExperimentalEnabled = ["true", "1", "yes"].includes(process.env.HAPPY_EXPERIMENTAL?.toLowerCase() || "");
202
+ this.disableCaffeinate = ["true", "1", "yes"].includes(process.env.HAPPY_DISABLE_CAFFEINATE?.toLowerCase() || "");
203
+ this.currentCliVersion = packageJson.version;
204
+ if (!existsSync(this.happyHomeDir)) {
205
+ mkdirSync(this.happyHomeDir, { recursive: true });
206
+ }
207
+ if (!existsSync(this.logsDir)) {
208
+ mkdirSync(this.logsDir, { recursive: true });
209
+ }
210
+ }
211
+ }
212
+ const configuration = new Configuration();
213
+
214
+ function encodeBase64(buffer, variant = "base64") {
215
+ if (variant === "base64url") {
216
+ return encodeBase64Url(buffer);
217
+ }
218
+ return Buffer.from(buffer).toString("base64");
219
+ }
220
+ function encodeBase64Url(buffer) {
221
+ return Buffer.from(buffer).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
222
+ }
223
+ function decodeBase64(base64, variant = "base64") {
224
+ if (variant === "base64url") {
225
+ const base64Standard = base64.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - base64.length % 4) % 4);
226
+ return new Uint8Array(Buffer.from(base64Standard, "base64"));
227
+ }
228
+ return new Uint8Array(Buffer.from(base64, "base64"));
229
+ }
230
+ function getRandomBytes(size) {
231
+ return new Uint8Array(randomBytes(size));
232
+ }
233
+ function derivePublicKeyFromSeed(seed) {
234
+ const hash = createHash("sha512").update(seed).digest();
235
+ const secretKey = new Uint8Array(hash.slice(0, 32));
236
+ const keypair = tweetnacl.box.keyPair.fromSecretKey(secretKey);
237
+ return keypair.publicKey;
238
+ }
239
+ function libsodiumEncryptForPublicKey(data, recipientPublicKey) {
240
+ const ephemeralKeyPair = tweetnacl.box.keyPair();
241
+ const nonce = getRandomBytes(tweetnacl.box.nonceLength);
242
+ const encrypted = tweetnacl.box(data, nonce, recipientPublicKey, ephemeralKeyPair.secretKey);
243
+ const result = new Uint8Array(ephemeralKeyPair.publicKey.length + nonce.length + encrypted.length);
244
+ result.set(ephemeralKeyPair.publicKey, 0);
245
+ result.set(nonce, ephemeralKeyPair.publicKey.length);
246
+ result.set(encrypted, ephemeralKeyPair.publicKey.length + nonce.length);
247
+ return result;
248
+ }
249
+ function libsodiumDecryptFromPublicKey(encryptedBundle, recipientSecretKey) {
250
+ if (encryptedBundle.length < 32 + 24) {
251
+ return null;
252
+ }
253
+ const ephemeralPublicKey = encryptedBundle.slice(0, 32);
254
+ const nonce = encryptedBundle.slice(32, 56);
255
+ const encrypted = encryptedBundle.slice(56);
256
+ const decrypted = tweetnacl.box.open(encrypted, nonce, ephemeralPublicKey, recipientSecretKey);
257
+ return decrypted || null;
258
+ }
259
+ function encryptLegacy(data, secret) {
260
+ const nonce = getRandomBytes(tweetnacl.secretbox.nonceLength);
261
+ const encrypted = tweetnacl.secretbox(new TextEncoder().encode(JSON.stringify(data)), nonce, secret);
262
+ const result = new Uint8Array(nonce.length + encrypted.length);
263
+ result.set(nonce);
264
+ result.set(encrypted, nonce.length);
265
+ return result;
266
+ }
267
+ function decryptLegacy(data, secret) {
268
+ const nonce = data.slice(0, tweetnacl.secretbox.nonceLength);
269
+ const encrypted = data.slice(tweetnacl.secretbox.nonceLength);
270
+ const decrypted = tweetnacl.secretbox.open(encrypted, nonce, secret);
271
+ if (!decrypted) {
272
+ return null;
273
+ }
274
+ return JSON.parse(new TextDecoder().decode(decrypted));
275
+ }
276
+ function encryptWithDataKey(data, dataKey) {
277
+ const nonce = getRandomBytes(12);
278
+ const cipher = createCipheriv("aes-256-gcm", dataKey, nonce);
279
+ const plaintext = new TextEncoder().encode(JSON.stringify(data));
280
+ const encrypted = Buffer.concat([
281
+ cipher.update(plaintext),
282
+ cipher.final()
283
+ ]);
284
+ const authTag = cipher.getAuthTag();
285
+ const bundle = new Uint8Array(12 + encrypted.length + 16 + 1);
286
+ bundle.set([0], 0);
287
+ bundle.set(nonce, 1);
288
+ bundle.set(new Uint8Array(encrypted), 13);
289
+ bundle.set(new Uint8Array(authTag), 13 + encrypted.length);
290
+ return bundle;
291
+ }
292
+ function decryptWithDataKey(bundle, dataKey) {
293
+ if (bundle.length < 1) {
294
+ return null;
295
+ }
296
+ if (bundle[0] !== 0) {
297
+ return null;
298
+ }
299
+ if (bundle.length < 12 + 16 + 1) {
300
+ return null;
301
+ }
302
+ const nonce = bundle.slice(1, 13);
303
+ const authTag = bundle.slice(bundle.length - 16);
304
+ const ciphertext = bundle.slice(13, bundle.length - 16);
305
+ try {
306
+ const decipher = createDecipheriv("aes-256-gcm", dataKey, nonce);
307
+ decipher.setAuthTag(authTag);
308
+ const decrypted = Buffer.concat([
309
+ decipher.update(ciphertext),
310
+ decipher.final()
311
+ ]);
312
+ return JSON.parse(new TextDecoder().decode(decrypted));
313
+ } catch (error) {
314
+ return null;
315
+ }
316
+ }
317
+ function encrypt(key, variant, data) {
318
+ if (variant === "legacy") {
319
+ return encryptLegacy(data, key);
320
+ } else {
321
+ return encryptWithDataKey(data, key);
322
+ }
323
+ }
324
+ function decrypt(key, variant, data) {
325
+ if (variant === "legacy") {
326
+ return decryptLegacy(data, key);
327
+ } else {
328
+ return decryptWithDataKey(data, key);
329
+ }
330
+ }
331
+ function authChallenge(secret) {
332
+ const keypair = tweetnacl.sign.keyPair.fromSeed(secret);
333
+ const challenge = getRandomBytes(32);
334
+ const signature = tweetnacl.sign.detached(challenge, keypair.secretKey);
335
+ return {
336
+ challenge,
337
+ publicKey: keypair.publicKey,
338
+ signature
339
+ };
340
+ }
341
+
342
+ const defaultSettings = {
343
+ onboardingCompleted: false
344
+ };
345
+ async function readSettings() {
346
+ if (!existsSync(configuration.settingsFile)) {
347
+ return { ...defaultSettings };
348
+ }
349
+ try {
350
+ const content = await readFile(configuration.settingsFile, "utf8");
351
+ return JSON.parse(content);
352
+ } catch {
353
+ return { ...defaultSettings };
354
+ }
355
+ }
356
+ async function updateSettings(updater) {
357
+ const LOCK_RETRY_INTERVAL_MS = 100;
358
+ const MAX_LOCK_ATTEMPTS = 50;
359
+ const STALE_LOCK_TIMEOUT_MS = 1e4;
360
+ const lockFile = configuration.settingsFile + ".lock";
361
+ const tmpFile = configuration.settingsFile + ".tmp";
362
+ let fileHandle;
363
+ let attempts = 0;
364
+ while (attempts < MAX_LOCK_ATTEMPTS) {
365
+ try {
366
+ fileHandle = await open(lockFile, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY);
367
+ break;
368
+ } catch (err) {
369
+ if (err.code === "EEXIST") {
370
+ attempts++;
371
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
372
+ try {
373
+ const stats = await stat(lockFile);
374
+ if (Date.now() - stats.mtimeMs > STALE_LOCK_TIMEOUT_MS) {
375
+ await unlink(lockFile).catch(() => {
376
+ });
377
+ }
378
+ } catch {
379
+ }
380
+ } else {
381
+ throw err;
382
+ }
383
+ }
384
+ }
385
+ if (!fileHandle) {
386
+ throw new Error(`Failed to acquire settings lock after ${MAX_LOCK_ATTEMPTS * LOCK_RETRY_INTERVAL_MS / 1e3} seconds`);
387
+ }
388
+ try {
389
+ const current = await readSettings() || { ...defaultSettings };
390
+ const updated = await updater(current);
391
+ if (!existsSync(configuration.happyHomeDir)) {
392
+ await mkdir(configuration.happyHomeDir, { recursive: true });
393
+ }
394
+ await writeFile(tmpFile, JSON.stringify(updated, null, 2));
395
+ await rename(tmpFile, configuration.settingsFile);
396
+ return updated;
397
+ } finally {
398
+ await fileHandle.close();
399
+ await unlink(lockFile).catch(() => {
400
+ });
401
+ }
402
+ }
403
+ const credentialsSchema = z.object({
404
+ token: z.string(),
405
+ secret: z.string().base64().nullish(),
406
+ // Legacy
407
+ encryption: z.object({
408
+ publicKey: z.string().base64(),
409
+ // Actually a seed, not a public key (legacy naming)
410
+ machineKey: z.string().base64()
411
+ }).nullish()
412
+ });
413
+ async function readCredentials() {
414
+ if (!existsSync(configuration.privateKeyFile)) {
415
+ return null;
416
+ }
417
+ try {
418
+ const keyBase64 = await readFile(configuration.privateKeyFile, "utf8");
419
+ const credentials = credentialsSchema.parse(JSON.parse(keyBase64));
420
+ if (credentials.secret) {
421
+ return {
422
+ token: credentials.token,
423
+ encryption: {
424
+ type: "legacy",
425
+ secret: new Uint8Array(Buffer.from(credentials.secret, "base64"))
426
+ }
427
+ };
428
+ } else if (credentials.encryption) {
429
+ return {
430
+ token: credentials.token,
431
+ encryption: {
432
+ type: "dataKey",
433
+ // Map file's "publicKey" field to properly named "dataKeySeed" in memory
434
+ dataKeySeed: new Uint8Array(Buffer.from(credentials.encryption.publicKey, "base64")),
435
+ machineKey: new Uint8Array(Buffer.from(credentials.encryption.machineKey, "base64"))
436
+ }
437
+ };
438
+ }
439
+ } catch {
440
+ return null;
441
+ }
442
+ return null;
443
+ }
444
+ async function writeCredentialsLegacy(credentials) {
445
+ if (!existsSync(configuration.happyHomeDir)) {
446
+ await mkdir(configuration.happyHomeDir, { recursive: true });
447
+ }
448
+ await writeFile(configuration.privateKeyFile, JSON.stringify({
449
+ secret: encodeBase64(credentials.secret),
450
+ token: credentials.token
451
+ }, null, 2));
452
+ }
453
+ async function writeCredentialsDataKey(credentials) {
454
+ if (!existsSync(configuration.happyHomeDir)) {
455
+ await mkdir(configuration.happyHomeDir, { recursive: true });
456
+ }
457
+ await writeFile(configuration.privateKeyFile, JSON.stringify({
458
+ encryption: { publicKey: encodeBase64(credentials.dataKeySeed), machineKey: encodeBase64(credentials.machineKey) },
459
+ token: credentials.token
460
+ }, null, 2));
461
+ }
462
+ async function clearCredentials() {
463
+ if (existsSync(configuration.privateKeyFile)) {
464
+ await unlink(configuration.privateKeyFile);
465
+ }
466
+ }
467
+ async function clearMachineId() {
468
+ await updateSettings((settings) => ({
469
+ ...settings,
470
+ machineId: void 0
471
+ }));
472
+ }
473
+ async function readDaemonState() {
474
+ try {
475
+ if (!existsSync(configuration.daemonStateFile)) {
476
+ return null;
477
+ }
478
+ const content = await readFile(configuration.daemonStateFile, "utf-8");
479
+ return JSON.parse(content);
480
+ } catch (error) {
481
+ console.error(`[PERSISTENCE] Daemon state file corrupted: ${configuration.daemonStateFile}`, error);
482
+ return null;
483
+ }
484
+ }
485
+ function writeDaemonState(state) {
486
+ writeFileSync(configuration.daemonStateFile, JSON.stringify(state, null, 2), "utf-8");
487
+ }
488
+ async function clearDaemonState() {
489
+ if (existsSync(configuration.daemonStateFile)) {
490
+ await unlink(configuration.daemonStateFile);
491
+ }
492
+ if (existsSync(configuration.daemonLockFile)) {
493
+ try {
494
+ await unlink(configuration.daemonLockFile);
495
+ } catch {
496
+ }
497
+ }
498
+ }
499
+ async function acquireDaemonLock(maxAttempts = 5, delayIncrementMs = 200) {
500
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
501
+ try {
502
+ const fileHandle = await open(
503
+ configuration.daemonLockFile,
504
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY
505
+ );
506
+ await fileHandle.writeFile(String(process.pid));
507
+ return fileHandle;
508
+ } catch (error) {
509
+ if (error.code === "EEXIST") {
510
+ try {
511
+ const lockPid = readFileSync(configuration.daemonLockFile, "utf-8").trim();
512
+ if (lockPid && !isNaN(Number(lockPid))) {
513
+ try {
514
+ process.kill(Number(lockPid), 0);
515
+ } catch {
516
+ unlinkSync(configuration.daemonLockFile);
517
+ continue;
518
+ }
519
+ }
520
+ } catch {
521
+ }
522
+ }
523
+ if (attempt === maxAttempts) {
524
+ return null;
525
+ }
526
+ const delayMs = attempt * delayIncrementMs;
527
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
528
+ }
529
+ }
530
+ return null;
531
+ }
532
+ async function releaseDaemonLock(lockHandle) {
533
+ try {
534
+ await lockHandle.close();
535
+ } catch {
536
+ }
537
+ try {
538
+ if (existsSync(configuration.daemonLockFile)) {
539
+ unlinkSync(configuration.daemonLockFile);
540
+ }
541
+ } catch {
542
+ }
543
+ }
544
+
545
+ function createTimestampForFilename(date = /* @__PURE__ */ new Date()) {
546
+ return date.toLocaleString("sv-SE", {
547
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
548
+ year: "numeric",
549
+ month: "2-digit",
550
+ day: "2-digit",
551
+ hour: "2-digit",
552
+ minute: "2-digit",
553
+ second: "2-digit"
554
+ }).replace(/[: ]/g, "-").replace(/,/g, "") + "-pid-" + process.pid;
555
+ }
556
+ function createTimestampForLogEntry(date = /* @__PURE__ */ new Date()) {
557
+ return date.toLocaleTimeString("en-US", {
558
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
559
+ hour12: false,
560
+ hour: "2-digit",
561
+ minute: "2-digit",
562
+ second: "2-digit",
563
+ fractionalSecondDigits: 3
564
+ });
565
+ }
566
+ function getSessionLogPath() {
567
+ const timestamp = createTimestampForFilename();
568
+ const filename = configuration.isDaemonProcess ? `${timestamp}-daemon.log` : `${timestamp}.log`;
569
+ return join(configuration.logsDir, filename);
570
+ }
571
+ class Logger {
572
+ constructor(logFilePath = getSessionLogPath()) {
573
+ this.logFilePath = logFilePath;
574
+ if (process.env.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING && process.env.HAPPY_SERVER_URL) {
575
+ this.dangerouslyUnencryptedServerLoggingUrl = process.env.HAPPY_SERVER_URL;
576
+ console.log(chalk.yellow("[REMOTE LOGGING] Sending logs to server for AI debugging"));
577
+ }
578
+ }
579
+ dangerouslyUnencryptedServerLoggingUrl;
580
+ // Use local timezone for simplicity of locating the logs,
581
+ // in practice you will not need absolute timestamps
582
+ localTimezoneTimestamp() {
583
+ return createTimestampForLogEntry();
584
+ }
585
+ debug(message, ...args) {
586
+ this.logToFile(`[${this.localTimezoneTimestamp()}]`, message, ...args);
587
+ }
588
+ debugLargeJson(message, object, maxStringLength = 100, maxArrayLength = 10) {
589
+ if (!process.env.DEBUG) {
590
+ this.debug(`In production, skipping message inspection`);
591
+ }
592
+ const truncateStrings = (obj) => {
593
+ if (typeof obj === "string") {
594
+ return obj.length > maxStringLength ? obj.substring(0, maxStringLength) + "... [truncated for logs]" : obj;
595
+ }
596
+ if (Array.isArray(obj)) {
597
+ const truncatedArray = obj.map((item) => truncateStrings(item)).slice(0, maxArrayLength);
598
+ if (obj.length > maxArrayLength) {
599
+ truncatedArray.push(`... [truncated array for logs up to ${maxArrayLength} items]`);
600
+ }
601
+ return truncatedArray;
602
+ }
603
+ if (obj && typeof obj === "object") {
604
+ const result = {};
605
+ for (const [key, value] of Object.entries(obj)) {
606
+ if (key === "usage") {
607
+ continue;
608
+ }
609
+ result[key] = truncateStrings(value);
610
+ }
611
+ return result;
612
+ }
613
+ return obj;
614
+ };
615
+ const truncatedObject = truncateStrings(object);
616
+ const json = JSON.stringify(truncatedObject, null, 2);
617
+ this.logToFile(`[${this.localTimezoneTimestamp()}]`, message, "\n", json);
618
+ }
619
+ info(message, ...args) {
620
+ this.logToConsole("info", "", message, ...args);
621
+ this.debug(message, args);
622
+ }
623
+ infoDeveloper(message, ...args) {
624
+ this.debug(message, ...args);
625
+ if (process.env.DEBUG) {
626
+ this.logToConsole("info", "[DEV]", message, ...args);
627
+ }
628
+ }
629
+ warn(message, ...args) {
630
+ this.logToConsole("warn", "", message, ...args);
631
+ this.debug(`[WARN] ${message}`, ...args);
632
+ }
633
+ getLogPath() {
634
+ return this.logFilePath;
635
+ }
636
+ logToConsole(level, prefix, message, ...args) {
637
+ switch (level) {
638
+ case "debug": {
639
+ console.log(chalk.gray(prefix), message, ...args);
640
+ break;
641
+ }
642
+ case "error": {
643
+ console.error(chalk.red(prefix), message, ...args);
644
+ break;
645
+ }
646
+ case "info": {
647
+ console.log(chalk.blue(prefix), message, ...args);
648
+ break;
649
+ }
650
+ case "warn": {
651
+ console.log(chalk.yellow(prefix), message, ...args);
652
+ break;
653
+ }
654
+ default: {
655
+ this.debug("Unknown log level:", level);
656
+ console.log(chalk.blue(prefix), message, ...args);
657
+ break;
658
+ }
659
+ }
660
+ }
661
+ async sendToRemoteServer(level, message, ...args) {
662
+ if (!this.dangerouslyUnencryptedServerLoggingUrl) return;
663
+ try {
664
+ await fetch(this.dangerouslyUnencryptedServerLoggingUrl + "/logs-combined-from-cli-and-mobile-for-simple-ai-debugging", {
665
+ method: "POST",
666
+ headers: { "Content-Type": "application/json" },
667
+ body: JSON.stringify({
668
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
669
+ level,
670
+ message: `${message} ${args.map(
671
+ (a) => typeof a === "object" ? JSON.stringify(a, null, 2) : String(a)
672
+ ).join(" ")}`,
673
+ source: "cli",
674
+ platform: process.platform
675
+ })
676
+ });
677
+ } catch (error) {
678
+ }
679
+ }
680
+ logToFile(prefix, message, ...args) {
681
+ const logLine = `${prefix} ${message} ${args.map(
682
+ (arg) => typeof arg === "string" ? arg : JSON.stringify(arg)
683
+ ).join(" ")}
684
+ `;
685
+ if (this.dangerouslyUnencryptedServerLoggingUrl) {
686
+ let level = "info";
687
+ if (prefix.includes(this.localTimezoneTimestamp())) {
688
+ level = "debug";
689
+ }
690
+ this.sendToRemoteServer(level, message, ...args).catch(() => {
691
+ });
692
+ }
693
+ try {
694
+ appendFileSync(this.logFilePath, logLine);
695
+ } catch (appendError) {
696
+ if (process.env.DEBUG) {
697
+ console.error("[DEV MODE ONLY THROWING] Failed to append to log file:", appendError);
698
+ throw appendError;
699
+ }
700
+ }
701
+ }
702
+ }
703
+ let logger = new Logger();
704
+ async function listDaemonLogFiles(limit = 50) {
705
+ try {
706
+ const logsDir = configuration.logsDir;
707
+ if (!existsSync(logsDir)) {
708
+ return [];
709
+ }
710
+ const logs = readdirSync(logsDir).filter((file) => file.endsWith("-daemon.log")).map((file) => {
711
+ const fullPath = join(logsDir, file);
712
+ const stats = statSync(fullPath);
713
+ return { file, path: fullPath, modified: stats.mtime };
714
+ }).sort((a, b) => b.modified.getTime() - a.modified.getTime());
715
+ try {
716
+ const state = await readDaemonState();
717
+ if (!state) {
718
+ return logs;
719
+ }
720
+ if (state.daemonLogPath && existsSync(state.daemonLogPath)) {
721
+ const stats = statSync(state.daemonLogPath);
722
+ const persisted = {
723
+ file: basename(state.daemonLogPath),
724
+ path: state.daemonLogPath,
725
+ modified: stats.mtime
726
+ };
727
+ const idx = logs.findIndex((l) => l.path === persisted.path);
728
+ if (idx >= 0) {
729
+ const [found] = logs.splice(idx, 1);
730
+ logs.unshift(found);
731
+ } else {
732
+ logs.unshift(persisted);
733
+ }
734
+ }
735
+ } catch {
736
+ }
737
+ return logs.slice(0, Math.max(0, limit));
738
+ } catch {
739
+ return [];
740
+ }
741
+ }
742
+ async function getLatestDaemonLog() {
743
+ const [latest] = await listDaemonLogFiles(1);
744
+ return latest || null;
745
+ }
746
+
747
+ const SessionMessageContentSchema = z$1.object({
748
+ c: z$1.string(),
749
+ // Base64 encoded encrypted content
750
+ t: z$1.literal("encrypted")
751
+ });
752
+ const UpdateBodySchema = z$1.object({
753
+ message: z$1.object({
754
+ id: z$1.string(),
755
+ seq: z$1.number(),
756
+ content: SessionMessageContentSchema
757
+ }),
758
+ sid: z$1.string(),
759
+ // Session ID
760
+ t: z$1.literal("new-message")
761
+ });
762
+ const UpdateSessionBodySchema = z$1.object({
763
+ t: z$1.literal("update-session"),
764
+ sid: z$1.string(),
765
+ metadata: z$1.object({
766
+ version: z$1.number(),
767
+ value: z$1.string()
768
+ }).nullish(),
769
+ agentState: z$1.object({
770
+ version: z$1.number(),
771
+ value: z$1.string()
772
+ }).nullish()
773
+ });
774
+ const UpdateMachineBodySchema = z$1.object({
775
+ t: z$1.literal("update-machine"),
776
+ machineId: z$1.string(),
777
+ metadata: z$1.object({
778
+ version: z$1.number(),
779
+ value: z$1.string()
780
+ }).nullish(),
781
+ daemonState: z$1.object({
782
+ version: z$1.number(),
783
+ value: z$1.string()
784
+ }).nullish()
785
+ });
786
+ z$1.object({
787
+ id: z$1.string(),
788
+ seq: z$1.number(),
789
+ body: z$1.union([
790
+ UpdateBodySchema,
791
+ UpdateSessionBodySchema,
792
+ UpdateMachineBodySchema
793
+ ]),
794
+ createdAt: z$1.number()
795
+ });
796
+ z$1.object({
797
+ host: z$1.string(),
798
+ platform: z$1.string(),
799
+ happyCliVersion: z$1.string(),
800
+ homeDir: z$1.string(),
801
+ happyHomeDir: z$1.string(),
802
+ happyLibDir: z$1.string()
803
+ });
804
+ z$1.object({
805
+ status: z$1.union([
806
+ z$1.enum(["running", "shutting-down"]),
807
+ z$1.string()
808
+ // Forward compatibility
809
+ ]),
810
+ pid: z$1.number().optional(),
811
+ httpPort: z$1.number().optional(),
812
+ startedAt: z$1.number().optional(),
813
+ shutdownRequestedAt: z$1.number().optional(),
814
+ shutdownSource: z$1.union([
815
+ z$1.enum(["mobile-app", "cli", "os-signal", "unknown"]),
816
+ z$1.string()
817
+ // Forward compatibility
818
+ ]).optional()
819
+ });
820
+ z$1.object({
821
+ content: SessionMessageContentSchema,
822
+ createdAt: z$1.number(),
823
+ id: z$1.string(),
824
+ seq: z$1.number(),
825
+ updatedAt: z$1.number()
826
+ });
827
+ const MessageMetaSchema = z$1.object({
828
+ sentFrom: z$1.string().optional(),
829
+ // Source identifier
830
+ permissionMode: z$1.string().optional(),
831
+ // Permission mode for this message
832
+ model: z$1.string().nullable().optional(),
833
+ // Model name for this message (null = reset)
834
+ fallbackModel: z$1.string().nullable().optional(),
835
+ // Fallback model for this message (null = reset)
836
+ customSystemPrompt: z$1.string().nullable().optional(),
837
+ // Custom system prompt for this message (null = reset)
838
+ appendSystemPrompt: z$1.string().nullable().optional(),
839
+ // Append to system prompt for this message (null = reset)
840
+ allowedTools: z$1.array(z$1.string()).nullable().optional(),
841
+ // Allowed tools for this message (null = reset)
842
+ disallowedTools: z$1.array(z$1.string()).nullable().optional()
843
+ // Disallowed tools for this message (null = reset)
844
+ });
845
+ z$1.object({
846
+ session: z$1.object({
847
+ id: z$1.string(),
848
+ tag: z$1.string(),
849
+ seq: z$1.number(),
850
+ createdAt: z$1.number(),
851
+ updatedAt: z$1.number(),
852
+ metadata: z$1.string(),
853
+ metadataVersion: z$1.number(),
854
+ agentState: z$1.string().nullable(),
855
+ agentStateVersion: z$1.number()
856
+ })
857
+ });
858
+ const UserMessageSchema = z$1.object({
859
+ role: z$1.literal("user"),
860
+ content: z$1.object({
861
+ type: z$1.literal("text"),
862
+ text: z$1.string()
863
+ }),
864
+ localKey: z$1.string().optional(),
865
+ // Mobile messages include this
866
+ meta: MessageMetaSchema.optional()
867
+ });
868
+ const AgentMessageSchema = z$1.object({
869
+ role: z$1.literal("agent"),
870
+ content: z$1.object({
871
+ type: z$1.literal("output"),
872
+ data: z$1.any()
873
+ }),
874
+ meta: MessageMetaSchema.optional()
875
+ });
876
+ z$1.union([UserMessageSchema, AgentMessageSchema]);
877
+
878
+ async function delay(ms) {
879
+ return new Promise((resolve) => setTimeout(resolve, ms));
880
+ }
881
+ function exponentialBackoffDelay(currentFailureCount, minDelay, maxDelay, maxFailureCount) {
882
+ let maxDelayRet = minDelay + (maxDelay - minDelay) / maxFailureCount * Math.min(currentFailureCount, maxFailureCount);
883
+ return Math.round(Math.random() * maxDelayRet);
884
+ }
885
+ function createBackoff(opts) {
886
+ return async (callback) => {
887
+ let currentFailureCount = 0;
888
+ const minDelay = 250;
889
+ const maxDelay = 1e3;
890
+ const maxFailureCount = 50;
891
+ while (true) {
892
+ try {
893
+ return await callback();
894
+ } catch (e) {
895
+ if (currentFailureCount < maxFailureCount) {
896
+ currentFailureCount++;
897
+ }
898
+ let waitForRequest = exponentialBackoffDelay(currentFailureCount, minDelay, maxDelay, maxFailureCount);
899
+ await delay(waitForRequest);
900
+ }
901
+ }
902
+ };
903
+ }
904
+ let backoff = createBackoff();
905
+ function formatTimeAgo(timestamp) {
906
+ const now = Date.now();
907
+ const time = timestamp instanceof Date ? timestamp.getTime() : timestamp;
908
+ const diffMs = now - time;
909
+ if (diffMs < 0) {
910
+ return "in the future";
911
+ }
912
+ const seconds = Math.floor(diffMs / 1e3);
913
+ const minutes = Math.floor(seconds / 60);
914
+ const hours = Math.floor(minutes / 60);
915
+ const days = Math.floor(hours / 24);
916
+ if (seconds < 60) {
917
+ return `${seconds} ${seconds === 1 ? "second" : "seconds"} ago`;
918
+ }
919
+ const parts = [];
920
+ if (days > 0) {
921
+ parts.push(`${days} ${days === 1 ? "day" : "days"}`);
922
+ }
923
+ const remainingHours = hours % 24;
924
+ if (remainingHours > 0) {
925
+ parts.push(`${remainingHours} ${remainingHours === 1 ? "hour" : "hours"}`);
926
+ }
927
+ const remainingMinutes = minutes % 60;
928
+ if (remainingMinutes > 0 && days === 0) {
929
+ parts.push(`${remainingMinutes} ${remainingMinutes === 1 ? "minute" : "minutes"}`);
930
+ }
931
+ return parts.slice(0, 2).join(", ") + " ago";
932
+ }
933
+
934
+ class AsyncLock {
935
+ permits = 1;
936
+ promiseResolverQueue = [];
937
+ async inLock(func) {
938
+ try {
939
+ await this.lock();
940
+ return await func();
941
+ } finally {
942
+ this.unlock();
943
+ }
944
+ }
945
+ async lock() {
946
+ if (this.permits > 0) {
947
+ this.permits = this.permits - 1;
948
+ return;
949
+ }
950
+ await new Promise((resolve) => this.promiseResolverQueue.push(resolve));
951
+ }
952
+ unlock() {
953
+ this.permits += 1;
954
+ if (this.permits > 1 && this.promiseResolverQueue.length > 0) {
955
+ throw new Error("this.permits should never be > 0 when there is someone waiting.");
956
+ } else if (this.permits === 1 && this.promiseResolverQueue.length > 0) {
957
+ this.permits -= 1;
958
+ const nextResolver = this.promiseResolverQueue.shift();
959
+ if (nextResolver) {
960
+ setTimeout(() => {
961
+ nextResolver(true);
962
+ }, 0);
963
+ }
964
+ }
965
+ }
966
+ }
967
+
968
+ class RpcHandlerManager {
969
+ handlers = /* @__PURE__ */ new Map();
970
+ scopePrefix;
971
+ encryptionKey;
972
+ encryptionVariant;
973
+ logger;
974
+ socket = null;
975
+ constructor(config) {
976
+ this.scopePrefix = config.scopePrefix;
977
+ this.encryptionKey = config.encryptionKey;
978
+ this.encryptionVariant = config.encryptionVariant;
979
+ this.logger = config.logger || ((msg, data) => logger.debug(msg, data));
980
+ }
981
+ /**
982
+ * Register an RPC handler for a specific method
983
+ * @param method - The method name (without prefix)
984
+ * @param handler - The handler function
985
+ */
986
+ registerHandler(method, handler) {
987
+ const prefixedMethod = this.getPrefixedMethod(method);
988
+ this.handlers.set(prefixedMethod, handler);
989
+ if (this.socket) {
990
+ this.socket.emit("rpc-register", { method: prefixedMethod });
991
+ }
992
+ }
993
+ /**
994
+ * Handle an incoming RPC request
995
+ * @param request - The RPC request data
996
+ * @param callback - The response callback
997
+ */
998
+ async handleRequest(request) {
999
+ try {
1000
+ const handler = this.handlers.get(request.method);
1001
+ if (!handler) {
1002
+ this.logger("[RPC] [ERROR] Method not found", { method: request.method });
1003
+ const errorResponse = { error: "Method not found" };
1004
+ const encryptedError = encodeBase64(encrypt(this.encryptionKey, this.encryptionVariant, errorResponse));
1005
+ return encryptedError;
1006
+ }
1007
+ const decryptedParams = decrypt(this.encryptionKey, this.encryptionVariant, decodeBase64(request.params));
1008
+ const result = await handler(decryptedParams);
1009
+ const encryptedResponse = encodeBase64(encrypt(this.encryptionKey, this.encryptionVariant, result));
1010
+ return encryptedResponse;
1011
+ } catch (error) {
1012
+ this.logger("[RPC] [ERROR] Error handling request", { error });
1013
+ const errorResponse = {
1014
+ error: error instanceof Error ? error.message : "Unknown error"
1015
+ };
1016
+ return encodeBase64(encrypt(this.encryptionKey, this.encryptionVariant, errorResponse));
1017
+ }
1018
+ }
1019
+ onSocketConnect(socket) {
1020
+ this.socket = socket;
1021
+ for (const [prefixedMethod] of this.handlers) {
1022
+ socket.emit("rpc-register", { method: prefixedMethod });
1023
+ }
1024
+ }
1025
+ onSocketDisconnect() {
1026
+ this.socket = null;
1027
+ }
1028
+ /**
1029
+ * Get the number of registered handlers
1030
+ */
1031
+ getHandlerCount() {
1032
+ return this.handlers.size;
1033
+ }
1034
+ /**
1035
+ * Check if a handler is registered
1036
+ * @param method - The method name (without prefix)
1037
+ */
1038
+ hasHandler(method) {
1039
+ const prefixedMethod = this.getPrefixedMethod(method);
1040
+ return this.handlers.has(prefixedMethod);
1041
+ }
1042
+ /**
1043
+ * Clear all handlers
1044
+ */
1045
+ clearHandlers() {
1046
+ this.handlers.clear();
1047
+ this.logger("Cleared all RPC handlers");
1048
+ }
1049
+ /**
1050
+ * Get the prefixed method name
1051
+ * @param method - The method name
1052
+ */
1053
+ getPrefixedMethod(method) {
1054
+ return `${this.scopePrefix}:${method}`;
1055
+ }
1056
+ }
1057
+
1058
+ const __dirname = dirname(fileURLToPath(import.meta.url));
1059
+ function projectPath() {
1060
+ const path = resolve(__dirname, "..");
1061
+ return path;
1062
+ }
1063
+
1064
+ function run$1(args, options) {
1065
+ const RUNNER_PATH = resolve(join$1(projectPath(), "scripts", "ripgrep_launcher.cjs"));
1066
+ return new Promise((resolve2, reject) => {
1067
+ const child = spawn("node", [RUNNER_PATH, JSON.stringify(args)], {
1068
+ stdio: ["pipe", "pipe", "pipe"],
1069
+ cwd: options?.cwd
1070
+ });
1071
+ let stdout = "";
1072
+ let stderr = "";
1073
+ child.stdout.on("data", (data) => {
1074
+ stdout += data.toString();
1075
+ });
1076
+ child.stderr.on("data", (data) => {
1077
+ stderr += data.toString();
1078
+ });
1079
+ child.on("close", (code) => {
1080
+ resolve2({
1081
+ exitCode: code || 0,
1082
+ stdout,
1083
+ stderr
1084
+ });
1085
+ });
1086
+ child.on("error", (err) => {
1087
+ reject(err);
1088
+ });
1089
+ });
1090
+ }
1091
+
1092
+ function getBinaryPath() {
1093
+ const platformName = platform();
1094
+ const binaryName = platformName === "win32" ? "difft.exe" : "difft";
1095
+ return resolve(join$1(projectPath(), "tools", "unpacked", binaryName));
1096
+ }
1097
+ function run(args, options) {
1098
+ const binaryPath = getBinaryPath();
1099
+ return new Promise((resolve2, reject) => {
1100
+ const child = spawn(binaryPath, args, {
1101
+ stdio: ["pipe", "pipe", "pipe"],
1102
+ cwd: options?.cwd,
1103
+ env: {
1104
+ ...process.env,
1105
+ // Force color output when needed
1106
+ FORCE_COLOR: "1"
1107
+ }
1108
+ });
1109
+ let stdout = "";
1110
+ let stderr = "";
1111
+ child.stdout.on("data", (data) => {
1112
+ stdout += data.toString();
1113
+ });
1114
+ child.stderr.on("data", (data) => {
1115
+ stderr += data.toString();
1116
+ });
1117
+ child.on("close", (code) => {
1118
+ resolve2({
1119
+ exitCode: code || 0,
1120
+ stdout,
1121
+ stderr
1122
+ });
1123
+ });
1124
+ child.on("error", (err) => {
1125
+ reject(err);
1126
+ });
1127
+ });
1128
+ }
1129
+
1130
+ const execAsync = promisify(exec);
1131
+ function registerCommonHandlers(rpcHandlerManager) {
1132
+ rpcHandlerManager.registerHandler("bash", async (data) => {
1133
+ logger.debug("Shell command request:", data.command);
1134
+ try {
1135
+ const options = {
1136
+ cwd: data.cwd,
1137
+ timeout: data.timeout || 3e4
1138
+ // Default 30 seconds timeout
1139
+ };
1140
+ const { stdout, stderr } = await execAsync(data.command, options);
1141
+ return {
1142
+ success: true,
1143
+ stdout: stdout ? stdout.toString() : "",
1144
+ stderr: stderr ? stderr.toString() : "",
1145
+ exitCode: 0
1146
+ };
1147
+ } catch (error) {
1148
+ const execError = error;
1149
+ if (execError.code === "ETIMEDOUT" || execError.killed) {
1150
+ return {
1151
+ success: false,
1152
+ stdout: execError.stdout || "",
1153
+ stderr: execError.stderr || "",
1154
+ exitCode: typeof execError.code === "number" ? execError.code : -1,
1155
+ error: "Command timed out"
1156
+ };
1157
+ }
1158
+ return {
1159
+ success: false,
1160
+ stdout: execError.stdout ? execError.stdout.toString() : "",
1161
+ stderr: execError.stderr ? execError.stderr.toString() : execError.message || "Command failed",
1162
+ exitCode: typeof execError.code === "number" ? execError.code : 1,
1163
+ error: execError.message || "Command failed"
1164
+ };
1165
+ }
1166
+ });
1167
+ rpcHandlerManager.registerHandler("readFile", async (data) => {
1168
+ logger.debug("Read file request:", data.path);
1169
+ try {
1170
+ const buffer = await readFile$1(data.path);
1171
+ const content = buffer.toString("base64");
1172
+ return { success: true, content };
1173
+ } catch (error) {
1174
+ logger.debug("Failed to read file:", error);
1175
+ return { success: false, error: error instanceof Error ? error.message : "Failed to read file" };
1176
+ }
1177
+ });
1178
+ rpcHandlerManager.registerHandler("writeFile", async (data) => {
1179
+ logger.debug("Write file request:", data.path);
1180
+ try {
1181
+ if (data.expectedHash !== null && data.expectedHash !== void 0) {
1182
+ try {
1183
+ const existingBuffer = await readFile$1(data.path);
1184
+ const existingHash = createHash$1("sha256").update(existingBuffer).digest("hex");
1185
+ if (existingHash !== data.expectedHash) {
1186
+ return {
1187
+ success: false,
1188
+ error: `File hash mismatch. Expected: ${data.expectedHash}, Actual: ${existingHash}`
1189
+ };
1190
+ }
1191
+ } catch (error) {
1192
+ const nodeError = error;
1193
+ if (nodeError.code !== "ENOENT") {
1194
+ throw error;
1195
+ }
1196
+ return {
1197
+ success: false,
1198
+ error: "File does not exist but hash was provided"
1199
+ };
1200
+ }
1201
+ } else {
1202
+ try {
1203
+ await stat$1(data.path);
1204
+ return {
1205
+ success: false,
1206
+ error: "File already exists but was expected to be new"
1207
+ };
1208
+ } catch (error) {
1209
+ const nodeError = error;
1210
+ if (nodeError.code !== "ENOENT") {
1211
+ throw error;
1212
+ }
1213
+ }
1214
+ }
1215
+ const buffer = Buffer.from(data.content, "base64");
1216
+ await writeFile$1(data.path, buffer);
1217
+ const hash = createHash$1("sha256").update(buffer).digest("hex");
1218
+ return { success: true, hash };
1219
+ } catch (error) {
1220
+ logger.debug("Failed to write file:", error);
1221
+ return { success: false, error: error instanceof Error ? error.message : "Failed to write file" };
1222
+ }
1223
+ });
1224
+ rpcHandlerManager.registerHandler("listDirectory", async (data) => {
1225
+ logger.debug("List directory request:", data.path);
1226
+ try {
1227
+ const entries = await readdir(data.path, { withFileTypes: true });
1228
+ const directoryEntries = await Promise.all(
1229
+ entries.map(async (entry) => {
1230
+ const fullPath = join$1(data.path, entry.name);
1231
+ let type = "other";
1232
+ let size;
1233
+ let modified;
1234
+ if (entry.isDirectory()) {
1235
+ type = "directory";
1236
+ } else if (entry.isFile()) {
1237
+ type = "file";
1238
+ }
1239
+ try {
1240
+ const stats = await stat$1(fullPath);
1241
+ size = stats.size;
1242
+ modified = stats.mtime.getTime();
1243
+ } catch (error) {
1244
+ logger.debug(`Failed to stat ${fullPath}:`, error);
1245
+ }
1246
+ return {
1247
+ name: entry.name,
1248
+ type,
1249
+ size,
1250
+ modified
1251
+ };
1252
+ })
1253
+ );
1254
+ directoryEntries.sort((a, b) => {
1255
+ if (a.type === "directory" && b.type !== "directory") return -1;
1256
+ if (a.type !== "directory" && b.type === "directory") return 1;
1257
+ return a.name.localeCompare(b.name);
1258
+ });
1259
+ return { success: true, entries: directoryEntries };
1260
+ } catch (error) {
1261
+ logger.debug("Failed to list directory:", error);
1262
+ return { success: false, error: error instanceof Error ? error.message : "Failed to list directory" };
1263
+ }
1264
+ });
1265
+ rpcHandlerManager.registerHandler("getDirectoryTree", async (data) => {
1266
+ logger.debug("Get directory tree request:", data.path, "maxDepth:", data.maxDepth);
1267
+ async function buildTree(path, name, currentDepth) {
1268
+ try {
1269
+ const stats = await stat$1(path);
1270
+ const node = {
1271
+ name,
1272
+ path,
1273
+ type: stats.isDirectory() ? "directory" : "file",
1274
+ size: stats.size,
1275
+ modified: stats.mtime.getTime()
1276
+ };
1277
+ if (stats.isDirectory() && currentDepth < data.maxDepth) {
1278
+ const entries = await readdir(path, { withFileTypes: true });
1279
+ const children = [];
1280
+ await Promise.all(
1281
+ entries.map(async (entry) => {
1282
+ if (entry.isSymbolicLink()) {
1283
+ logger.debug(`Skipping symlink: ${join$1(path, entry.name)}`);
1284
+ return;
1285
+ }
1286
+ const childPath = join$1(path, entry.name);
1287
+ const childNode = await buildTree(childPath, entry.name, currentDepth + 1);
1288
+ if (childNode) {
1289
+ children.push(childNode);
1290
+ }
1291
+ })
1292
+ );
1293
+ children.sort((a, b) => {
1294
+ if (a.type === "directory" && b.type !== "directory") return -1;
1295
+ if (a.type !== "directory" && b.type === "directory") return 1;
1296
+ return a.name.localeCompare(b.name);
1297
+ });
1298
+ node.children = children;
1299
+ }
1300
+ return node;
1301
+ } catch (error) {
1302
+ logger.debug(`Failed to process ${path}:`, error instanceof Error ? error.message : String(error));
1303
+ return null;
1304
+ }
1305
+ }
1306
+ try {
1307
+ if (data.maxDepth < 0) {
1308
+ return { success: false, error: "maxDepth must be non-negative" };
1309
+ }
1310
+ const baseName = data.path === "/" ? "/" : data.path.split("/").pop() || data.path;
1311
+ const tree = await buildTree(data.path, baseName, 0);
1312
+ if (!tree) {
1313
+ return { success: false, error: "Failed to access the specified path" };
1314
+ }
1315
+ return { success: true, tree };
1316
+ } catch (error) {
1317
+ logger.debug("Failed to get directory tree:", error);
1318
+ return { success: false, error: error instanceof Error ? error.message : "Failed to get directory tree" };
1319
+ }
1320
+ });
1321
+ rpcHandlerManager.registerHandler("ripgrep", async (data) => {
1322
+ logger.debug("Ripgrep request with args:", data.args, "cwd:", data.cwd);
1323
+ try {
1324
+ const result = await run$1(data.args, { cwd: data.cwd });
1325
+ return {
1326
+ success: true,
1327
+ exitCode: result.exitCode,
1328
+ stdout: result.stdout.toString(),
1329
+ stderr: result.stderr.toString()
1330
+ };
1331
+ } catch (error) {
1332
+ logger.debug("Failed to run ripgrep:", error);
1333
+ return {
1334
+ success: false,
1335
+ error: error instanceof Error ? error.message : "Failed to run ripgrep"
1336
+ };
1337
+ }
1338
+ });
1339
+ rpcHandlerManager.registerHandler("difftastic", async (data) => {
1340
+ logger.debug("Difftastic request with args:", data.args, "cwd:", data.cwd);
1341
+ try {
1342
+ const result = await run(data.args, { cwd: data.cwd });
1343
+ return {
1344
+ success: true,
1345
+ exitCode: result.exitCode,
1346
+ stdout: result.stdout.toString(),
1347
+ stderr: result.stderr.toString()
1348
+ };
1349
+ } catch (error) {
1350
+ logger.debug("Failed to run difftastic:", error);
1351
+ return {
1352
+ success: false,
1353
+ error: error instanceof Error ? error.message : "Failed to run difftastic"
1354
+ };
1355
+ }
1356
+ });
1357
+ }
1358
+
1359
+ class ApiSessionClient extends EventEmitter {
1360
+ token;
1361
+ sessionId;
1362
+ metadata;
1363
+ metadataVersion;
1364
+ agentState;
1365
+ agentStateVersion;
1366
+ socket;
1367
+ pendingMessages = [];
1368
+ pendingMessageCallback = null;
1369
+ rpcHandlerManager;
1370
+ agentStateLock = new AsyncLock();
1371
+ metadataLock = new AsyncLock();
1372
+ encryptionKey;
1373
+ encryptionVariant;
1374
+ constructor(token, session) {
1375
+ super();
1376
+ this.token = token;
1377
+ this.sessionId = session.id;
1378
+ this.metadata = session.metadata;
1379
+ this.metadataVersion = session.metadataVersion;
1380
+ this.agentState = session.agentState;
1381
+ this.agentStateVersion = session.agentStateVersion;
1382
+ this.encryptionKey = session.encryptionKey;
1383
+ this.encryptionVariant = session.encryptionVariant;
1384
+ this.rpcHandlerManager = new RpcHandlerManager({
1385
+ scopePrefix: this.sessionId,
1386
+ encryptionKey: this.encryptionKey,
1387
+ encryptionVariant: this.encryptionVariant,
1388
+ logger: (msg, data) => logger.debug(msg, data)
1389
+ });
1390
+ registerCommonHandlers(this.rpcHandlerManager);
1391
+ this.socket = io(configuration.serverUrl, {
1392
+ auth: {
1393
+ token: this.token,
1394
+ clientType: "session-scoped",
1395
+ sessionId: this.sessionId
1396
+ },
1397
+ path: "/v1/updates",
1398
+ reconnection: true,
1399
+ reconnectionAttempts: Infinity,
1400
+ reconnectionDelay: 1e3,
1401
+ reconnectionDelayMax: 5e3,
1402
+ transports: ["websocket"],
1403
+ withCredentials: true,
1404
+ autoConnect: false
1405
+ });
1406
+ this.socket.on("connect", () => {
1407
+ logger.debug("Socket connected successfully");
1408
+ this.rpcHandlerManager.onSocketConnect(this.socket);
1409
+ });
1410
+ this.socket.on("rpc-request", async (data, callback) => {
1411
+ callback(await this.rpcHandlerManager.handleRequest(data));
1412
+ });
1413
+ this.socket.on("disconnect", (reason) => {
1414
+ logger.debug("[API] Socket disconnected:", reason);
1415
+ this.rpcHandlerManager.onSocketDisconnect();
1416
+ });
1417
+ this.socket.on("connect_error", (error) => {
1418
+ logger.debug("[API] Socket connection error:", error);
1419
+ this.rpcHandlerManager.onSocketDisconnect();
1420
+ });
1421
+ this.socket.on("update", (data) => {
1422
+ try {
1423
+ logger.debugLargeJson("[SOCKET] [UPDATE] Received update:", data);
1424
+ if (!data.body) {
1425
+ logger.debug("[SOCKET] [UPDATE] [ERROR] No body in update!");
1426
+ return;
1427
+ }
1428
+ if (data.body.t === "new-message" && data.body.message.content.t === "encrypted") {
1429
+ const body = decrypt(this.encryptionKey, this.encryptionVariant, decodeBase64(data.body.message.content.c));
1430
+ logger.debugLargeJson("[SOCKET] [UPDATE] Received update:", body);
1431
+ const userResult = UserMessageSchema.safeParse(body);
1432
+ if (userResult.success) {
1433
+ if (this.pendingMessageCallback) {
1434
+ this.pendingMessageCallback(userResult.data);
1435
+ } else {
1436
+ this.pendingMessages.push(userResult.data);
1437
+ }
1438
+ } else {
1439
+ this.emit("message", body);
1440
+ }
1441
+ } else if (data.body.t === "update-session") {
1442
+ if (data.body.metadata && data.body.metadata.version > this.metadataVersion) {
1443
+ this.metadata = decrypt(this.encryptionKey, this.encryptionVariant, decodeBase64(data.body.metadata.value));
1444
+ this.metadataVersion = data.body.metadata.version;
1445
+ }
1446
+ if (data.body.agentState && data.body.agentState.version > this.agentStateVersion) {
1447
+ this.agentState = data.body.agentState.value ? decrypt(this.encryptionKey, this.encryptionVariant, decodeBase64(data.body.agentState.value)) : null;
1448
+ this.agentStateVersion = data.body.agentState.version;
1449
+ }
1450
+ } else if (data.body.t === "update-machine") {
1451
+ logger.debug(`[SOCKET] WARNING: Session client received unexpected machine update - ignoring`);
1452
+ } else {
1453
+ this.emit("message", data.body);
1454
+ }
1455
+ } catch (error) {
1456
+ logger.debug("[SOCKET] [UPDATE] [ERROR] Error handling update", { error });
1457
+ }
1458
+ });
1459
+ this.socket.on("error", (error) => {
1460
+ logger.debug("[API] Socket error:", error);
1461
+ });
1462
+ this.socket.connect();
1463
+ }
1464
+ onUserMessage(callback) {
1465
+ this.pendingMessageCallback = callback;
1466
+ while (this.pendingMessages.length > 0) {
1467
+ callback(this.pendingMessages.shift());
1468
+ }
1469
+ }
1470
+ /**
1471
+ * Send message to session
1472
+ * @param body - Message body (can be MessageContent or raw content for agent messages)
1473
+ */
1474
+ sendClaudeSessionMessage(body) {
1475
+ let content;
1476
+ if (body.type === "user" && typeof body.message.content === "string" && body.isSidechain !== true && body.isMeta !== true) {
1477
+ content = {
1478
+ role: "user",
1479
+ content: {
1480
+ type: "text",
1481
+ text: body.message.content
1482
+ },
1483
+ meta: {
1484
+ sentFrom: "cli"
1485
+ }
1486
+ };
1487
+ } else {
1488
+ content = {
1489
+ role: "agent",
1490
+ content: {
1491
+ type: "output",
1492
+ data: body
1493
+ // This wraps the entire Claude message
1494
+ },
1495
+ meta: {
1496
+ sentFrom: "cli"
1497
+ }
1498
+ };
1499
+ }
1500
+ logger.debugLargeJson("[SOCKET] Sending message through socket:", content);
1501
+ const encrypted = encodeBase64(encrypt(this.encryptionKey, this.encryptionVariant, content));
1502
+ this.socket.emit("message", {
1503
+ sid: this.sessionId,
1504
+ message: encrypted
1505
+ });
1506
+ if (body.type === "assistant" && body.message.usage) {
1507
+ try {
1508
+ this.sendUsageData(body.message.usage);
1509
+ } catch (error) {
1510
+ logger.debug("[SOCKET] Failed to send usage data:", error);
1511
+ }
1512
+ }
1513
+ if (body.type === "summary" && "summary" in body && "leafUuid" in body) {
1514
+ this.updateMetadata((metadata) => ({
1515
+ ...metadata,
1516
+ summary: {
1517
+ text: body.summary,
1518
+ updatedAt: Date.now()
1519
+ }
1520
+ }));
1521
+ }
1522
+ }
1523
+ sendCodexMessage(body) {
1524
+ let content = {
1525
+ role: "agent",
1526
+ content: {
1527
+ type: "codex",
1528
+ data: body
1529
+ // This wraps the entire Claude message
1530
+ },
1531
+ meta: {
1532
+ sentFrom: "cli"
1533
+ }
1534
+ };
1535
+ const encrypted = encodeBase64(encrypt(this.encryptionKey, this.encryptionVariant, content));
1536
+ this.socket.emit("message", {
1537
+ sid: this.sessionId,
1538
+ message: encrypted
1539
+ });
1540
+ }
1541
+ sendSessionEvent(event, id) {
1542
+ let content = {
1543
+ role: "agent",
1544
+ content: {
1545
+ id: id ?? randomUUID(),
1546
+ type: "event",
1547
+ data: event
1548
+ }
1549
+ };
1550
+ const encrypted = encodeBase64(encrypt(this.encryptionKey, this.encryptionVariant, content));
1551
+ this.socket.emit("message", {
1552
+ sid: this.sessionId,
1553
+ message: encrypted
1554
+ });
1555
+ }
1556
+ /**
1557
+ * Send a ping message to keep the connection alive
1558
+ */
1559
+ keepAlive(thinking, mode) {
1560
+ if (process.env.DEBUG) {
1561
+ logger.debug(`[API] Sending keep alive message: ${thinking}`);
1562
+ }
1563
+ this.socket.volatile.emit("session-alive", {
1564
+ sid: this.sessionId,
1565
+ time: Date.now(),
1566
+ thinking,
1567
+ mode
1568
+ });
1569
+ }
1570
+ /**
1571
+ * Send session death message
1572
+ */
1573
+ sendSessionDeath() {
1574
+ this.socket.emit("session-end", { sid: this.sessionId, time: Date.now() });
1575
+ }
1576
+ /**
1577
+ * Send usage data to the server
1578
+ */
1579
+ sendUsageData(usage) {
1580
+ const totalTokens = usage.input_tokens + usage.output_tokens + (usage.cache_creation_input_tokens || 0) + (usage.cache_read_input_tokens || 0);
1581
+ const usageReport = {
1582
+ key: "claude-session",
1583
+ sessionId: this.sessionId,
1584
+ tokens: {
1585
+ total: totalTokens,
1586
+ input: usage.input_tokens,
1587
+ output: usage.output_tokens,
1588
+ cache_creation: usage.cache_creation_input_tokens || 0,
1589
+ cache_read: usage.cache_read_input_tokens || 0
1590
+ },
1591
+ cost: {
1592
+ // TODO: Calculate actual costs based on pricing
1593
+ // For now, using placeholder values
1594
+ total: 0,
1595
+ input: 0,
1596
+ output: 0
1597
+ }
1598
+ };
1599
+ logger.debugLargeJson("[SOCKET] Sending usage data:", usageReport);
1600
+ this.socket.emit("usage-report", usageReport);
1601
+ }
1602
+ /**
1603
+ * Update session metadata
1604
+ * @param handler - Handler function that returns the updated metadata
1605
+ */
1606
+ updateMetadata(handler) {
1607
+ this.metadataLock.inLock(async () => {
1608
+ await backoff(async () => {
1609
+ let updated = handler(this.metadata);
1610
+ const answer = await this.socket.emitWithAck("update-metadata", { sid: this.sessionId, expectedVersion: this.metadataVersion, metadata: encodeBase64(encrypt(this.encryptionKey, this.encryptionVariant, updated)) });
1611
+ if (answer.result === "success") {
1612
+ this.metadata = decrypt(this.encryptionKey, this.encryptionVariant, decodeBase64(answer.metadata));
1613
+ this.metadataVersion = answer.version;
1614
+ } else if (answer.result === "version-mismatch") {
1615
+ if (answer.version > this.metadataVersion) {
1616
+ this.metadataVersion = answer.version;
1617
+ this.metadata = decrypt(this.encryptionKey, this.encryptionVariant, decodeBase64(answer.metadata));
1618
+ }
1619
+ throw new Error("Metadata version mismatch");
1620
+ } else if (answer.result === "error") ;
1621
+ });
1622
+ });
1623
+ }
1624
+ /**
1625
+ * Update session agent state
1626
+ * @param handler - Handler function that returns the updated agent state
1627
+ */
1628
+ updateAgentState(handler) {
1629
+ logger.debugLargeJson("Updating agent state", this.agentState);
1630
+ this.agentStateLock.inLock(async () => {
1631
+ await backoff(async () => {
1632
+ let updated = handler(this.agentState || {});
1633
+ const answer = await this.socket.emitWithAck("update-state", { sid: this.sessionId, expectedVersion: this.agentStateVersion, agentState: updated ? encodeBase64(encrypt(this.encryptionKey, this.encryptionVariant, updated)) : null });
1634
+ if (answer.result === "success") {
1635
+ this.agentState = answer.agentState ? decrypt(this.encryptionKey, this.encryptionVariant, decodeBase64(answer.agentState)) : null;
1636
+ this.agentStateVersion = answer.version;
1637
+ logger.debug("Agent state updated", this.agentState);
1638
+ } else if (answer.result === "version-mismatch") {
1639
+ if (answer.version > this.agentStateVersion) {
1640
+ this.agentStateVersion = answer.version;
1641
+ this.agentState = answer.agentState ? decrypt(this.encryptionKey, this.encryptionVariant, decodeBase64(answer.agentState)) : null;
1642
+ }
1643
+ throw new Error("Agent state version mismatch");
1644
+ } else if (answer.result === "error") ;
1645
+ });
1646
+ });
1647
+ }
1648
+ /**
1649
+ * Wait for socket buffer to flush
1650
+ */
1651
+ async flush() {
1652
+ if (!this.socket.connected) {
1653
+ return;
1654
+ }
1655
+ return new Promise((resolve) => {
1656
+ this.socket.emit("ping", () => {
1657
+ resolve();
1658
+ });
1659
+ setTimeout(() => {
1660
+ resolve();
1661
+ }, 1e4);
1662
+ });
1663
+ }
1664
+ async close() {
1665
+ logger.debug("[API] socket.close() called");
1666
+ this.socket.close();
1667
+ }
1668
+ }
1669
+
1670
+ class ApiMachineClient {
1671
+ constructor(token, machine) {
1672
+ this.token = token;
1673
+ this.machine = machine;
1674
+ this.rpcHandlerManager = new RpcHandlerManager({
1675
+ scopePrefix: this.machine.id,
1676
+ encryptionKey: this.machine.encryptionKey,
1677
+ encryptionVariant: this.machine.encryptionVariant,
1678
+ logger: (msg, data) => logger.debug(msg, data)
1679
+ });
1680
+ registerCommonHandlers(this.rpcHandlerManager);
1681
+ }
1682
+ socket;
1683
+ keepAliveInterval = null;
1684
+ rpcHandlerManager;
1685
+ setRPCHandlers({
1686
+ spawnSession,
1687
+ stopSession,
1688
+ requestShutdown
1689
+ }) {
1690
+ this.rpcHandlerManager.registerHandler("spawn-happy-session", async (params) => {
1691
+ const { directory, sessionId, machineId, approvedNewDirectoryCreation, agent, token } = params || {};
1692
+ logger.debug(`[API MACHINE] Spawning session with params: ${JSON.stringify(params)}`);
1693
+ if (!directory) {
1694
+ throw new Error("Directory is required");
1695
+ }
1696
+ const result = await spawnSession({ directory, sessionId, machineId, approvedNewDirectoryCreation, agent, token });
1697
+ switch (result.type) {
1698
+ case "success":
1699
+ logger.debug(`[API MACHINE] Spawned session ${result.sessionId}`);
1700
+ return { type: "success", sessionId: result.sessionId };
1701
+ case "requestToApproveDirectoryCreation":
1702
+ logger.debug(`[API MACHINE] Requesting directory creation approval for: ${result.directory}`);
1703
+ return { type: "requestToApproveDirectoryCreation", directory: result.directory };
1704
+ case "error":
1705
+ throw new Error(result.errorMessage);
1706
+ }
1707
+ });
1708
+ this.rpcHandlerManager.registerHandler("stop-session", (params) => {
1709
+ const { sessionId } = params || {};
1710
+ if (!sessionId) {
1711
+ throw new Error("Session ID is required");
1712
+ }
1713
+ const success = stopSession(sessionId);
1714
+ if (!success) {
1715
+ throw new Error("Session not found or failed to stop");
1716
+ }
1717
+ logger.debug(`[API MACHINE] Stopped session ${sessionId}`);
1718
+ return { message: "Session stopped" };
1719
+ });
1720
+ this.rpcHandlerManager.registerHandler("stop-daemon", () => {
1721
+ logger.debug("[API MACHINE] Received stop-daemon RPC request");
1722
+ setTimeout(() => {
1723
+ logger.debug("[API MACHINE] Initiating daemon shutdown from RPC");
1724
+ requestShutdown();
1725
+ }, 100);
1726
+ return { message: "Daemon stop request acknowledged, starting shutdown sequence..." };
1727
+ });
1728
+ this.rpcHandlerManager.registerHandler("ping", () => {
1729
+ logger.debug("[API MACHINE] Received ping RPC request");
1730
+ return {
1731
+ status: "alive",
1732
+ timestamp: Date.now(),
1733
+ uptime: process.uptime(),
1734
+ machineId: this.machine.id
1735
+ };
1736
+ });
1737
+ }
1738
+ /**
1739
+ * Update machine metadata
1740
+ * Currently unused, changes from the mobile client are more likely
1741
+ * for example to set a custom name.
1742
+ */
1743
+ async updateMachineMetadata(handler) {
1744
+ await backoff(async () => {
1745
+ const updated = handler(this.machine.metadata);
1746
+ const answer = await this.socket.emitWithAck("machine-update-metadata", {
1747
+ machineId: this.machine.id,
1748
+ metadata: encodeBase64(encrypt(this.machine.encryptionKey, this.machine.encryptionVariant, updated)),
1749
+ expectedVersion: this.machine.metadataVersion
1750
+ });
1751
+ if (answer.result === "success") {
1752
+ this.machine.metadata = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(answer.metadata));
1753
+ this.machine.metadataVersion = answer.version;
1754
+ logger.debug("[API MACHINE] Metadata updated successfully");
1755
+ } else if (answer.result === "version-mismatch") {
1756
+ if (answer.version > this.machine.metadataVersion) {
1757
+ this.machine.metadataVersion = answer.version;
1758
+ this.machine.metadata = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(answer.metadata));
1759
+ }
1760
+ throw new Error("Metadata version mismatch");
1761
+ }
1762
+ });
1763
+ }
1764
+ /**
1765
+ * Update daemon state (runtime info) - similar to session updateAgentState
1766
+ * Simplified without lock - relies on backoff for retry
1767
+ */
1768
+ async updateDaemonState(handler) {
1769
+ await backoff(async () => {
1770
+ const updated = handler(this.machine.daemonState);
1771
+ const answer = await this.socket.emitWithAck("machine-update-state", {
1772
+ machineId: this.machine.id,
1773
+ daemonState: encodeBase64(encrypt(this.machine.encryptionKey, this.machine.encryptionVariant, updated)),
1774
+ expectedVersion: this.machine.daemonStateVersion
1775
+ });
1776
+ if (answer.result === "success") {
1777
+ this.machine.daemonState = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(answer.daemonState));
1778
+ this.machine.daemonStateVersion = answer.version;
1779
+ logger.debug("[API MACHINE] Daemon state updated successfully");
1780
+ } else if (answer.result === "version-mismatch") {
1781
+ if (answer.version > this.machine.daemonStateVersion) {
1782
+ this.machine.daemonStateVersion = answer.version;
1783
+ this.machine.daemonState = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(answer.daemonState));
1784
+ }
1785
+ throw new Error("Daemon state version mismatch");
1786
+ }
1787
+ });
1788
+ }
1789
+ connect() {
1790
+ const serverUrl = configuration.serverUrl.replace(/^http/, "ws");
1791
+ logger.debug(`[API MACHINE] Connecting to ${serverUrl}`);
1792
+ this.socket = io(serverUrl, {
1793
+ transports: ["websocket"],
1794
+ auth: {
1795
+ token: this.token,
1796
+ clientType: "machine-scoped",
1797
+ machineId: this.machine.id
1798
+ },
1799
+ path: "/v1/updates",
1800
+ reconnection: true,
1801
+ reconnectionDelay: 1e3,
1802
+ reconnectionDelayMax: 5e3
1803
+ });
1804
+ this.socket.on("connect", () => {
1805
+ logger.debug("[API MACHINE] Connected to server");
1806
+ this.updateDaemonState((state) => ({
1807
+ ...state,
1808
+ status: "running",
1809
+ pid: process.pid,
1810
+ httpPort: this.machine.daemonState?.httpPort,
1811
+ startedAt: Date.now()
1812
+ }));
1813
+ this.rpcHandlerManager.onSocketConnect(this.socket);
1814
+ this.startKeepAlive();
1815
+ });
1816
+ this.socket.on("disconnect", () => {
1817
+ logger.debug("[API MACHINE] Disconnected from server");
1818
+ this.rpcHandlerManager.onSocketDisconnect();
1819
+ this.stopKeepAlive();
1820
+ });
1821
+ this.socket.on("rpc-request", async (data, callback) => {
1822
+ logger.debugLargeJson(`[API MACHINE] Received RPC request:`, data);
1823
+ callback(await this.rpcHandlerManager.handleRequest(data));
1824
+ });
1825
+ this.socket.on("update", (data) => {
1826
+ if (data.body.t === "update-machine" && data.body.machineId === this.machine.id) {
1827
+ const update = data.body;
1828
+ if (update.metadata) {
1829
+ logger.debug("[API MACHINE] Received external metadata update");
1830
+ this.machine.metadata = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(update.metadata.value));
1831
+ this.machine.metadataVersion = update.metadata.version;
1832
+ }
1833
+ if (update.daemonState) {
1834
+ logger.debug("[API MACHINE] Received external daemon state update");
1835
+ this.machine.daemonState = decrypt(this.machine.encryptionKey, this.machine.encryptionVariant, decodeBase64(update.daemonState.value));
1836
+ this.machine.daemonStateVersion = update.daemonState.version;
1837
+ }
1838
+ } else {
1839
+ logger.debug(`[API MACHINE] Received unknown update type: ${data.body.t}`);
1840
+ }
1841
+ });
1842
+ this.socket.on("connect_error", (error) => {
1843
+ logger.debug(`[API MACHINE] Connection error: ${error.message}`);
1844
+ });
1845
+ this.socket.io.on("error", (error) => {
1846
+ logger.debug("[API MACHINE] Socket error:", error);
1847
+ });
1848
+ }
1849
+ startKeepAlive() {
1850
+ this.stopKeepAlive();
1851
+ this.keepAliveInterval = setInterval(() => {
1852
+ const payload = {
1853
+ machineId: this.machine.id,
1854
+ time: Date.now()
1855
+ };
1856
+ if (process.env.DEBUG) {
1857
+ logger.debugLargeJson(`[API MACHINE] Emitting machine-alive`, payload);
1858
+ }
1859
+ this.socket.emit("machine-alive", payload);
1860
+ }, 2e4);
1861
+ logger.debug("[API MACHINE] Keep-alive started (20s interval)");
1862
+ }
1863
+ stopKeepAlive() {
1864
+ if (this.keepAliveInterval) {
1865
+ clearInterval(this.keepAliveInterval);
1866
+ this.keepAliveInterval = null;
1867
+ logger.debug("[API MACHINE] Keep-alive stopped");
1868
+ }
1869
+ }
1870
+ shutdown() {
1871
+ logger.debug("[API MACHINE] Shutting down");
1872
+ this.stopKeepAlive();
1873
+ if (this.socket) {
1874
+ this.socket.close();
1875
+ logger.debug("[API MACHINE] Socket closed");
1876
+ }
1877
+ }
1878
+ }
1879
+
1880
+ class PushNotificationClient {
1881
+ token;
1882
+ baseUrl;
1883
+ expo;
1884
+ constructor(token, baseUrl = "https://api.cluster-fluster.com") {
1885
+ this.token = token;
1886
+ this.baseUrl = baseUrl;
1887
+ this.expo = new Expo();
1888
+ }
1889
+ /**
1890
+ * Fetch all push tokens for the authenticated user
1891
+ */
1892
+ async fetchPushTokens() {
1893
+ try {
1894
+ const response = await axios.get(
1895
+ `${this.baseUrl}/v1/push-tokens`,
1896
+ {
1897
+ headers: {
1898
+ "Authorization": `Bearer ${this.token}`,
1899
+ "Content-Type": "application/json"
1900
+ }
1901
+ }
1902
+ );
1903
+ logger.debug(`Fetched ${response.data.tokens.length} push tokens`);
1904
+ response.data.tokens.forEach((token, index) => {
1905
+ logger.debug(`[PUSH] Token ${index + 1}: id=${token.id}, token=${token.token}, created=${new Date(token.createdAt).toISOString()}, updated=${new Date(token.updatedAt).toISOString()}`);
1906
+ });
1907
+ return response.data.tokens;
1908
+ } catch (error) {
1909
+ logger.debug("[PUSH] [ERROR] Failed to fetch push tokens:", error);
1910
+ throw new Error(`Failed to fetch push tokens: ${error instanceof Error ? error.message : "Unknown error"}`);
1911
+ }
1912
+ }
1913
+ /**
1914
+ * Send push notification via Expo Push API with retry
1915
+ * @param messages - Array of push messages to send
1916
+ */
1917
+ async sendPushNotifications(messages) {
1918
+ logger.debug(`Sending ${messages.length} push notifications`);
1919
+ const validMessages = messages.filter((message) => {
1920
+ if (Array.isArray(message.to)) {
1921
+ return message.to.every((token) => Expo.isExpoPushToken(token));
1922
+ }
1923
+ return Expo.isExpoPushToken(message.to);
1924
+ });
1925
+ if (validMessages.length === 0) {
1926
+ logger.debug("No valid Expo push tokens found");
1927
+ return;
1928
+ }
1929
+ const chunks = this.expo.chunkPushNotifications(validMessages);
1930
+ for (const chunk of chunks) {
1931
+ const startTime = Date.now();
1932
+ const timeout = 3e5;
1933
+ let attempt = 0;
1934
+ while (true) {
1935
+ try {
1936
+ const ticketChunk = await this.expo.sendPushNotificationsAsync(chunk);
1937
+ const errors = ticketChunk.filter((ticket) => ticket.status === "error");
1938
+ if (errors.length > 0) {
1939
+ const errorDetails = errors.map((e) => ({ message: e.message, details: e.details }));
1940
+ logger.debug("[PUSH] Some notifications failed:", errorDetails);
1941
+ }
1942
+ if (errors.length === ticketChunk.length) {
1943
+ throw new Error("All push notifications in chunk failed");
1944
+ }
1945
+ break;
1946
+ } catch (error) {
1947
+ const elapsed = Date.now() - startTime;
1948
+ if (elapsed >= timeout) {
1949
+ logger.debug("[PUSH] Timeout reached after 5 minutes, giving up on chunk");
1950
+ break;
1951
+ }
1952
+ attempt++;
1953
+ const delay = Math.min(1e3 * Math.pow(2, attempt), 3e4);
1954
+ const remainingTime = timeout - elapsed;
1955
+ const waitTime = Math.min(delay, remainingTime);
1956
+ if (waitTime > 0) {
1957
+ logger.debug(`[PUSH] Retrying in ${waitTime}ms (attempt ${attempt})`);
1958
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
1959
+ }
1960
+ }
1961
+ }
1962
+ }
1963
+ logger.debug(`Push notifications sent successfully`);
1964
+ }
1965
+ /**
1966
+ * Send a push notification to all registered devices for the user
1967
+ * @param title - Notification title
1968
+ * @param body - Notification body
1969
+ * @param data - Additional data to send with the notification
1970
+ */
1971
+ sendToAllDevices(title, body, data) {
1972
+ logger.debug(`[PUSH] sendToAllDevices called with title: "${title}", body: "${body}"`);
1973
+ (async () => {
1974
+ try {
1975
+ logger.debug("[PUSH] Fetching push tokens...");
1976
+ const tokens = await this.fetchPushTokens();
1977
+ logger.debug(`[PUSH] Fetched ${tokens.length} push tokens`);
1978
+ tokens.forEach((token, index) => {
1979
+ logger.debug(`[PUSH] Using token ${index + 1}: id=${token.id}, token=${token.token}`);
1980
+ });
1981
+ if (tokens.length === 0) {
1982
+ logger.debug("No push tokens found for user");
1983
+ return;
1984
+ }
1985
+ const messages = tokens.map((token, index) => {
1986
+ logger.debug(`[PUSH] Creating message ${index + 1} for token: ${token.token}`);
1987
+ return {
1988
+ to: token.token,
1989
+ title,
1990
+ body,
1991
+ data,
1992
+ sound: "default",
1993
+ priority: "high"
1994
+ };
1995
+ });
1996
+ logger.debug(`[PUSH] Sending ${messages.length} push notifications...`);
1997
+ await this.sendPushNotifications(messages);
1998
+ logger.debug("[PUSH] Push notifications sent successfully");
1999
+ } catch (error) {
2000
+ logger.debug("[PUSH] Error sending to all devices:", error);
2001
+ }
2002
+ })();
2003
+ }
2004
+ }
2005
+
2006
+ class ApiClient {
2007
+ static async create(credential) {
2008
+ return new ApiClient(credential);
2009
+ }
2010
+ credential;
2011
+ pushClient;
2012
+ constructor(credential) {
2013
+ this.credential = credential;
2014
+ this.pushClient = new PushNotificationClient(credential.token, configuration.serverUrl);
2015
+ }
2016
+ /**
2017
+ * Create a new session or load existing one with the given tag
2018
+ */
2019
+ async getOrCreateSession(opts) {
2020
+ let dataEncryptionKey = null;
2021
+ let encryptionKey;
2022
+ let encryptionVariant;
2023
+ if (this.credential.encryption.type === "dataKey") {
2024
+ encryptionKey = this.credential.encryption.machineKey;
2025
+ encryptionVariant = "dataKey";
2026
+ const derivedPublicKey = derivePublicKeyFromSeed(this.credential.encryption.dataKeySeed);
2027
+ let encryptedDataKey = libsodiumEncryptForPublicKey(this.credential.encryption.machineKey, derivedPublicKey);
2028
+ dataEncryptionKey = new Uint8Array(encryptedDataKey.length + 1);
2029
+ dataEncryptionKey.set([0], 0);
2030
+ dataEncryptionKey.set(encryptedDataKey, 1);
2031
+ } else {
2032
+ encryptionKey = this.credential.encryption.secret;
2033
+ encryptionVariant = "legacy";
2034
+ }
2035
+ try {
2036
+ const response = await axios.post(
2037
+ `${configuration.serverUrl}/v1/sessions`,
2038
+ {
2039
+ tag: opts.tag,
2040
+ metadata: encodeBase64(encrypt(encryptionKey, encryptionVariant, opts.metadata)),
2041
+ agentState: opts.state ? encodeBase64(encrypt(encryptionKey, encryptionVariant, opts.state)) : null,
2042
+ dataEncryptionKey: dataEncryptionKey ? encodeBase64(dataEncryptionKey) : null
2043
+ },
2044
+ {
2045
+ headers: {
2046
+ "Authorization": `Bearer ${this.credential.token}`,
2047
+ "Content-Type": "application/json"
2048
+ },
2049
+ timeout: 6e4
2050
+ // 1 minute timeout for very bad network connections
2051
+ }
2052
+ );
2053
+ logger.debug(`Session created/loaded: ${response.data.session.id} (tag: ${opts.tag})`);
2054
+ let raw = response.data.session;
2055
+ let session = {
2056
+ id: raw.id,
2057
+ seq: raw.seq,
2058
+ metadata: decrypt(encryptionKey, encryptionVariant, decodeBase64(raw.metadata)),
2059
+ metadataVersion: raw.metadataVersion,
2060
+ agentState: raw.agentState ? decrypt(encryptionKey, encryptionVariant, decodeBase64(raw.agentState)) : null,
2061
+ agentStateVersion: raw.agentStateVersion,
2062
+ encryptionKey,
2063
+ encryptionVariant
2064
+ };
2065
+ return session;
2066
+ } catch (error) {
2067
+ logger.debug("[API] [ERROR] Failed to get or create session:", error);
2068
+ throw new Error(`Failed to get or create session: ${error instanceof Error ? error.message : "Unknown error"}`);
2069
+ }
2070
+ }
2071
+ /**
2072
+ * Register or update machine with the server
2073
+ * Returns the current machine state from the server with decrypted metadata and daemonState
2074
+ */
2075
+ async getOrCreateMachine(opts) {
2076
+ let dataEncryptionKey = null;
2077
+ let encryptionKey;
2078
+ let encryptionVariant;
2079
+ if (this.credential.encryption.type === "dataKey") {
2080
+ encryptionVariant = "dataKey";
2081
+ encryptionKey = this.credential.encryption.machineKey;
2082
+ const derivedPublicKey = derivePublicKeyFromSeed(this.credential.encryption.dataKeySeed);
2083
+ let encryptedDataKey = libsodiumEncryptForPublicKey(this.credential.encryption.machineKey, derivedPublicKey);
2084
+ dataEncryptionKey = new Uint8Array(encryptedDataKey.length + 1);
2085
+ dataEncryptionKey.set([0], 0);
2086
+ dataEncryptionKey.set(encryptedDataKey, 1);
2087
+ } else {
2088
+ encryptionKey = this.credential.encryption.secret;
2089
+ encryptionVariant = "legacy";
2090
+ }
2091
+ const response = await axios.post(
2092
+ `${configuration.serverUrl}/v1/machines`,
2093
+ {
2094
+ id: opts.machineId,
2095
+ metadata: encodeBase64(encrypt(encryptionKey, encryptionVariant, opts.metadata)),
2096
+ daemonState: opts.daemonState ? encodeBase64(encrypt(encryptionKey, encryptionVariant, opts.daemonState)) : void 0,
2097
+ dataEncryptionKey: dataEncryptionKey ? encodeBase64(dataEncryptionKey) : void 0
2098
+ },
2099
+ {
2100
+ headers: {
2101
+ "Authorization": `Bearer ${this.credential.token}`,
2102
+ "Content-Type": "application/json"
2103
+ },
2104
+ timeout: 6e4
2105
+ // 1 minute timeout for very bad network connections
2106
+ }
2107
+ );
2108
+ if (response.status !== 200) {
2109
+ console.error(chalk.red(`[API] Failed to create machine: ${response.statusText}`));
2110
+ console.log(chalk.yellow(`[API] Failed to create machine: ${response.statusText}, most likely you have re-authenticated, but you still have a machine associated with the old account. Now we are trying to re-associate the machine with the new account. That is not allowed. Please run 'happy doctor clean' to clean up your happy state, and try your original command again. Please create an issue on github if this is causing you problems. We apologize for the inconvenience.`));
2111
+ process.exit(1);
2112
+ }
2113
+ const raw = response.data.machine;
2114
+ logger.debug(`[API] Machine ${opts.machineId} registered/updated with server`);
2115
+ const machine = {
2116
+ id: raw.id,
2117
+ encryptionKey,
2118
+ encryptionVariant,
2119
+ metadata: raw.metadata ? decrypt(encryptionKey, encryptionVariant, decodeBase64(raw.metadata)) : null,
2120
+ metadataVersion: raw.metadataVersion || 0,
2121
+ daemonState: raw.daemonState ? decrypt(encryptionKey, encryptionVariant, decodeBase64(raw.daemonState)) : null,
2122
+ daemonStateVersion: raw.daemonStateVersion || 0
2123
+ };
2124
+ return machine;
2125
+ }
2126
+ sessionSyncClient(session) {
2127
+ return new ApiSessionClient(this.credential.token, session);
2128
+ }
2129
+ machineSyncClient(machine) {
2130
+ return new ApiMachineClient(this.credential.token, machine);
2131
+ }
2132
+ push() {
2133
+ return this.pushClient;
2134
+ }
2135
+ /**
2136
+ * Register a vendor API token with the server
2137
+ * The token is sent as a JSON string - server handles encryption
2138
+ */
2139
+ async registerVendorToken(vendor, apiKey) {
2140
+ try {
2141
+ const response = await axios.post(
2142
+ `${configuration.serverUrl}/v1/connect/${vendor}/register`,
2143
+ {
2144
+ token: JSON.stringify(apiKey)
2145
+ },
2146
+ {
2147
+ headers: {
2148
+ "Authorization": `Bearer ${this.credential.token}`,
2149
+ "Content-Type": "application/json"
2150
+ },
2151
+ timeout: 5e3
2152
+ }
2153
+ );
2154
+ if (response.status !== 200 && response.status !== 201) {
2155
+ throw new Error(`Server returned status ${response.status}`);
2156
+ }
2157
+ logger.debug(`[API] Vendor token for ${vendor} registered successfully`);
2158
+ } catch (error) {
2159
+ logger.debug(`[API] [ERROR] Failed to register vendor token:`, error);
2160
+ throw new Error(`Failed to register vendor token: ${error instanceof Error ? error.message : "Unknown error"}`);
2161
+ }
2162
+ }
2163
+ }
2164
+
2165
+ const UsageSchema = z$1.object({
2166
+ input_tokens: z$1.number().int().nonnegative(),
2167
+ cache_creation_input_tokens: z$1.number().int().nonnegative().optional(),
2168
+ cache_read_input_tokens: z$1.number().int().nonnegative().optional(),
2169
+ output_tokens: z$1.number().int().nonnegative(),
2170
+ service_tier: z$1.string().optional()
2171
+ }).passthrough();
2172
+ const RawJSONLinesSchema = z$1.discriminatedUnion("type", [
2173
+ // User message - validates uuid and message.content
2174
+ z$1.object({
2175
+ type: z$1.literal("user"),
2176
+ isSidechain: z$1.boolean().optional(),
2177
+ isMeta: z$1.boolean().optional(),
2178
+ uuid: z$1.string(),
2179
+ // Used in getMessageKey()
2180
+ message: z$1.object({
2181
+ content: z$1.union([z$1.string(), z$1.any()])
2182
+ // Used in sessionScanner.ts
2183
+ }).passthrough()
2184
+ }).passthrough(),
2185
+ // Assistant message - validates message object with usage and content
2186
+ z$1.object({
2187
+ uuid: z$1.string(),
2188
+ type: z$1.literal("assistant"),
2189
+ message: z$1.object({
2190
+ // Entire message used in getMessageKey()
2191
+ usage: UsageSchema.optional(),
2192
+ // Used in apiSession.ts
2193
+ content: z$1.any()
2194
+ // Used in tests
2195
+ }).passthrough()
2196
+ }).passthrough(),
2197
+ // Summary message - validates summary and leafUuid
2198
+ z$1.object({
2199
+ type: z$1.literal("summary"),
2200
+ summary: z$1.string(),
2201
+ // Used in apiSession.ts
2202
+ leafUuid: z$1.string()
2203
+ // Used in getMessageKey()
2204
+ }).passthrough(),
2205
+ // System message - validates uuid
2206
+ z$1.object({
2207
+ type: z$1.literal("system"),
2208
+ uuid: z$1.string()
2209
+ // Used in getMessageKey()
2210
+ }).passthrough()
2211
+ ]);
2212
+
2213
+ export { ApiClient as A, clearCredentials as B, clearMachineId as C, getLatestDaemonLog as D, RawJSONLinesSchema as R, ApiSessionClient as a, decrypt as b, configuration as c, decodeBase64 as d, libsodiumDecryptFromPublicKey as e, formatTimeAgo as f, encodeBase64 as g, encrypt as h, packageJson as i, backoff as j, delay as k, logger as l, AsyncLock as m, readDaemonState as n, clearDaemonState as o, projectPath as p, readCredentials as q, readSettings as r, encodeBase64Url as s, writeCredentialsDataKey as t, updateSettings as u, acquireDaemonLock as v, writeCredentialsLegacy as w, writeDaemonState as x, releaseDaemonLock as y, authChallenge as z };