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