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