very-happy-cli 0.2.124 → 0.2.125

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 (49) hide show
  1. package/dist/{AcpBackend-CT9TOBEM.mjs → AcpBackend-DOQGItcS.mjs} +2 -1
  2. package/dist/{AcpBackend-au0veuIF.cjs → AcpBackend-ssQpTLks.cjs} +30 -29
  3. package/dist/{AcpSessionManager-p1tj7FxF.mjs → AcpSessionManager-D4WkNsRs.mjs} +1 -1
  4. package/dist/{AcpSessionManager-BCWeBKDd.cjs → AcpSessionManager-DHLc-D50.cjs} +9 -9
  5. package/dist/agentGuidance-Cg9ZG1pP.cjs +236 -0
  6. package/dist/agentGuidance-QpYwykb9.mjs +224 -0
  7. package/dist/codex/happyMcpStdioBridge.cjs +29 -6
  8. package/dist/codex/happyMcpStdioBridge.mjs +25 -2
  9. package/dist/{config-GzzqE5Ev.cjs → config-BxHOGtEK.cjs} +11 -11
  10. package/dist/{config-DwMic6AC.mjs → config-CZNIz3W0.mjs} +11 -11
  11. package/dist/{index-DgN9P02i.cjs → index-CBj99SO6.cjs} +53 -19
  12. package/dist/{index-SQKnWyz-.mjs → index-CrSifgJM.mjs} +2046 -1719
  13. package/dist/{index-B3-daYaX.mjs → index-D-BgvQi5.mjs} +8 -8
  14. package/dist/{index-C69uF6Up.cjs → index-D_Rm9dw9.cjs} +8 -8
  15. package/dist/{index-DI_VC3vJ.cjs → index-Do-kjc30.cjs} +2191 -1864
  16. package/dist/{index-Ba6Fu6MJ.mjs → index-Jrk6ud3g.mjs} +49 -15
  17. package/dist/index.cjs +5 -5
  18. package/dist/index.mjs +5 -5
  19. package/dist/{installTerminalHooks-CvMt8cBI.cjs → installTerminalHooks-CPsdeOM4.cjs} +9 -9
  20. package/dist/{installTerminalHooks-Df4hzzdM.mjs → installTerminalHooks-Z1Jb6yjb.mjs} +8 -8
  21. package/dist/lib.cjs +12 -12
  22. package/dist/lib.d.cts +3 -0
  23. package/dist/lib.d.mts +3 -0
  24. package/dist/lib.mjs +9 -9
  25. package/dist/limits-DViGHwSj.cjs +1198 -0
  26. package/dist/limits-FjbPJPsF.mjs +1129 -0
  27. package/dist/{mcp-DnyLwSPq.cjs → mcp-BbQ5FWcQ.cjs} +11 -10
  28. package/dist/{mcp-C0oW5u-b.mjs → mcp-zqPJ94Bk.mjs} +7 -6
  29. package/dist/resources-CVl7NdOB.cjs +83 -0
  30. package/dist/resources-D-mn7ptO.mjs +80 -0
  31. package/dist/{runGemini-_FHrxuHN.cjs → runGemini-BnHGYX-H.cjs} +30 -30
  32. package/dist/{runGemini-mqLjz-M7.mjs → runGemini-Bu49s_bN.mjs} +13 -13
  33. package/dist/{runOpenClaw-C5VZQ6Na.cjs → runOpenClaw-3Ld1eoWV.cjs} +24 -24
  34. package/dist/{runOpenClaw-Bs03yQHe.mjs → runOpenClaw-CznAYPCh.mjs} +9 -9
  35. package/dist/{send-BaLjQPZQ.mjs → send-BevgS1mf.mjs} +10 -10
  36. package/dist/{send-BD2gTVoP.cjs → send-DCzyBxLl.cjs} +10 -10
  37. package/dist/{sessions-ggBePfSY.mjs → sessions-Ba2oRTmw.mjs} +10 -10
  38. package/dist/{sessions-B108j_Xj.cjs → sessions-DSoaBHwA.cjs} +11 -11
  39. package/dist/{spawn-iI8w8sD7.cjs → spawn-CqMLY6dE.cjs} +21 -21
  40. package/dist/{spawn-CORFRb9D.mjs → spawn-j9KBfj4e.mjs} +21 -21
  41. package/dist/teams-C0ggJTJ-.mjs +164 -0
  42. package/dist/teams-CmU3K9vB.cjs +166 -0
  43. package/dist/{types-CZIwVSN2.cjs → types-BGHnQXl5.cjs} +462 -1571
  44. package/dist/{types-gDOmwOKw.mjs → types-DLDkfrTC.mjs} +76 -1148
  45. package/package.json +7 -7
  46. package/dist/agentGuidance-BifkGXdE.cjs +0 -46
  47. package/dist/agentGuidance-C2_pkgRI.mjs +0 -37
  48. package/dist/limits-CwFb5S2b.mjs +0 -22
  49. package/dist/limits-KdWKmwtH.cjs +0 -28
@@ -0,0 +1,1129 @@
1
+ import { mkdir, chmod, writeFile, readFile, open, unlink, stat, rename } from 'node:fs/promises';
2
+ import { mkdirSync, chmodSync, readdirSync, statSync, appendFileSync, writeFileSync, existsSync, readFileSync, constants, unlinkSync, renameSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, basename } from 'node:path';
5
+ import * as z from 'zod';
6
+ import { randomBytes, createCipheriv, createDecipheriv, createHash } from 'node:crypto';
7
+ import tweetnacl from 'tweetnacl';
8
+ import chalk from 'chalk';
9
+ import { inspect } from 'node:util';
10
+
11
+ var name = "very-happy-cli";
12
+ var version = "0.2.125";
13
+ var description = "Remote multi-agent workspace CLI with deep Claude integration, native terminal streaming, and self-hosting.";
14
+ var author = "Kirill Dubovitskiy";
15
+ var contributors = [
16
+ "Mereith (very-happy-cli fork)"
17
+ ];
18
+ var license = "MIT";
19
+ var engines = {
20
+ node: "^20.19.0 || ^22.13.0 || >=24.0.0"
21
+ };
22
+ var type = "module";
23
+ var homepage = "https://github.com/Mereithhh/very-happy";
24
+ var bugs = "https://github.com/Mereithhh/very-happy/issues";
25
+ var repository = {
26
+ type: "git",
27
+ url: "git+https://github.com/Mereithhh/very-happy.git"
28
+ };
29
+ var bin = {
30
+ "very-happy": "./bin/very-happy.mjs",
31
+ "very-happy-mcp": "./bin/very-happy-mcp.mjs"
32
+ };
33
+ var main = "./dist/index.cjs";
34
+ var module$1 = "./dist/index.mjs";
35
+ var types = "./dist/index.d.cts";
36
+ var exports$1 = {
37
+ ".": {
38
+ require: {
39
+ types: "./dist/index.d.cts",
40
+ "default": "./dist/index.cjs"
41
+ },
42
+ "import": {
43
+ types: "./dist/index.d.mts",
44
+ "default": "./dist/index.mjs"
45
+ }
46
+ },
47
+ "./lib": {
48
+ require: {
49
+ types: "./dist/lib.d.cts",
50
+ "default": "./dist/lib.cjs"
51
+ },
52
+ "import": {
53
+ types: "./dist/lib.d.mts",
54
+ "default": "./dist/lib.mjs"
55
+ }
56
+ },
57
+ "./codex/happyMcpStdioBridge": {
58
+ require: {
59
+ types: "./dist/codex/happyMcpStdioBridge.d.cts",
60
+ "default": "./dist/codex/happyMcpStdioBridge.cjs"
61
+ },
62
+ "import": {
63
+ types: "./dist/codex/happyMcpStdioBridge.d.mts",
64
+ "default": "./dist/codex/happyMcpStdioBridge.mjs"
65
+ }
66
+ }
67
+ };
68
+ var files = [
69
+ "dist",
70
+ "bin",
71
+ "scripts",
72
+ "tools/licenses",
73
+ "package.json",
74
+ "README.md",
75
+ "LICENSE"
76
+ ];
77
+ var scripts = {
78
+ typecheck: "tsc --noEmit",
79
+ "bundle:server": "node scripts/bundle-server.cjs",
80
+ "bundle:server:all": "node scripts/bundle-server.cjs --all-platforms",
81
+ "bundle:webapp": "node scripts/bundle-webapp.cjs",
82
+ build: "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc --noEmit && pkgroll",
83
+ test: "pnpm run build && vitest run --project unit",
84
+ "test:integration": "pnpm run build && vitest run --project integration-empty --project integration-plan-mode --project integration-authenticated",
85
+ "cli:install": "node scripts/install-local.cjs",
86
+ prepublishOnly: "pnpm test",
87
+ postinstall: "node scripts/unpack-tools.cjs && node scripts/fix-pty-perms.cjs"
88
+ };
89
+ var dependencies = {
90
+ "@agentclientprotocol/sdk": "^0.14.1",
91
+ "@anthropic-ai/claude-agent-sdk": "^0.3.232",
92
+ "@anthropic-ai/sandbox-runtime": "^0.0.37",
93
+ "@modelcontextprotocol/sdk": "1.30.0",
94
+ "@noble/ed25519": "^3.0.0",
95
+ "@noble/hashes": "^2.0.1",
96
+ "@paralleldrive/cuid2": "^2.2.2",
97
+ "@stablelib/base64": "^2.0.1",
98
+ "@stablelib/hex": "^2.0.1",
99
+ "@types/cross-spawn": "^6.0.6",
100
+ "@types/http-proxy": "^1.17.17",
101
+ "@types/react": "^19.2.7",
102
+ "@types/tmp": "^0.2.6",
103
+ axios: "^1.13.2",
104
+ chalk: "^5.6.2",
105
+ "cross-spawn": "^7.0.6",
106
+ "expo-server-sdk": "^3.15.0",
107
+ fastify: "5.8.5",
108
+ "fastify-type-provider-zod": "^6.1.0",
109
+ "http-proxy": "^1.18.1",
110
+ "http-proxy-middleware": "^3.0.7",
111
+ ink: "^6.5.1",
112
+ inquirer: "^13.2.2",
113
+ "node-pty": "^1.0.0",
114
+ open: "^10.2.0",
115
+ "ps-list": "^8.1.1",
116
+ react: "^19.2.0",
117
+ "socket.io-client": "^4.8.1",
118
+ tar: "^7.5.22",
119
+ tmp: "^0.2.7",
120
+ tweetnacl: "^1.0.3",
121
+ ws: "^8.21.3",
122
+ zod: "^4.0.0"
123
+ };
124
+ var optionalDependencies = {
125
+ "very-happy-tools-arm64-darwin": "0.2.125",
126
+ "very-happy-tools-x64-darwin": "0.2.125",
127
+ "very-happy-tools-arm64-linux": "0.2.125",
128
+ "very-happy-tools-x64-linux": "0.2.125",
129
+ "very-happy-tools-arm64-win32": "0.2.125",
130
+ "very-happy-tools-x64-win32": "0.2.125"
131
+ };
132
+ var devDependencies = {
133
+ "@slopus/happy-wire": "workspace:*",
134
+ "@xterm/addon-serialize": "0.13.0",
135
+ "@xterm/headless": "5.5.0",
136
+ "@types/inquirer": "^9.0.9",
137
+ "@types/node": ">=20",
138
+ "@types/ws": "^8.18.1",
139
+ "cross-env": "^10.1.0",
140
+ dotenv: "^16.6.1",
141
+ pkgroll: "^2.14.2",
142
+ "ts-node": "^10",
143
+ tsx: "^4.20.6",
144
+ typescript: "5.9.3",
145
+ vitest: "3.2.6"
146
+ };
147
+ var publishConfig = {
148
+ registry: "https://registry.npmjs.org"
149
+ };
150
+ var packageManager = "pnpm@10.11.0";
151
+ var packageJson = {
152
+ name: name,
153
+ version: version,
154
+ description: description,
155
+ author: author,
156
+ contributors: contributors,
157
+ license: license,
158
+ engines: engines,
159
+ type: type,
160
+ homepage: homepage,
161
+ bugs: bugs,
162
+ repository: repository,
163
+ bin: bin,
164
+ main: main,
165
+ module: module$1,
166
+ types: types,
167
+ exports: exports$1,
168
+ files: files,
169
+ scripts: scripts,
170
+ dependencies: dependencies,
171
+ optionalDependencies: optionalDependencies,
172
+ devDependencies: devDependencies,
173
+ publishConfig: publishConfig,
174
+ packageManager: packageManager
175
+ };
176
+
177
+ const PRIVATE_DIRECTORY_MODE = 448;
178
+ const PRIVATE_FILE_MODE = 384;
179
+ function ignoreUnsupportedPermissions(error) {
180
+ if (process.platform !== "win32") throw error;
181
+ }
182
+ function ensurePrivateDirectorySync(path) {
183
+ mkdirSync(path, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
184
+ try {
185
+ chmodSync(path, PRIVATE_DIRECTORY_MODE);
186
+ } catch (error) {
187
+ ignoreUnsupportedPermissions(error);
188
+ }
189
+ }
190
+ async function ensurePrivateDirectory(path) {
191
+ await mkdir(path, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
192
+ try {
193
+ await chmod(path, PRIVATE_DIRECTORY_MODE);
194
+ } catch (error) {
195
+ ignoreUnsupportedPermissions(error);
196
+ }
197
+ }
198
+ function hardenPrivateFileSync(path) {
199
+ try {
200
+ chmodSync(path, PRIVATE_FILE_MODE);
201
+ } catch (error) {
202
+ ignoreUnsupportedPermissions(error);
203
+ }
204
+ }
205
+ function hardenPrivateDirectoryFilesSync(path) {
206
+ for (const name of readdirSync(path)) {
207
+ const candidate = join(path, name);
208
+ try {
209
+ if (statSync(candidate).isFile()) hardenPrivateFileSync(candidate);
210
+ } catch {
211
+ }
212
+ }
213
+ }
214
+ async function hardenPrivateFile(path) {
215
+ try {
216
+ await chmod(path, PRIVATE_FILE_MODE);
217
+ } catch (error) {
218
+ ignoreUnsupportedPermissions(error);
219
+ }
220
+ }
221
+ function writePrivateFileSync(path, data) {
222
+ writeFileSync(path, data, { encoding: "utf8", mode: PRIVATE_FILE_MODE });
223
+ hardenPrivateFileSync(path);
224
+ }
225
+ async function writePrivateFile(path, data) {
226
+ await writeFile(path, data, { encoding: "utf8", mode: PRIVATE_FILE_MODE });
227
+ await hardenPrivateFile(path);
228
+ }
229
+ function appendPrivateFileSync(path, data) {
230
+ appendFileSync(path, data, { encoding: "utf8", mode: PRIVATE_FILE_MODE });
231
+ hardenPrivateFileSync(path);
232
+ }
233
+
234
+ const DEFAULT_RELAY_URL = "https://veryhappy.dev";
235
+ function normalizeHttpEndpoint(value, source) {
236
+ const trimmed = value.trim();
237
+ let parsed;
238
+ try {
239
+ parsed = new URL(trimmed);
240
+ } catch {
241
+ throw new Error(`${source} must be an absolute http(s) origin`);
242
+ }
243
+ const onlyOriginPath = /^\/+$/u.test(parsed.pathname);
244
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || parsed.username.length > 0 || parsed.password.length > 0 || !onlyOriginPath || parsed.search.length > 0 || parsed.hash.length > 0) {
245
+ throw new Error(`${source} must be an http(s) origin without credentials, path, query, or fragment`);
246
+ }
247
+ return parsed.origin;
248
+ }
249
+ function resolveHttpEndpoint(environmentValue, settingsValue, environmentName, settingsName) {
250
+ if (environmentValue !== void 0) {
251
+ return normalizeHttpEndpoint(environmentValue, environmentName);
252
+ }
253
+ if (settingsValue !== void 0) {
254
+ return normalizeHttpEndpoint(settingsValue, `settings.${settingsName}`);
255
+ }
256
+ return DEFAULT_RELAY_URL;
257
+ }
258
+ class Configuration {
259
+ serverUrl;
260
+ webappUrl;
261
+ isDaemonProcess;
262
+ // Directories and paths (from persistence)
263
+ happyHomeDir;
264
+ logsDir;
265
+ settingsFile;
266
+ privateKeyFile;
267
+ daemonStateFile;
268
+ daemonLockFile;
269
+ sessionsFile;
270
+ currentCliVersion;
271
+ isExperimentalEnabled;
272
+ disableCaffeinate;
273
+ constructor() {
274
+ const args = process.argv.slice(2);
275
+ this.isDaemonProcess = args.length >= 2 && args[0] === "daemon" && args[1] === "start-sync";
276
+ if (process.env.HAPPY_HOME_DIR) {
277
+ const expandedPath = process.env.HAPPY_HOME_DIR.replace(/^~/, homedir());
278
+ this.happyHomeDir = expandedPath;
279
+ } else {
280
+ this.happyHomeDir = join(homedir(), ".happy");
281
+ }
282
+ this.logsDir = join(this.happyHomeDir, "logs");
283
+ this.settingsFile = join(this.happyHomeDir, "settings.json");
284
+ this.privateKeyFile = join(this.happyHomeDir, "access.key");
285
+ this.daemonStateFile = join(this.happyHomeDir, "daemon.state.json");
286
+ this.daemonLockFile = join(this.happyHomeDir, "daemon.state.json.lock");
287
+ this.sessionsFile = join(this.happyHomeDir, "sessions.json");
288
+ try {
289
+ this.serverUrl = resolveHttpEndpoint(
290
+ process.env.HAPPY_SERVER_URL,
291
+ readSettingsStringSync(this.settingsFile, "serverUrl"),
292
+ "HAPPY_SERVER_URL",
293
+ "serverUrl"
294
+ );
295
+ this.webappUrl = resolveHttpEndpoint(
296
+ process.env.HAPPY_WEBAPP_URL,
297
+ readSettingsStringSync(this.settingsFile, "webappUrl"),
298
+ "HAPPY_WEBAPP_URL",
299
+ "webappUrl"
300
+ );
301
+ } catch (error) {
302
+ const message = error instanceof Error ? error.message : "invalid client endpoint";
303
+ process.stderr.write(`[very-happy] Configuration error: ${message}
304
+ `);
305
+ process.exit(1);
306
+ }
307
+ this.isExperimentalEnabled = ["true", "1", "yes"].includes(process.env.HAPPY_EXPERIMENTAL?.toLowerCase() || "");
308
+ this.disableCaffeinate = ["true", "1", "yes"].includes(process.env.HAPPY_DISABLE_CAFFEINATE?.toLowerCase() || "");
309
+ this.currentCliVersion = packageJson.version;
310
+ const variant = process.env.HAPPY_VARIANT || "stable";
311
+ if (!this.isDaemonProcess && variant === "dev") {
312
+ console.log("\x1B[33m\u{1F527} DEV MODE\x1B[0m - Data: " + this.happyHomeDir);
313
+ }
314
+ ensurePrivateDirectorySync(this.happyHomeDir);
315
+ ensurePrivateDirectorySync(this.logsDir);
316
+ for (const privateFile of [
317
+ this.settingsFile,
318
+ this.privateKeyFile,
319
+ this.daemonStateFile,
320
+ this.daemonLockFile,
321
+ this.sessionsFile
322
+ ]) {
323
+ if (existsSync(privateFile)) hardenPrivateFileSync(privateFile);
324
+ }
325
+ hardenPrivateDirectoryFilesSync(this.logsDir);
326
+ }
327
+ }
328
+ function readSettingsStringSync(settingsFile, key) {
329
+ try {
330
+ if (!existsSync(settingsFile)) return void 0;
331
+ const raw = JSON.parse(readFileSync(settingsFile, "utf8"));
332
+ const value = raw?.[key];
333
+ return typeof value === "string" && value.length > 0 ? value : void 0;
334
+ } catch {
335
+ return void 0;
336
+ }
337
+ }
338
+ const configuration = new Configuration();
339
+
340
+ function encodeBase64(buffer, variant = "base64") {
341
+ if (variant === "base64url") {
342
+ return encodeBase64Url(buffer);
343
+ }
344
+ return Buffer.from(buffer).toString("base64");
345
+ }
346
+ function encodeBase64Url(buffer) {
347
+ return Buffer.from(buffer).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
348
+ }
349
+ function decodeBase64(base64, variant = "base64") {
350
+ if (variant === "base64url") {
351
+ const base64Standard = base64.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - base64.length % 4) % 4);
352
+ return new Uint8Array(Buffer.from(base64Standard, "base64"));
353
+ }
354
+ return new Uint8Array(Buffer.from(base64, "base64"));
355
+ }
356
+ function getRandomBytes(size) {
357
+ return new Uint8Array(randomBytes(size));
358
+ }
359
+ function libsodiumPublicKeyFromSecretKey(seed) {
360
+ const hashedSeed = new Uint8Array(createHash("sha512").update(seed).digest());
361
+ const secretKey = hashedSeed.slice(0, 32);
362
+ return new Uint8Array(tweetnacl.box.keyPair.fromSecretKey(secretKey).publicKey);
363
+ }
364
+ function libsodiumEncryptForPublicKey(data, recipientPublicKey) {
365
+ const ephemeralKeyPair = tweetnacl.box.keyPair();
366
+ const nonce = getRandomBytes(tweetnacl.box.nonceLength);
367
+ const encrypted = tweetnacl.box(data, nonce, recipientPublicKey, ephemeralKeyPair.secretKey);
368
+ const result = new Uint8Array(ephemeralKeyPair.publicKey.length + nonce.length + encrypted.length);
369
+ result.set(ephemeralKeyPair.publicKey, 0);
370
+ result.set(nonce, ephemeralKeyPair.publicKey.length);
371
+ result.set(encrypted, ephemeralKeyPair.publicKey.length + nonce.length);
372
+ return result;
373
+ }
374
+ function encryptLegacy(data, secret) {
375
+ const nonce = getRandomBytes(tweetnacl.secretbox.nonceLength);
376
+ const encrypted = tweetnacl.secretbox(new TextEncoder().encode(JSON.stringify(data)), nonce, secret);
377
+ const result = new Uint8Array(nonce.length + encrypted.length);
378
+ result.set(nonce);
379
+ result.set(encrypted, nonce.length);
380
+ return result;
381
+ }
382
+ function decryptLegacy(data, secret) {
383
+ const nonce = data.slice(0, tweetnacl.secretbox.nonceLength);
384
+ const encrypted = data.slice(tweetnacl.secretbox.nonceLength);
385
+ const decrypted = tweetnacl.secretbox.open(encrypted, nonce, secret);
386
+ if (!decrypted) {
387
+ return null;
388
+ }
389
+ return JSON.parse(new TextDecoder().decode(decrypted));
390
+ }
391
+ function decryptBlob(bundle, key) {
392
+ if (bundle.length < tweetnacl.secretbox.nonceLength + 16) {
393
+ return null;
394
+ }
395
+ const nonce = bundle.slice(0, tweetnacl.secretbox.nonceLength);
396
+ const ciphertext = bundle.slice(tweetnacl.secretbox.nonceLength);
397
+ const decrypted = tweetnacl.secretbox.open(ciphertext, nonce, key);
398
+ if (!decrypted) {
399
+ return null;
400
+ }
401
+ return new Uint8Array(decrypted);
402
+ }
403
+ function encryptWithDataKey(data, dataKey) {
404
+ const nonce = getRandomBytes(12);
405
+ const cipher = createCipheriv("aes-256-gcm", dataKey, nonce);
406
+ const plaintext = new TextEncoder().encode(JSON.stringify(data));
407
+ const encrypted = Buffer.concat([
408
+ cipher.update(plaintext),
409
+ cipher.final()
410
+ ]);
411
+ const authTag = cipher.getAuthTag();
412
+ const bundle = new Uint8Array(12 + encrypted.length + 16 + 1);
413
+ bundle.set([0], 0);
414
+ bundle.set(nonce, 1);
415
+ bundle.set(new Uint8Array(encrypted), 13);
416
+ bundle.set(new Uint8Array(authTag), 13 + encrypted.length);
417
+ return bundle;
418
+ }
419
+ function decryptWithDataKey(bundle, dataKey) {
420
+ if (bundle.length < 1) {
421
+ return null;
422
+ }
423
+ if (bundle[0] !== 0) {
424
+ return null;
425
+ }
426
+ if (bundle.length < 12 + 16 + 1) {
427
+ return null;
428
+ }
429
+ const nonce = bundle.slice(1, 13);
430
+ const authTag = bundle.slice(bundle.length - 16);
431
+ const ciphertext = bundle.slice(13, bundle.length - 16);
432
+ try {
433
+ const decipher = createDecipheriv("aes-256-gcm", dataKey, nonce);
434
+ decipher.setAuthTag(authTag);
435
+ const decrypted = Buffer.concat([
436
+ decipher.update(ciphertext),
437
+ decipher.final()
438
+ ]);
439
+ return JSON.parse(new TextDecoder().decode(decrypted));
440
+ } catch (error) {
441
+ return null;
442
+ }
443
+ }
444
+ function encrypt(key, variant, data) {
445
+ if (variant === "legacy") {
446
+ return encryptLegacy(data, key);
447
+ } else {
448
+ return encryptWithDataKey(data, key);
449
+ }
450
+ }
451
+ function decrypt(key, variant, data) {
452
+ if (variant === "legacy") {
453
+ return decryptLegacy(data, key);
454
+ } else {
455
+ return decryptWithDataKey(data, key);
456
+ }
457
+ }
458
+
459
+ function sensitiveKey(key) {
460
+ const normalized = key.toLowerCase().replace(/[_\-\s]/g, "");
461
+ return /(token|secret|password|authorization|cookie|credential|apikey|privatekey|encryptionkey|accesskey|claimsecret)/.test(normalized);
462
+ }
463
+ function redactLogString(value) {
464
+ return value.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1[REDACTED]").replace(/([?&](?:token|secret|password|api[_-]?key)=)[^&#\s]+/gi, "$1[REDACTED]").replace(/((?:token|secret|password|api[_-]?key)\s*[=:]\s*)[^\s,;]+/gi, "$1[REDACTED]");
465
+ }
466
+ function redactLogValue(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
467
+ if (typeof value === "string") return redactLogString(value);
468
+ if (value === null || typeof value !== "object") return value;
469
+ if (depth >= 6) return "[TRUNCATED]";
470
+ if (seen.has(value)) return "[CIRCULAR]";
471
+ seen.add(value);
472
+ if (value instanceof Error) {
473
+ const error = value;
474
+ return {
475
+ name: error.name,
476
+ message: redactLogString(error.message),
477
+ ...typeof error.code === "string" || typeof error.code === "number" ? { code: error.code } : {},
478
+ ...typeof (error.status ?? error.response?.status) === "number" ? { status: error.status ?? error.response?.status } : {}
479
+ };
480
+ }
481
+ if (Array.isArray(value)) return value.map((item) => redactLogValue(item, depth + 1, seen));
482
+ const result = {};
483
+ for (const [key, child] of Object.entries(value)) {
484
+ if (sensitiveKey(key)) {
485
+ result[key] = "[REDACTED]";
486
+ } else if (key === "environmentVariables" && child && typeof child === "object") {
487
+ result[key] = { names: Object.keys(child).sort() };
488
+ } else {
489
+ result[key] = redactLogValue(child, depth + 1, seen);
490
+ }
491
+ }
492
+ return result;
493
+ }
494
+
495
+ function createTimestampForFilename(date = /* @__PURE__ */ new Date()) {
496
+ return date.toLocaleString("sv-SE", {
497
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
498
+ year: "numeric",
499
+ month: "2-digit",
500
+ day: "2-digit",
501
+ hour: "2-digit",
502
+ minute: "2-digit",
503
+ second: "2-digit"
504
+ }).replace(/[: ]/g, "-").replace(/,/g, "") + "-pid-" + process.pid;
505
+ }
506
+ function createTimestampForLogEntry(date = /* @__PURE__ */ new Date()) {
507
+ return date.toLocaleTimeString("en-US", {
508
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
509
+ hour12: false,
510
+ hour: "2-digit",
511
+ minute: "2-digit",
512
+ second: "2-digit",
513
+ fractionalSecondDigits: 3
514
+ });
515
+ }
516
+ function getSessionLogPath() {
517
+ const timestamp = createTimestampForFilename();
518
+ const filename = configuration.isDaemonProcess ? `${timestamp}-daemon.log` : `${timestamp}.log`;
519
+ return join(configuration.logsDir, filename);
520
+ }
521
+ function safeRemoteLogUrl(raw) {
522
+ if (!raw) return void 0;
523
+ try {
524
+ const url = new URL(raw);
525
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
526
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) return void 0;
527
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" && url.pathname !== "") return void 0;
528
+ return url.origin;
529
+ } catch {
530
+ return void 0;
531
+ }
532
+ }
533
+ class Logger {
534
+ constructor(logFilePath = getSessionLogPath()) {
535
+ this.logFilePath = logFilePath;
536
+ const remoteUrl = safeRemoteLogUrl(process.env.HAPPY_SERVER_URL);
537
+ const remoteToken = process.env.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING_TOKEN;
538
+ if (process.env.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING && remoteUrl && remoteToken && Buffer.byteLength(remoteToken) >= 32) {
539
+ this.dangerouslyUnencryptedServerLoggingUrl = remoteUrl;
540
+ this.dangerouslyUnencryptedServerLoggingToken = remoteToken;
541
+ console.log(chalk.yellow("[REMOTE LOGGING] Sending logs to server for AI debugging"));
542
+ }
543
+ }
544
+ dangerouslyUnencryptedServerLoggingUrl;
545
+ dangerouslyUnencryptedServerLoggingToken;
546
+ // Use local timezone for simplicity of locating the logs,
547
+ // in practice you will not need absolute timestamps
548
+ localTimezoneTimestamp() {
549
+ return createTimestampForLogEntry();
550
+ }
551
+ debug(message, ...args) {
552
+ this.logToFile(`[${this.localTimezoneTimestamp()}]`, message, ...args);
553
+ }
554
+ debugLargeJson(message, object, maxStringLength = 100, maxArrayLength = 10) {
555
+ if (!process.env.DEBUG) {
556
+ this.debug(`In production, skipping message inspection`);
557
+ return;
558
+ }
559
+ const truncateStrings = (obj) => {
560
+ if (typeof obj === "string") {
561
+ return obj.length > maxStringLength ? obj.substring(0, maxStringLength) + "... [truncated for logs]" : obj;
562
+ }
563
+ if (Array.isArray(obj)) {
564
+ const truncatedArray = obj.map((item) => truncateStrings(item)).slice(0, maxArrayLength);
565
+ if (obj.length > maxArrayLength) {
566
+ truncatedArray.push(`... [truncated array for logs up to ${maxArrayLength} items]`);
567
+ }
568
+ return truncatedArray;
569
+ }
570
+ if (obj && typeof obj === "object") {
571
+ const result = {};
572
+ for (const [key, value] of Object.entries(obj)) {
573
+ if (key === "usage") {
574
+ continue;
575
+ }
576
+ result[key] = truncateStrings(value);
577
+ }
578
+ return result;
579
+ }
580
+ return obj;
581
+ };
582
+ const truncatedObject = truncateStrings(redactLogValue(object));
583
+ const json = JSON.stringify(truncatedObject, null, 2);
584
+ this.logToFile(`[${this.localTimezoneTimestamp()}]`, redactLogString(message), "\n", json);
585
+ }
586
+ info(message, ...args) {
587
+ this.logToConsole("info", "", message, ...args);
588
+ this.debug(message, args);
589
+ }
590
+ infoDeveloper(message, ...args) {
591
+ this.debug(message, ...args);
592
+ if (process.env.DEBUG) {
593
+ this.logToConsole("info", "[DEV]", message, ...args);
594
+ }
595
+ }
596
+ warn(message, ...args) {
597
+ this.logToConsole("warn", "", message, ...args);
598
+ this.debug(`[WARN] ${message}`, ...args);
599
+ }
600
+ getLogPath() {
601
+ return this.logFilePath;
602
+ }
603
+ logToConsole(level, prefix, message, ...args) {
604
+ message = redactLogString(message);
605
+ args = args.map((arg) => redactLogValue(arg));
606
+ switch (level) {
607
+ case "debug": {
608
+ console.log(chalk.gray(prefix), message, ...args);
609
+ break;
610
+ }
611
+ case "error": {
612
+ console.error(chalk.red(prefix), message, ...args);
613
+ break;
614
+ }
615
+ case "info": {
616
+ console.log(chalk.blue(prefix), message, ...args);
617
+ break;
618
+ }
619
+ case "warn": {
620
+ console.log(chalk.yellow(prefix), message, ...args);
621
+ break;
622
+ }
623
+ default: {
624
+ this.debug("Unknown log level:", level);
625
+ console.log(chalk.blue(prefix), message, ...args);
626
+ break;
627
+ }
628
+ }
629
+ }
630
+ async sendToRemoteServer(level, message, ...args) {
631
+ if (!this.dangerouslyUnencryptedServerLoggingUrl) return;
632
+ try {
633
+ await fetch(this.dangerouslyUnencryptedServerLoggingUrl + "/logs-combined-from-cli-and-mobile-for-simple-ai-debugging", {
634
+ method: "POST",
635
+ headers: {
636
+ "Content-Type": "application/json",
637
+ "Authorization": `Bearer ${this.dangerouslyUnencryptedServerLoggingToken}`
638
+ },
639
+ body: JSON.stringify({
640
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
641
+ level,
642
+ message: `${redactLogString(message)} ${args.map((raw) => {
643
+ const safe = redactLogValue(raw);
644
+ return typeof safe === "object" ? JSON.stringify(safe, null, 2) : String(safe);
645
+ }).join(" ")}`,
646
+ source: "cli",
647
+ platform: process.platform
648
+ })
649
+ });
650
+ } catch (error) {
651
+ }
652
+ }
653
+ logToFile(prefix, message, ...args) {
654
+ const safeMessage = redactLogString(message);
655
+ const safeArgs = args.map((arg) => redactLogValue(arg));
656
+ const logLine = `${prefix} ${safeMessage} ${safeArgs.map(
657
+ (arg) => typeof arg === "string" ? arg : inspect(arg, { depth: 5, breakLength: 120 })
658
+ ).join(" ")}
659
+ `;
660
+ if (this.dangerouslyUnencryptedServerLoggingUrl) {
661
+ let level = "info";
662
+ if (prefix.includes(this.localTimezoneTimestamp())) {
663
+ level = "debug";
664
+ }
665
+ this.sendToRemoteServer(level, safeMessage, ...safeArgs).catch(() => {
666
+ });
667
+ }
668
+ try {
669
+ appendPrivateFileSync(this.logFilePath, logLine);
670
+ } catch (appendError) {
671
+ if (process.env.DEBUG) {
672
+ console.error("[DEV MODE ONLY THROWING] Failed to append to log file:", appendError);
673
+ throw appendError;
674
+ }
675
+ }
676
+ }
677
+ }
678
+ let logger = new Logger();
679
+ async function listDaemonLogFiles(limit = 50) {
680
+ try {
681
+ const logsDir = configuration.logsDir;
682
+ if (!existsSync(logsDir)) {
683
+ return [];
684
+ }
685
+ const logs = readdirSync(logsDir).filter((file) => file.endsWith("-daemon.log")).map((file) => {
686
+ const fullPath = join(logsDir, file);
687
+ const stats = statSync(fullPath);
688
+ return { file, path: fullPath, modified: stats.mtime };
689
+ }).sort((a, b) => b.modified.getTime() - a.modified.getTime());
690
+ try {
691
+ const { readDaemonState } = await Promise.resolve().then(function () { return persistence; });
692
+ const state = await readDaemonState();
693
+ if (!state) {
694
+ return logs;
695
+ }
696
+ if (state.daemonLogPath && existsSync(state.daemonLogPath)) {
697
+ const stats = statSync(state.daemonLogPath);
698
+ const persisted = {
699
+ file: basename(state.daemonLogPath),
700
+ path: state.daemonLogPath,
701
+ modified: stats.mtime
702
+ };
703
+ const idx = logs.findIndex((l) => l.path === persisted.path);
704
+ if (idx >= 0) {
705
+ const [found] = logs.splice(idx, 1);
706
+ logs.unshift(found);
707
+ } else {
708
+ logs.unshift(persisted);
709
+ }
710
+ }
711
+ } catch {
712
+ }
713
+ return logs.slice(0, Math.max(0, limit));
714
+ } catch {
715
+ return [];
716
+ }
717
+ }
718
+ async function getLatestDaemonLog() {
719
+ const [latest] = await listDaemonLogFiles(1);
720
+ return latest || null;
721
+ }
722
+
723
+ const DEFAULT_SERVER_URL = "https://veryhappy.dev";
724
+ const LEGACY_CLOUD_SERVER_URL = "https://happy.mereith.com";
725
+ const CLOUD_SERVER_URLS = [DEFAULT_SERVER_URL, LEGACY_CLOUD_SERVER_URL];
726
+ function sameRelay(left, right) {
727
+ try {
728
+ return new URL(left).origin === new URL(right).origin;
729
+ } catch {
730
+ return left.replace(/\/+$/, "") === right.replace(/\/+$/, "");
731
+ }
732
+ }
733
+ function credentialRelayProblem(credentialServerUrl, configuredServerUrl) {
734
+ if (credentialServerUrl) {
735
+ return sameRelay(credentialServerUrl, configuredServerUrl) ? void 0 : `Credentials belong to ${credentialServerUrl}, but the active relay is ${configuredServerUrl}.`;
736
+ }
737
+ if (CLOUD_SERVER_URLS.some((cloudUrl) => sameRelay(configuredServerUrl, cloudUrl))) {
738
+ return void 0;
739
+ }
740
+ return `These credentials predate relay tracking, so they cannot be safely reused with ${configuredServerUrl}.`;
741
+ }
742
+
743
+ const SandboxConfigSchema = z.object({
744
+ enabled: z.boolean().default(false),
745
+ workspaceRoot: z.string().optional(),
746
+ sessionIsolation: z.enum(["strict", "workspace", "custom"]).default("workspace"),
747
+ customWritePaths: z.array(z.string()).default([]),
748
+ denyReadPaths: z.array(z.string()).default(["~/.ssh", "~/.aws", "~/.gnupg"]),
749
+ extraWritePaths: z.array(z.string()).default(["/tmp"]),
750
+ denyWritePaths: z.array(z.string()).default([".env"]),
751
+ networkMode: z.enum(["blocked", "allowed", "custom"]).default("allowed"),
752
+ allowedDomains: z.array(z.string()).default([]),
753
+ deniedDomains: z.array(z.string()).default([]),
754
+ allowLocalBinding: z.boolean().default(true)
755
+ });
756
+ const SUPPORTED_SCHEMA_VERSION = 2;
757
+ const defaultSettings = {
758
+ schemaVersion: SUPPORTED_SCHEMA_VERSION,
759
+ onboardingCompleted: false,
760
+ sandboxConfig: void 0
761
+ };
762
+ function migrateSettings(raw, fromVersion) {
763
+ let migrated = { ...raw };
764
+ return migrated;
765
+ }
766
+ async function readSettingsOutcome() {
767
+ if (!existsSync(configuration.settingsFile)) {
768
+ return { kind: "absent" };
769
+ }
770
+ try {
771
+ return { kind: "ok", settings: await parseSettingsFile() };
772
+ } catch (error) {
773
+ return { kind: "unreadable", error: error?.message ?? String(error) };
774
+ }
775
+ }
776
+ async function readSettings() {
777
+ const outcome = await readSettingsOutcome();
778
+ if (outcome.kind === "ok") return outcome.settings;
779
+ if (outcome.kind === "unreadable") {
780
+ logger.warn(`Failed to read settings: ${outcome.error}`);
781
+ }
782
+ return { ...defaultSettings };
783
+ }
784
+ async function parseSettingsFile() {
785
+ const content = await readFile(configuration.settingsFile, "utf8");
786
+ const raw = JSON.parse(content);
787
+ const schemaVersion = raw.schemaVersion ?? 1;
788
+ if (schemaVersion > SUPPORTED_SCHEMA_VERSION) {
789
+ logger.warn(
790
+ `\u26A0\uFE0F Settings schema v${schemaVersion} > supported v${SUPPORTED_SCHEMA_VERSION}. Update happy-cli for full functionality.`
791
+ );
792
+ }
793
+ const migrated = migrateSettings(raw);
794
+ if (migrated.sandboxConfig !== void 0) {
795
+ try {
796
+ migrated.sandboxConfig = SandboxConfigSchema.parse(migrated.sandboxConfig);
797
+ } catch (error) {
798
+ logger.warn(`\u26A0\uFE0F Invalid sandbox config - skipping. Error: ${error.message}`);
799
+ migrated.sandboxConfig = void 0;
800
+ }
801
+ }
802
+ return { ...defaultSettings, ...migrated };
803
+ }
804
+ async function writeSettings(settings) {
805
+ await ensurePrivateDirectory(configuration.happyHomeDir);
806
+ const settingsWithVersion = {
807
+ ...settings,
808
+ schemaVersion: settings.schemaVersion ?? SUPPORTED_SCHEMA_VERSION
809
+ };
810
+ await writePrivateFile(configuration.settingsFile, JSON.stringify(settingsWithVersion, null, 2));
811
+ }
812
+ async function updateSettings(updater) {
813
+ const LOCK_RETRY_INTERVAL_MS = 100;
814
+ const MAX_LOCK_ATTEMPTS = 50;
815
+ const STALE_LOCK_TIMEOUT_MS = 1e4;
816
+ const lockFile = configuration.settingsFile + ".lock";
817
+ const tmpFile = configuration.settingsFile + ".tmp";
818
+ let fileHandle;
819
+ let attempts = 0;
820
+ while (attempts < MAX_LOCK_ATTEMPTS) {
821
+ try {
822
+ fileHandle = await open(lockFile, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, PRIVATE_FILE_MODE);
823
+ break;
824
+ } catch (err) {
825
+ if (err.code === "EEXIST") {
826
+ attempts++;
827
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
828
+ try {
829
+ const stats = await stat(lockFile);
830
+ if (Date.now() - stats.mtimeMs > STALE_LOCK_TIMEOUT_MS) {
831
+ await unlink(lockFile).catch(() => {
832
+ });
833
+ }
834
+ } catch {
835
+ }
836
+ } else {
837
+ throw err;
838
+ }
839
+ }
840
+ }
841
+ if (!fileHandle) {
842
+ throw new Error(`Failed to acquire settings lock after ${MAX_LOCK_ATTEMPTS * LOCK_RETRY_INTERVAL_MS / 1e3} seconds`);
843
+ }
844
+ try {
845
+ const outcome = await readSettingsOutcome();
846
+ if (outcome.kind === "unreadable") {
847
+ throw new Error(
848
+ `Settings file ${configuration.settingsFile} exists but could not be read (${outcome.error}). Refusing to overwrite it \u2014 fix or remove the file (a removed file is recreated with defaults).`
849
+ );
850
+ }
851
+ const current = outcome.kind === "ok" ? outcome.settings : { ...defaultSettings };
852
+ const updated = await updater(current);
853
+ await ensurePrivateDirectory(configuration.happyHomeDir);
854
+ await writePrivateFile(tmpFile, JSON.stringify(updated, null, 2));
855
+ await rename(tmpFile, configuration.settingsFile);
856
+ await hardenPrivateFile(configuration.settingsFile);
857
+ return updated;
858
+ } finally {
859
+ await fileHandle.close();
860
+ await unlink(lockFile).catch(() => {
861
+ });
862
+ }
863
+ }
864
+ const credentialsSchema = z.object({
865
+ token: z.string(),
866
+ authServerUrl: z.string().optional(),
867
+ secret: z.string().base64().nullish(),
868
+ // Legacy
869
+ encryption: z.object({
870
+ publicKey: z.string().base64(),
871
+ machineKey: z.string().base64()
872
+ }).nullish()
873
+ });
874
+ async function readCredentials() {
875
+ if (!existsSync(configuration.privateKeyFile)) {
876
+ return null;
877
+ }
878
+ try {
879
+ const keyBase64 = await readFile(configuration.privateKeyFile, "utf8");
880
+ const credentials = credentialsSchema.parse(JSON.parse(keyBase64));
881
+ if (credentials.secret) {
882
+ return {
883
+ token: credentials.token,
884
+ authServerUrl: credentials.authServerUrl,
885
+ encryption: {
886
+ type: "legacy",
887
+ secret: new Uint8Array(Buffer.from(credentials.secret, "base64"))
888
+ }
889
+ };
890
+ } else if (credentials.encryption) {
891
+ return {
892
+ token: credentials.token,
893
+ authServerUrl: credentials.authServerUrl,
894
+ encryption: {
895
+ type: "dataKey",
896
+ publicKey: new Uint8Array(Buffer.from(credentials.encryption.publicKey, "base64")),
897
+ machineKey: new Uint8Array(Buffer.from(credentials.encryption.machineKey, "base64"))
898
+ }
899
+ };
900
+ }
901
+ } catch {
902
+ return null;
903
+ }
904
+ return null;
905
+ }
906
+ async function readCredentialsForConfiguredRelay() {
907
+ const credentials = await readCredentials();
908
+ if (!credentials) return null;
909
+ const relayProblem = credentialRelayProblem(credentials.authServerUrl, configuration.serverUrl);
910
+ if (relayProblem) {
911
+ throw new Error(
912
+ `${relayProblem} Use a separate HAPPY_HOME_DIR for this relay, or run \`very-happy auth login --force\` before making relay requests.`
913
+ );
914
+ }
915
+ return credentials;
916
+ }
917
+ async function writeCredentialsLegacy(credentials) {
918
+ await ensurePrivateDirectory(configuration.happyHomeDir);
919
+ await writePrivateFile(configuration.privateKeyFile, JSON.stringify({
920
+ secret: encodeBase64(credentials.secret),
921
+ token: credentials.token,
922
+ authServerUrl: configuration.serverUrl
923
+ }, null, 2));
924
+ }
925
+ async function writeCredentialsDataKey(credentials) {
926
+ await ensurePrivateDirectory(configuration.happyHomeDir);
927
+ await writePrivateFile(configuration.privateKeyFile, JSON.stringify({
928
+ encryption: { publicKey: encodeBase64(credentials.publicKey), machineKey: encodeBase64(credentials.machineKey) },
929
+ token: credentials.token,
930
+ authServerUrl: configuration.serverUrl
931
+ }, null, 2));
932
+ }
933
+ async function clearCredentials() {
934
+ if (existsSync(configuration.privateKeyFile)) {
935
+ await unlink(configuration.privateKeyFile);
936
+ }
937
+ }
938
+ async function clearMachineId() {
939
+ await updateSettings((settings) => ({
940
+ ...settings,
941
+ machineId: void 0
942
+ }));
943
+ }
944
+ async function readDaemonState() {
945
+ try {
946
+ if (!existsSync(configuration.daemonStateFile)) {
947
+ return null;
948
+ }
949
+ const content = await readFile(configuration.daemonStateFile, "utf-8");
950
+ return JSON.parse(content);
951
+ } catch (error) {
952
+ console.error(`[PERSISTENCE] Daemon state file corrupted: ${configuration.daemonStateFile}`, error);
953
+ return null;
954
+ }
955
+ }
956
+ function writeDaemonState(state) {
957
+ writePrivateFileSync(configuration.daemonStateFile, JSON.stringify(state, null, 2));
958
+ }
959
+ async function clearDaemonState() {
960
+ if (existsSync(configuration.daemonStateFile)) {
961
+ await unlink(configuration.daemonStateFile);
962
+ }
963
+ if (existsSync(configuration.daemonLockFile)) {
964
+ try {
965
+ await unlink(configuration.daemonLockFile);
966
+ } catch {
967
+ }
968
+ }
969
+ }
970
+ async function acquireDaemonLock(maxAttempts = 5, delayIncrementMs = 200) {
971
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
972
+ try {
973
+ const fileHandle = await open(
974
+ configuration.daemonLockFile,
975
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,
976
+ PRIVATE_FILE_MODE
977
+ );
978
+ await fileHandle.writeFile(String(process.pid));
979
+ return fileHandle;
980
+ } catch (error) {
981
+ if (error.code === "EEXIST") {
982
+ try {
983
+ const lockPid = readFileSync(configuration.daemonLockFile, "utf-8").trim();
984
+ if (lockPid && !isNaN(Number(lockPid))) {
985
+ try {
986
+ process.kill(Number(lockPid), 0);
987
+ } catch {
988
+ unlinkSync(configuration.daemonLockFile);
989
+ continue;
990
+ }
991
+ }
992
+ } catch {
993
+ }
994
+ }
995
+ if (attempt === maxAttempts) {
996
+ return null;
997
+ }
998
+ const delayMs = attempt * delayIncrementMs;
999
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
1000
+ }
1001
+ }
1002
+ return null;
1003
+ }
1004
+ async function releaseDaemonLock(lockHandle) {
1005
+ try {
1006
+ await lockHandle.close();
1007
+ } catch {
1008
+ }
1009
+ try {
1010
+ if (existsSync(configuration.daemonLockFile)) {
1011
+ unlinkSync(configuration.daemonLockFile);
1012
+ }
1013
+ } catch {
1014
+ }
1015
+ }
1016
+ const SESSION_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1e3;
1017
+ function readPersistedSessions() {
1018
+ try {
1019
+ if (!existsSync(configuration.sessionsFile)) return {};
1020
+ const data = JSON.parse(readFileSync(configuration.sessionsFile, "utf-8"));
1021
+ if (!data?.sessions || typeof data.sessions !== "object") return {};
1022
+ const now = Date.now();
1023
+ const sessions = {};
1024
+ for (const [id, session] of Object.entries(data.sessions)) {
1025
+ if (now - session.savedAt < SESSION_MAX_AGE_MS) {
1026
+ sessions[id] = session;
1027
+ }
1028
+ }
1029
+ return sessions;
1030
+ } catch {
1031
+ return {};
1032
+ }
1033
+ }
1034
+ function readTrackedClaudeSessionIds() {
1035
+ try {
1036
+ if (!existsSync(configuration.sessionsFile)) return [];
1037
+ const data = JSON.parse(readFileSync(configuration.sessionsFile, "utf-8"));
1038
+ if (!data?.sessions || typeof data.sessions !== "object") return [];
1039
+ const ids = /* @__PURE__ */ new Set();
1040
+ for (const session of Object.values(data.sessions)) {
1041
+ const metadata = (session ?? {}).metadata;
1042
+ for (const id of [metadata?.claudeSessionId, metadata?.importedFromClaudeSessionId]) {
1043
+ if (typeof id === "string" && id.length > 0) ids.add(id.toLowerCase());
1044
+ }
1045
+ }
1046
+ return [...ids];
1047
+ } catch {
1048
+ return [];
1049
+ }
1050
+ }
1051
+ function persistSession(sessionId, session) {
1052
+ try {
1053
+ const existing = readPersistedSessions();
1054
+ existing[sessionId] = session;
1055
+ const tmpFile = configuration.sessionsFile + ".tmp";
1056
+ writePrivateFileSync(tmpFile, JSON.stringify({ sessions: existing }, null, 2));
1057
+ renameSync(tmpFile, configuration.sessionsFile);
1058
+ hardenPrivateFileSync(configuration.sessionsFile);
1059
+ } catch (error) {
1060
+ logger.debug(`[PERSISTENCE] Failed to persist session ${sessionId}:`, error);
1061
+ }
1062
+ }
1063
+ function deletePersistedSessions(sessionIds) {
1064
+ try {
1065
+ const existing = readPersistedSessions();
1066
+ let changed = false;
1067
+ for (const id of sessionIds) {
1068
+ if (id in existing) {
1069
+ delete existing[id];
1070
+ changed = true;
1071
+ }
1072
+ }
1073
+ if (!changed) return;
1074
+ const tmpFile = configuration.sessionsFile + ".tmp";
1075
+ writePrivateFileSync(tmpFile, JSON.stringify({ sessions: existing }, null, 2));
1076
+ renameSync(tmpFile, configuration.sessionsFile);
1077
+ hardenPrivateFileSync(configuration.sessionsFile);
1078
+ } catch (error) {
1079
+ logger.debug(`[PERSISTENCE] Failed to delete persisted sessions:`, error);
1080
+ }
1081
+ }
1082
+
1083
+ var persistence = /*#__PURE__*/Object.freeze({
1084
+ __proto__: null,
1085
+ SUPPORTED_SCHEMA_VERSION: SUPPORTED_SCHEMA_VERSION,
1086
+ SandboxConfigSchema: SandboxConfigSchema,
1087
+ acquireDaemonLock: acquireDaemonLock,
1088
+ clearCredentials: clearCredentials,
1089
+ clearDaemonState: clearDaemonState,
1090
+ clearMachineId: clearMachineId,
1091
+ deletePersistedSessions: deletePersistedSessions,
1092
+ persistSession: persistSession,
1093
+ readCredentials: readCredentials,
1094
+ readCredentialsForConfiguredRelay: readCredentialsForConfiguredRelay,
1095
+ readDaemonState: readDaemonState,
1096
+ readPersistedSessions: readPersistedSessions,
1097
+ readSettings: readSettings,
1098
+ readSettingsOutcome: readSettingsOutcome,
1099
+ readTrackedClaudeSessionIds: readTrackedClaudeSessionIds,
1100
+ releaseDaemonLock: releaseDaemonLock,
1101
+ updateSettings: updateSettings,
1102
+ writeCredentialsDataKey: writeCredentialsDataKey,
1103
+ writeCredentialsLegacy: writeCredentialsLegacy,
1104
+ writeDaemonState: writeDaemonState,
1105
+ writeSettings: writeSettings
1106
+ });
1107
+
1108
+ const CLIPBOARD_MAX_BYTES = 256 * 1024;
1109
+ const CLIPBOARD_TOOL_NAME = "copy_to_clipboard";
1110
+ const CLIPBOARD_TOOL_TITLE = "Copy to User Clipboard";
1111
+ const CLIPBOARD_TOOL_DESCRIPTION = `Copy text to the clipboard of the device the user is currently viewing this session from (their web browser, possibly a phone). Use this whenever the user wants a piece of text handed to them \u2014 not only when they literally say "clipboard". Trigger phrases include: "copy X", "copy that for me", "give me X", "send me X", "I need X on my phone", "\u590D\u5236\u7ED9\u6211", "\u628A X \u590D\u5236\u4E00\u4E0B", "\u53D1\u6211", "\u7ED9\u6211\u4E00\u4EFD", "\u590D\u5236\u5230\u526A\u5207\u677F/\u526A\u8D34\u677F". Typical payloads: command output, code snippets, tokens/keys, URLs, file contents, commit messages. The text is delivered to every device where the user has the web client open. Payloads larger than ${CLIPBOARD_MAX_BYTES / 1024}KB are truncated.`;
1112
+ function prepareClipboardText(input) {
1113
+ const totalBytes = Buffer.byteLength(input, "utf8");
1114
+ if (totalBytes <= CLIPBOARD_MAX_BYTES) {
1115
+ return { text: input, truncated: false, totalBytes };
1116
+ }
1117
+ const sliced = Buffer.from(input, "utf8").subarray(0, CLIPBOARD_MAX_BYTES).toString("utf8");
1118
+ let text = sliced;
1119
+ if (text.endsWith("\uFFFD")) {
1120
+ text = text.slice(0, -1);
1121
+ }
1122
+ const lastCode = text.charCodeAt(text.length - 1);
1123
+ if (lastCode >= 55296 && lastCode <= 56319) {
1124
+ text = text.slice(0, -1);
1125
+ }
1126
+ return { text, truncated: true, totalBytes };
1127
+ }
1128
+
1129
+ export { clearDaemonState as A, ensurePrivateDirectory as B, CLIPBOARD_TOOL_NAME as C, hardenPrivateFile as D, readCredentials as E, readSettingsOutcome as F, updateSettings as G, encodeBase64Url as H, writeCredentialsLegacy as I, writeCredentialsDataKey as J, decryptWithDataKey as K, decryptLegacy as L, persistSession as M, acquireDaemonLock as N, deletePersistedSessions as O, writeDaemonState as P, writeSettings as Q, releaseDaemonLock as R, clearCredentials as S, clearMachineId as T, SandboxConfigSchema as U, getLatestDaemonLog as V, persistence as W, CLIPBOARD_TOOL_TITLE as a, CLIPBOARD_TOOL_DESCRIPTION as b, configuration as c, CLIPBOARD_MAX_BYTES as d, ensurePrivateDirectorySync as e, readSettings as f, encodeBase64 as g, hardenPrivateFileSync as h, readCredentialsForConfiguredRelay as i, encrypt as j, decrypt as k, logger as l, decodeBase64 as m, normalizeHttpEndpoint as n, decryptBlob as o, packageJson as p, prepareClipboardText as q, readPersistedSessions as r, credentialRelayProblem as s, readTrackedClaudeSessionIds as t, libsodiumEncryptForPublicKey as u, libsodiumPublicKeyFromSecretKey as v, writePrivateFileSync as w, getRandomBytes as x, redactLogValue as y, readDaemonState as z };