@cerulin/chell 0.2.5

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