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