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