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