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