zenflo 0.11.2

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