happy-coder 0.2.3-beta.1 → 0.3.1-beta.0

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