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