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