happy-coder 0.1.9 → 0.1.11

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 (40) hide show
  1. package/README.md +2 -0
  2. package/dist/index-B2GqfEZV.cjs +1564 -0
  3. package/dist/index-QItBXhux.mjs +1540 -0
  4. package/dist/index.cjs +997 -260
  5. package/dist/index.mjs +996 -259
  6. package/dist/install-B0DnBGS_.mjs +29 -0
  7. package/dist/install-C809w0Cj.cjs +31 -0
  8. package/dist/install-DEPy62QN.mjs +97 -0
  9. package/dist/install-GZIzyuIE.cjs +99 -0
  10. package/dist/lib.cjs +1 -1
  11. package/dist/lib.d.cts +265 -460
  12. package/dist/lib.d.mts +265 -460
  13. package/dist/lib.mjs +1 -1
  14. package/dist/run-BmEaINbl.cjs +250 -0
  15. package/dist/run-DMbKhYfb.mjs +247 -0
  16. package/dist/types-BRICSarm.mjs +870 -0
  17. package/dist/types-BTQRfIr3.cjs +892 -0
  18. package/dist/types-CEvzGLMI.cjs +882 -0
  19. package/dist/types-D39L8JSd.mjs +850 -0
  20. package/dist/types-DYBiuNUQ.cjs +883 -0
  21. package/dist/types-Df5dlWLV.mjs +871 -0
  22. package/dist/types-hotUTaWz.cjs +863 -0
  23. package/dist/types-tLWMaptR.mjs +879 -0
  24. package/dist/uninstall-BGgl5V8F.mjs +29 -0
  25. package/dist/uninstall-BWHglipH.mjs +40 -0
  26. package/dist/uninstall-CdHMb6wi.cjs +31 -0
  27. package/dist/uninstall-FXyyAuGU.cjs +42 -0
  28. package/package.json +8 -2
  29. package/ripgrep/COPYING +3 -0
  30. package/ripgrep/arm64-darwin/rg +0 -0
  31. package/ripgrep/arm64-darwin/ripgrep.node +0 -0
  32. package/ripgrep/arm64-linux/rg +0 -0
  33. package/ripgrep/arm64-linux/ripgrep.node +0 -0
  34. package/ripgrep/x64-darwin/rg +0 -0
  35. package/ripgrep/x64-darwin/ripgrep.node +0 -0
  36. package/ripgrep/x64-linux/rg +0 -0
  37. package/ripgrep/x64-linux/ripgrep.node +0 -0
  38. package/ripgrep/x64-win32/rg.exe +0 -0
  39. package/ripgrep/x64-win32/ripgrep.node +0 -0
  40. package/scripts/ripgrep_launcher.cjs +57 -0
@@ -0,0 +1,879 @@
1
+ import axios from 'axios';
2
+ import chalk from 'chalk';
3
+ import { appendFileSync } from 'fs';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { mkdir } from 'node:fs/promises';
7
+ import { existsSync } from 'node:fs';
8
+ import { EventEmitter } from 'node:events';
9
+ import { io } from 'socket.io-client';
10
+ import { z } from 'zod';
11
+ import { randomBytes } from 'node:crypto';
12
+ import tweetnacl from 'tweetnacl';
13
+ import { Expo } from 'expo-server-sdk';
14
+
15
+ class Configuration {
16
+ serverUrl;
17
+ // Directories and paths (from persistence)
18
+ happyDir;
19
+ logsDir;
20
+ settingsFile;
21
+ privateKeyFile;
22
+ constructor(location) {
23
+ this.serverUrl = process.env.HANDY_SERVER_URL || "https://handy-api.korshakov.org";
24
+ if (location === "local") {
25
+ this.happyDir = join(process.cwd(), ".happy");
26
+ } else {
27
+ this.happyDir = join(homedir(), ".happy");
28
+ }
29
+ this.logsDir = join(this.happyDir, "logs");
30
+ this.settingsFile = join(this.happyDir, "settings.json");
31
+ this.privateKeyFile = join(this.happyDir, "access.key");
32
+ }
33
+ }
34
+ let configuration = void 0;
35
+ function initializeConfiguration(location) {
36
+ configuration = new Configuration(location);
37
+ }
38
+
39
+ async function getSessionLogPath() {
40
+ if (!existsSync(configuration.logsDir)) {
41
+ await mkdir(configuration.logsDir, { recursive: true });
42
+ }
43
+ const now = /* @__PURE__ */ new Date();
44
+ const timestamp = now.toLocaleString("sv-SE", {
45
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
46
+ year: "numeric",
47
+ month: "2-digit",
48
+ day: "2-digit",
49
+ hour: "2-digit",
50
+ minute: "2-digit",
51
+ second: "2-digit"
52
+ }).replace(/[: ]/g, "-").replace(/,/g, "");
53
+ return join(configuration.logsDir, `${timestamp}.log`);
54
+ }
55
+ class Logger {
56
+ constructor(logFilePathPromise = getSessionLogPath()) {
57
+ this.logFilePathPromise = logFilePathPromise;
58
+ }
59
+ // Use local timezone for simplicity of locating the logs,
60
+ // in practice you will not need absolute timestamps
61
+ localTimezoneTimestamp() {
62
+ return (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
63
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
64
+ hour12: false,
65
+ hour: "2-digit",
66
+ minute: "2-digit",
67
+ second: "2-digit",
68
+ fractionalSecondDigits: 3
69
+ });
70
+ }
71
+ debug(message, ...args) {
72
+ this.logToFile(`[${this.localTimezoneTimestamp()}]`, message, ...args);
73
+ }
74
+ debugLargeJson(message, object, maxStringLength = 100, maxArrayLength = 10) {
75
+ if (!process.env.DEBUG) {
76
+ this.debug(`In production, skipping message inspection`);
77
+ }
78
+ const truncateStrings = (obj) => {
79
+ if (typeof obj === "string") {
80
+ return obj.length > maxStringLength ? obj.substring(0, maxStringLength) + "... [truncated for logs]" : obj;
81
+ }
82
+ if (Array.isArray(obj)) {
83
+ const truncatedArray = obj.map((item) => truncateStrings(item)).slice(0, maxArrayLength);
84
+ if (obj.length > maxArrayLength) {
85
+ truncatedArray.push(`... [truncated array for logs up to ${maxArrayLength} items]`);
86
+ }
87
+ return truncatedArray;
88
+ }
89
+ if (obj && typeof obj === "object") {
90
+ const result = {};
91
+ for (const [key, value] of Object.entries(obj)) {
92
+ if (key === "usage") {
93
+ continue;
94
+ }
95
+ result[key] = truncateStrings(value);
96
+ }
97
+ return result;
98
+ }
99
+ return obj;
100
+ };
101
+ const truncatedObject = truncateStrings(object);
102
+ const json = JSON.stringify(truncatedObject, null, 2);
103
+ this.logToFile(`[${this.localTimezoneTimestamp()}]`, message, "\n", json);
104
+ }
105
+ info(message, ...args) {
106
+ this.logToConsole("info", "", message, ...args);
107
+ this.debug(message, args);
108
+ }
109
+ infoDeveloper(message, ...args) {
110
+ this.debug(message, ...args);
111
+ if (process.env.DEBUG) {
112
+ this.logToConsole("info", "[DEV]", message, ...args);
113
+ }
114
+ }
115
+ logToConsole(level, prefix, message, ...args) {
116
+ switch (level) {
117
+ case "debug": {
118
+ console.log(chalk.gray(prefix), message, ...args);
119
+ break;
120
+ }
121
+ case "error": {
122
+ console.error(chalk.red(prefix), message, ...args);
123
+ break;
124
+ }
125
+ case "info": {
126
+ console.log(chalk.blue(prefix), message, ...args);
127
+ break;
128
+ }
129
+ case "warn": {
130
+ console.log(chalk.yellow(prefix), message, ...args);
131
+ break;
132
+ }
133
+ default: {
134
+ this.debug("Unknown log level:", level);
135
+ console.log(chalk.blue(prefix), message, ...args);
136
+ break;
137
+ }
138
+ }
139
+ }
140
+ logToFile(prefix, message, ...args) {
141
+ const logLine = `${prefix} ${message} ${args.map(
142
+ (arg) => typeof arg === "string" ? arg : JSON.stringify(arg)
143
+ ).join(" ")}
144
+ `;
145
+ this.logFilePathPromise.then((logFilePath) => {
146
+ try {
147
+ appendFileSync(logFilePath, logLine);
148
+ } catch (appendError) {
149
+ if (process.env.DEBUG) {
150
+ console.error("Failed to append to log file:", appendError);
151
+ throw appendError;
152
+ }
153
+ }
154
+ }).catch((error) => {
155
+ if (process.env.DEBUG) {
156
+ console.log("This message only visible in DEBUG mode, not in production");
157
+ console.error("Failed to resolve log file path:", error);
158
+ console.log(prefix, message, ...args);
159
+ }
160
+ });
161
+ }
162
+ }
163
+ let logger;
164
+ function initLoggerWithGlobalConfiguration() {
165
+ logger = new Logger();
166
+ if (process.env.DEBUG) {
167
+ logger.logFilePathPromise.then((logPath) => {
168
+ logger.info(chalk.yellow("[DEBUG MODE] Debug logging enabled"));
169
+ logger.info(chalk.gray(`Log file: ${logPath}`));
170
+ });
171
+ }
172
+ }
173
+
174
+ const SessionMessageContentSchema = z.object({
175
+ c: z.string(),
176
+ // Base64 encoded encrypted content
177
+ t: z.literal("encrypted")
178
+ });
179
+ const UpdateBodySchema = z.object({
180
+ message: z.object({
181
+ id: z.string(),
182
+ seq: z.number(),
183
+ content: SessionMessageContentSchema
184
+ }),
185
+ sid: z.string(),
186
+ // Session ID
187
+ t: z.literal("new-message")
188
+ });
189
+ const UpdateSessionBodySchema = z.object({
190
+ t: z.literal("update-session"),
191
+ sid: z.string(),
192
+ metadata: z.object({
193
+ version: z.number(),
194
+ metadata: z.string()
195
+ }).nullish(),
196
+ agentState: z.object({
197
+ version: z.number(),
198
+ agentState: z.string()
199
+ }).nullish()
200
+ });
201
+ z.object({
202
+ id: z.string(),
203
+ seq: z.number(),
204
+ body: z.union([UpdateBodySchema, UpdateSessionBodySchema]),
205
+ createdAt: z.number()
206
+ });
207
+ z.object({
208
+ createdAt: z.number(),
209
+ id: z.string(),
210
+ seq: z.number(),
211
+ updatedAt: z.number(),
212
+ metadata: z.any(),
213
+ metadataVersion: z.number(),
214
+ agentState: z.any().nullable(),
215
+ agentStateVersion: z.number()
216
+ });
217
+ z.object({
218
+ content: SessionMessageContentSchema,
219
+ createdAt: z.number(),
220
+ id: z.string(),
221
+ seq: z.number(),
222
+ updatedAt: z.number()
223
+ });
224
+ z.object({
225
+ session: z.object({
226
+ id: z.string(),
227
+ tag: z.string(),
228
+ seq: z.number(),
229
+ createdAt: z.number(),
230
+ updatedAt: z.number(),
231
+ metadata: z.string(),
232
+ metadataVersion: z.number(),
233
+ agentState: z.string().nullable(),
234
+ agentStateVersion: z.number()
235
+ })
236
+ });
237
+ const UserMessageSchema$1 = z.object({
238
+ role: z.literal("user"),
239
+ content: z.object({
240
+ type: z.literal("text"),
241
+ text: z.string()
242
+ }),
243
+ localKey: z.string().optional(),
244
+ // Mobile messages include this
245
+ sentFrom: z.enum(["mobile", "cli"]).optional()
246
+ // Source identifier
247
+ });
248
+ const AgentMessageSchema = z.object({
249
+ role: z.literal("agent"),
250
+ content: z.object({
251
+ type: z.literal("output"),
252
+ data: z.any()
253
+ })
254
+ });
255
+ z.union([UserMessageSchema$1, AgentMessageSchema]);
256
+
257
+ function encodeBase64(buffer, variant = "base64") {
258
+ if (variant === "base64url") {
259
+ return encodeBase64Url(buffer);
260
+ }
261
+ return Buffer.from(buffer).toString("base64");
262
+ }
263
+ function encodeBase64Url(buffer) {
264
+ return Buffer.from(buffer).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
265
+ }
266
+ function decodeBase64(base64, variant = "base64") {
267
+ if (variant === "base64url") {
268
+ const base64Standard = base64.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat((4 - base64.length % 4) % 4);
269
+ return new Uint8Array(Buffer.from(base64Standard, "base64"));
270
+ }
271
+ return new Uint8Array(Buffer.from(base64, "base64"));
272
+ }
273
+ function getRandomBytes(size) {
274
+ return new Uint8Array(randomBytes(size));
275
+ }
276
+ function encrypt(data, secret) {
277
+ const nonce = getRandomBytes(tweetnacl.secretbox.nonceLength);
278
+ const encrypted = tweetnacl.secretbox(new TextEncoder().encode(JSON.stringify(data)), nonce, secret);
279
+ const result = new Uint8Array(nonce.length + encrypted.length);
280
+ result.set(nonce);
281
+ result.set(encrypted, nonce.length);
282
+ return result;
283
+ }
284
+ function decrypt(data, secret) {
285
+ const nonce = data.slice(0, tweetnacl.secretbox.nonceLength);
286
+ const encrypted = data.slice(tweetnacl.secretbox.nonceLength);
287
+ const decrypted = tweetnacl.secretbox.open(encrypted, nonce, secret);
288
+ if (!decrypted) {
289
+ return null;
290
+ }
291
+ return JSON.parse(new TextDecoder().decode(decrypted));
292
+ }
293
+
294
+ async function delay(ms) {
295
+ return new Promise((resolve) => setTimeout(resolve, ms));
296
+ }
297
+ function exponentialBackoffDelay(currentFailureCount, minDelay, maxDelay, maxFailureCount) {
298
+ let maxDelayRet = minDelay + (maxDelay - minDelay) / maxFailureCount * Math.max(currentFailureCount, maxFailureCount);
299
+ return Math.round(Math.random() * maxDelayRet);
300
+ }
301
+ function createBackoff(opts) {
302
+ return async (callback) => {
303
+ let currentFailureCount = 0;
304
+ const minDelay = 250;
305
+ const maxDelay = 1e3;
306
+ const maxFailureCount = 50;
307
+ while (true) {
308
+ try {
309
+ return await callback();
310
+ } catch (e) {
311
+ if (currentFailureCount < maxFailureCount) {
312
+ currentFailureCount++;
313
+ }
314
+ let waitForRequest = exponentialBackoffDelay(currentFailureCount, minDelay, maxDelay, maxFailureCount);
315
+ await delay(waitForRequest);
316
+ }
317
+ }
318
+ };
319
+ }
320
+ let backoff = createBackoff();
321
+
322
+ class ApiSessionClient extends EventEmitter {
323
+ token;
324
+ secret;
325
+ sessionId;
326
+ metadata;
327
+ metadataVersion;
328
+ agentState;
329
+ agentStateVersion;
330
+ socket;
331
+ pendingMessages = [];
332
+ pendingMessageCallback = null;
333
+ rpcHandlers = /* @__PURE__ */ new Map();
334
+ constructor(token, secret, session) {
335
+ super();
336
+ this.token = token;
337
+ this.secret = secret;
338
+ this.sessionId = session.id;
339
+ this.metadata = session.metadata;
340
+ this.metadataVersion = session.metadataVersion;
341
+ this.agentState = session.agentState;
342
+ this.agentStateVersion = session.agentStateVersion;
343
+ this.socket = io(configuration.serverUrl, {
344
+ auth: {
345
+ token: this.token,
346
+ clientType: "session-scoped",
347
+ sessionId: this.sessionId
348
+ },
349
+ path: "/v1/updates",
350
+ reconnection: true,
351
+ reconnectionAttempts: Infinity,
352
+ reconnectionDelay: 1e3,
353
+ reconnectionDelayMax: 5e3,
354
+ transports: ["websocket"],
355
+ withCredentials: true,
356
+ autoConnect: false
357
+ });
358
+ this.socket.on("connect", () => {
359
+ logger.debug("Socket connected successfully");
360
+ this.reregisterHandlers();
361
+ });
362
+ this.socket.on("rpc-request", async (data, callback) => {
363
+ try {
364
+ const method = data.method;
365
+ const handler = this.rpcHandlers.get(method);
366
+ if (!handler) {
367
+ logger.debug("[SOCKET] [RPC] [ERROR] method not found", { method });
368
+ const errorResponse = { error: "Method not found" };
369
+ const encryptedError = encodeBase64(encrypt(errorResponse, this.secret));
370
+ callback(encryptedError);
371
+ return;
372
+ }
373
+ const decryptedParams = decrypt(decodeBase64(data.params), this.secret);
374
+ const result = await handler(decryptedParams);
375
+ const encryptedResponse = encodeBase64(encrypt(result, this.secret));
376
+ callback(encryptedResponse);
377
+ } catch (error) {
378
+ logger.debug("[SOCKET] [RPC] [ERROR] Error handling RPC request", { error });
379
+ const errorResponse = { error: error instanceof Error ? error.message : "Unknown error" };
380
+ const encryptedError = encodeBase64(encrypt(errorResponse, this.secret));
381
+ callback(encryptedError);
382
+ }
383
+ });
384
+ this.socket.on("disconnect", (reason) => {
385
+ logger.debug("[API] Socket disconnected:", reason);
386
+ });
387
+ this.socket.on("connect_error", (error) => {
388
+ logger.debug("[API] Socket connection error:", error);
389
+ });
390
+ this.socket.on("update", (data) => {
391
+ try {
392
+ logger.debugLargeJson("[SOCKET] [UPDATE] Received update:", data);
393
+ if (!data.body) {
394
+ logger.debug("[SOCKET] [UPDATE] [ERROR] No body in update!");
395
+ return;
396
+ }
397
+ if (data.body.t === "new-message" && data.body.message.content.t === "encrypted") {
398
+ const body = decrypt(decodeBase64(data.body.message.content.c), this.secret);
399
+ logger.debugLargeJson("[SOCKET] [UPDATE] Received update:", body);
400
+ const userResult = UserMessageSchema$1.safeParse(body);
401
+ if (userResult.success) {
402
+ if (this.pendingMessageCallback) {
403
+ this.pendingMessageCallback(userResult.data);
404
+ } else {
405
+ this.pendingMessages.push(userResult.data);
406
+ }
407
+ } else {
408
+ this.emit("message", body);
409
+ }
410
+ } else if (data.body.t === "update-session") {
411
+ if (data.body.metadata && data.body.metadata.version > this.metadataVersion) {
412
+ this.metadata = decrypt(decodeBase64(data.body.metadata.metadata), this.secret);
413
+ this.metadataVersion = data.body.metadata.version;
414
+ }
415
+ if (data.body.agentState && data.body.agentState.version > this.agentStateVersion) {
416
+ this.agentState = data.body.agentState.agentState ? decrypt(decodeBase64(data.body.agentState.agentState), this.secret) : null;
417
+ this.agentStateVersion = data.body.agentState.version;
418
+ }
419
+ }
420
+ } catch (error) {
421
+ logger.debug("[SOCKET] [UPDATE] [ERROR] Error handling update", { error });
422
+ }
423
+ });
424
+ this.socket.on("error", (error) => {
425
+ logger.debug("[API] Socket error:", error);
426
+ });
427
+ this.socket.connect();
428
+ }
429
+ onUserMessage(callback) {
430
+ this.pendingMessageCallback = callback;
431
+ while (this.pendingMessages.length > 0) {
432
+ callback(this.pendingMessages.shift());
433
+ }
434
+ }
435
+ /**
436
+ * Send message to session
437
+ * @param body - Message body (can be MessageContent or raw content for agent messages)
438
+ */
439
+ sendClaudeSessionMessage(body) {
440
+ let content;
441
+ if (body.type === "user" && typeof body.message.content === "string") {
442
+ content = {
443
+ role: "user",
444
+ content: {
445
+ type: "text",
446
+ text: body.message.content
447
+ }
448
+ };
449
+ } else {
450
+ content = {
451
+ role: "agent",
452
+ content: {
453
+ type: "output",
454
+ data: body
455
+ // This wraps the entire Claude message
456
+ }
457
+ };
458
+ }
459
+ logger.debugLargeJson("[SOCKET] Sending message through socket:", content);
460
+ const encrypted = encodeBase64(encrypt(content, this.secret));
461
+ this.socket.emit("message", {
462
+ sid: this.sessionId,
463
+ message: encrypted
464
+ });
465
+ if (body.type === "assistant" && body.message.usage) {
466
+ try {
467
+ this.sendUsageData(body.message.usage);
468
+ } catch (error) {
469
+ logger.debug("[SOCKET] Failed to send usage data:", error);
470
+ }
471
+ }
472
+ if (body.type === "summary" && "summary" in body && "leafUuid" in body) {
473
+ this.updateMetadata((metadata) => ({
474
+ ...metadata,
475
+ summary: {
476
+ text: body.summary,
477
+ updatedAt: Date.now()
478
+ }
479
+ }));
480
+ }
481
+ }
482
+ /**
483
+ * Send a ping message to keep the connection alive
484
+ */
485
+ keepAlive(thinking) {
486
+ this.socket.volatile.emit("session-alive", {
487
+ sid: this.sessionId,
488
+ time: Date.now(),
489
+ thinking
490
+ });
491
+ }
492
+ /**
493
+ * Send session death message
494
+ */
495
+ sendSessionDeath() {
496
+ this.socket.emit("session-end", { sid: this.sessionId, time: Date.now() });
497
+ }
498
+ /**
499
+ * Send usage data to the server
500
+ */
501
+ sendUsageData(usage) {
502
+ const totalTokens = usage.input_tokens + usage.output_tokens + (usage.cache_creation_input_tokens || 0) + (usage.cache_read_input_tokens || 0);
503
+ const usageReport = {
504
+ key: "claude-session",
505
+ sessionId: this.sessionId,
506
+ tokens: {
507
+ total: totalTokens,
508
+ input: usage.input_tokens,
509
+ output: usage.output_tokens,
510
+ cache_creation: usage.cache_creation_input_tokens || 0,
511
+ cache_read: usage.cache_read_input_tokens || 0
512
+ },
513
+ cost: {
514
+ // TODO: Calculate actual costs based on pricing
515
+ // For now, using placeholder values
516
+ total: 0,
517
+ input: 0,
518
+ output: 0
519
+ }
520
+ };
521
+ logger.debugLargeJson("[SOCKET] Sending usage data:", usageReport);
522
+ this.socket.emit("usage-report", usageReport);
523
+ }
524
+ /**
525
+ * Update session metadata
526
+ * @param handler - Handler function that returns the updated metadata
527
+ */
528
+ updateMetadata(handler) {
529
+ backoff(async () => {
530
+ let updated = handler(this.metadata);
531
+ const answer = await this.socket.emitWithAck("update-metadata", { sid: this.sessionId, expectedVersion: this.metadataVersion, metadata: encodeBase64(encrypt(updated, this.secret)) });
532
+ if (answer.result === "success") {
533
+ this.metadata = decrypt(decodeBase64(answer.metadata), this.secret);
534
+ this.metadataVersion = answer.version;
535
+ } else if (answer.result === "version-mismatch") {
536
+ if (answer.version > this.metadataVersion) {
537
+ this.metadataVersion = answer.version;
538
+ this.metadata = decrypt(decodeBase64(answer.metadata), this.secret);
539
+ }
540
+ throw new Error("Metadata version mismatch");
541
+ } else if (answer.result === "error") ;
542
+ });
543
+ }
544
+ /**
545
+ * Update session agent state
546
+ * @param handler - Handler function that returns the updated agent state
547
+ */
548
+ updateAgentState(handler) {
549
+ console.log("Updating agent state", this.agentState);
550
+ backoff(async () => {
551
+ let updated = handler(this.agentState || {});
552
+ const answer = await this.socket.emitWithAck("update-state", { sid: this.sessionId, expectedVersion: this.agentStateVersion, agentState: updated ? encodeBase64(encrypt(updated, this.secret)) : null });
553
+ if (answer.result === "success") {
554
+ this.agentState = answer.agentState ? decrypt(decodeBase64(answer.agentState), this.secret) : null;
555
+ this.agentStateVersion = answer.version;
556
+ console.log("Agent state updated", this.agentState);
557
+ } else if (answer.result === "version-mismatch") {
558
+ if (answer.version > this.agentStateVersion) {
559
+ this.agentStateVersion = answer.version;
560
+ this.agentState = answer.agentState ? decrypt(decodeBase64(answer.agentState), this.secret) : null;
561
+ }
562
+ throw new Error("Agent state version mismatch");
563
+ } else if (answer.result === "error") {
564
+ console.error("Agent state update error", answer);
565
+ }
566
+ });
567
+ }
568
+ /**
569
+ * Set a custom RPC handler for a specific method with encrypted arguments and responses
570
+ * @param method - The method name to handle
571
+ * @param handler - The handler function to call when the method is invoked
572
+ */
573
+ setHandler(method, handler) {
574
+ const prefixedMethod = `${this.sessionId}:${method}`;
575
+ this.rpcHandlers.set(prefixedMethod, handler);
576
+ this.socket.emit("rpc-register", { method: prefixedMethod });
577
+ logger.debug("Registered RPC handler", { method, prefixedMethod });
578
+ }
579
+ /**
580
+ * Re-register all RPC handlers after reconnection
581
+ */
582
+ reregisterHandlers() {
583
+ logger.debug("Re-registering RPC handlers after reconnection", {
584
+ totalMethods: this.rpcHandlers.size
585
+ });
586
+ for (const [prefixedMethod] of this.rpcHandlers) {
587
+ this.socket.emit("rpc-register", { method: prefixedMethod });
588
+ logger.debug("Re-registered method", { prefixedMethod });
589
+ }
590
+ }
591
+ /**
592
+ * Wait for socket buffer to flush
593
+ */
594
+ async flush() {
595
+ if (!this.socket.connected) {
596
+ return;
597
+ }
598
+ return new Promise((resolve) => {
599
+ this.socket.emit("ping", () => {
600
+ resolve();
601
+ });
602
+ setTimeout(() => {
603
+ resolve();
604
+ }, 1e4);
605
+ });
606
+ }
607
+ async close() {
608
+ this.socket.close();
609
+ }
610
+ }
611
+
612
+ class PushNotificationClient {
613
+ token;
614
+ baseUrl;
615
+ expo;
616
+ constructor(token, baseUrl = "https://handy-api.korshakov.org") {
617
+ this.token = token;
618
+ this.baseUrl = baseUrl;
619
+ this.expo = new Expo();
620
+ }
621
+ /**
622
+ * Fetch all push tokens for the authenticated user
623
+ */
624
+ async fetchPushTokens() {
625
+ try {
626
+ const response = await axios.get(
627
+ `${this.baseUrl}/v1/push-tokens`,
628
+ {
629
+ headers: {
630
+ "Authorization": `Bearer ${this.token}`,
631
+ "Content-Type": "application/json"
632
+ }
633
+ }
634
+ );
635
+ logger.info(`Fetched ${response.data.tokens.length} push tokens`);
636
+ return response.data.tokens;
637
+ } catch (error) {
638
+ logger.debug("[PUSH] [ERROR] Failed to fetch push tokens:", error);
639
+ throw new Error(`Failed to fetch push tokens: ${error instanceof Error ? error.message : "Unknown error"}`);
640
+ }
641
+ }
642
+ /**
643
+ * Send push notification via Expo Push API with retry
644
+ * @param messages - Array of push messages to send
645
+ */
646
+ async sendPushNotifications(messages) {
647
+ logger.info(`Sending ${messages.length} push notifications`);
648
+ const validMessages = messages.filter((message) => {
649
+ if (Array.isArray(message.to)) {
650
+ return message.to.every((token) => Expo.isExpoPushToken(token));
651
+ }
652
+ return Expo.isExpoPushToken(message.to);
653
+ });
654
+ if (validMessages.length === 0) {
655
+ logger.info("No valid Expo push tokens found");
656
+ return;
657
+ }
658
+ const chunks = this.expo.chunkPushNotifications(validMessages);
659
+ for (const chunk of chunks) {
660
+ const startTime = Date.now();
661
+ const timeout = 3e5;
662
+ let attempt = 0;
663
+ while (true) {
664
+ try {
665
+ const ticketChunk = await this.expo.sendPushNotificationsAsync(chunk);
666
+ const errors = ticketChunk.filter((ticket) => ticket.status === "error");
667
+ if (errors.length > 0) {
668
+ logger.debug("[PUSH] Some notifications failed:", errors);
669
+ }
670
+ if (errors.length === ticketChunk.length) {
671
+ throw new Error("All push notifications in chunk failed");
672
+ }
673
+ break;
674
+ } catch (error) {
675
+ const elapsed = Date.now() - startTime;
676
+ if (elapsed >= timeout) {
677
+ logger.debug("[PUSH] Timeout reached after 5 minutes, giving up on chunk");
678
+ break;
679
+ }
680
+ attempt++;
681
+ const delay = Math.min(1e3 * Math.pow(2, attempt), 3e4);
682
+ const remainingTime = timeout - elapsed;
683
+ const waitTime = Math.min(delay, remainingTime);
684
+ if (waitTime > 0) {
685
+ logger.debug(`[PUSH] Retrying in ${waitTime}ms (attempt ${attempt})`);
686
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
687
+ }
688
+ }
689
+ }
690
+ }
691
+ logger.info(`Push notifications sent successfully`);
692
+ }
693
+ /**
694
+ * Send a push notification to all registered devices for the user
695
+ * @param title - Notification title
696
+ * @param body - Notification body
697
+ * @param data - Additional data to send with the notification
698
+ */
699
+ async sendToAllDevices(title, body, data) {
700
+ const tokens = await this.fetchPushTokens();
701
+ if (tokens.length === 0) {
702
+ logger.info("No push tokens found for user");
703
+ return;
704
+ }
705
+ const messages = tokens.map((token) => ({
706
+ to: token.token,
707
+ title,
708
+ body,
709
+ data,
710
+ sound: "default",
711
+ priority: "high"
712
+ }));
713
+ await this.sendPushNotifications(messages);
714
+ }
715
+ }
716
+
717
+ class ApiClient {
718
+ token;
719
+ secret;
720
+ pushClient;
721
+ constructor(token, secret) {
722
+ this.token = token;
723
+ this.secret = secret;
724
+ this.pushClient = new PushNotificationClient(token);
725
+ }
726
+ /**
727
+ * Create a new session or load existing one with the given tag
728
+ */
729
+ async getOrCreateSession(opts) {
730
+ try {
731
+ const response = await axios.post(
732
+ `${configuration.serverUrl}/v1/sessions`,
733
+ {
734
+ tag: opts.tag,
735
+ metadata: encodeBase64(encrypt(opts.metadata, this.secret)),
736
+ agentState: opts.state ? encodeBase64(encrypt(opts.state, this.secret)) : null
737
+ },
738
+ {
739
+ headers: {
740
+ "Authorization": `Bearer ${this.token}`,
741
+ "Content-Type": "application/json"
742
+ }
743
+ }
744
+ );
745
+ logger.debug(`Session created/loaded: ${response.data.session.id} (tag: ${opts.tag})`);
746
+ let raw = response.data.session;
747
+ let session = {
748
+ id: raw.id,
749
+ createdAt: raw.createdAt,
750
+ updatedAt: raw.updatedAt,
751
+ seq: raw.seq,
752
+ metadata: decrypt(decodeBase64(raw.metadata), this.secret),
753
+ metadataVersion: raw.metadataVersion,
754
+ agentState: raw.agentState ? decrypt(decodeBase64(raw.agentState), this.secret) : null,
755
+ agentStateVersion: raw.agentStateVersion
756
+ };
757
+ return session;
758
+ } catch (error) {
759
+ logger.debug("[API] [ERROR] Failed to get or create session:", error);
760
+ throw new Error(`Failed to get or create session: ${error instanceof Error ? error.message : "Unknown error"}`);
761
+ }
762
+ }
763
+ /**
764
+ * Start realtime session client
765
+ * @param id - Session ID
766
+ * @returns Session client
767
+ */
768
+ session(session) {
769
+ return new ApiSessionClient(this.token, this.secret, session);
770
+ }
771
+ /**
772
+ * Get push notification client
773
+ * @returns Push notification client
774
+ */
775
+ push() {
776
+ return this.pushClient;
777
+ }
778
+ }
779
+
780
+ const UsageSchema = z.object({
781
+ input_tokens: z.number().int().nonnegative(),
782
+ cache_creation_input_tokens: z.number().int().nonnegative().optional(),
783
+ cache_read_input_tokens: z.number().int().nonnegative().optional(),
784
+ output_tokens: z.number().int().nonnegative(),
785
+ service_tier: z.string().optional()
786
+ });
787
+ const TextContentSchema = z.object({
788
+ type: z.literal("text"),
789
+ text: z.string()
790
+ });
791
+ const ThinkingContentSchema = z.object({
792
+ type: z.literal("thinking"),
793
+ thinking: z.string(),
794
+ signature: z.string()
795
+ });
796
+ const ToolUseContentSchema = z.object({
797
+ type: z.literal("tool_use"),
798
+ id: z.string(),
799
+ name: z.string(),
800
+ input: z.unknown()
801
+ // Tool-specific input parameters
802
+ });
803
+ const ToolResultContentSchema = z.object({
804
+ tool_use_id: z.string(),
805
+ type: z.literal("tool_result"),
806
+ content: z.union([
807
+ z.string(),
808
+ // For simple string responses
809
+ z.array(TextContentSchema)
810
+ // For structured content blocks (typically text)
811
+ ]),
812
+ is_error: z.boolean().optional()
813
+ });
814
+ const ContentSchema = z.union([
815
+ TextContentSchema,
816
+ ThinkingContentSchema,
817
+ ToolUseContentSchema,
818
+ ToolResultContentSchema
819
+ ]);
820
+ const UserMessageSchema = z.object({
821
+ role: z.literal("user"),
822
+ content: z.union([
823
+ z.string(),
824
+ // Simple string content
825
+ z.array(z.union([ToolResultContentSchema, TextContentSchema]))
826
+ ])
827
+ });
828
+ const AssistantMessageSchema = z.object({
829
+ id: z.string(),
830
+ type: z.literal("message"),
831
+ role: z.literal("assistant"),
832
+ model: z.string(),
833
+ content: z.array(ContentSchema),
834
+ stop_reason: z.string().nullable(),
835
+ stop_sequence: z.string().nullable(),
836
+ usage: UsageSchema
837
+ });
838
+ const BaseEntrySchema = z.object({
839
+ cwd: z.string(),
840
+ sessionId: z.string(),
841
+ version: z.string(),
842
+ uuid: z.string(),
843
+ timestamp: z.string().datetime(),
844
+ parent_tool_use_id: z.string().nullable().optional()
845
+ });
846
+ const SummaryEntrySchema = z.object({
847
+ type: z.literal("summary"),
848
+ summary: z.string(),
849
+ leafUuid: z.string()
850
+ });
851
+ const UserEntrySchema = BaseEntrySchema.extend({
852
+ type: z.literal("user"),
853
+ message: UserMessageSchema,
854
+ isMeta: z.boolean().optional(),
855
+ toolUseResult: z.unknown().optional()
856
+ // Present when user responds to tool use
857
+ });
858
+ const AssistantEntrySchema = BaseEntrySchema.extend({
859
+ type: z.literal("assistant"),
860
+ message: AssistantMessageSchema,
861
+ requestId: z.string().optional()
862
+ });
863
+ const SystemEntrySchema = BaseEntrySchema.extend({
864
+ type: z.literal("system"),
865
+ content: z.string(),
866
+ isMeta: z.boolean().optional(),
867
+ level: z.string().optional(),
868
+ parentUuid: z.string().optional(),
869
+ isSidechain: z.boolean().optional(),
870
+ userType: z.string().optional()
871
+ });
872
+ const RawJSONLinesSchema = z.discriminatedUnion("type", [
873
+ UserEntrySchema,
874
+ AssistantEntrySchema,
875
+ SummaryEntrySchema,
876
+ SystemEntrySchema
877
+ ]);
878
+
879
+ export { ApiClient as A, RawJSONLinesSchema as R, ApiSessionClient as a, initializeConfiguration as b, configuration as c, backoff as d, encodeBase64 as e, encodeBase64Url as f, decodeBase64 as g, delay as h, initLoggerWithGlobalConfiguration as i, encrypt as j, decrypt as k, logger as l };