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,883 +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
- if (data.body.t === "new-message" && data.body.message.content.t === "encrypted") {
394
- const body = decrypt(decodeBase64(data.body.message.content.c), this.secret);
395
- exports.logger.debugLargeJson("[SOCKET] [UPDATE] Received update:", body);
396
- const userResult = UserMessageSchema$1.safeParse(body);
397
- if (userResult.success) {
398
- if (this.pendingMessageCallback) {
399
- this.pendingMessageCallback(userResult.data);
400
- } else {
401
- this.pendingMessages.push(userResult.data);
402
- }
403
- } else {
404
- this.emit("message", body);
405
- }
406
- } else if (data.body.t === "update-session") {
407
- if (data.body.metadata && data.body.metadata.version > this.metadataVersion) {
408
- this.metadata = decrypt(decodeBase64(data.body.metadata.metadata), this.secret);
409
- this.metadataVersion = data.body.metadata.version;
410
- }
411
- if (data.body.agentState && data.body.agentState.version > this.agentStateVersion) {
412
- this.agentState = data.body.agentState.agentState ? decrypt(decodeBase64(data.body.agentState.agentState), this.secret) : null;
413
- this.agentStateVersion = data.body.agentState.version;
414
- }
415
- }
416
- });
417
- this.socket.on("error", (error) => {
418
- exports.logger.debug("[API] Socket error:", error);
419
- });
420
- this.socket.connect();
421
- }
422
- onUserMessage(callback) {
423
- this.pendingMessageCallback = callback;
424
- while (this.pendingMessages.length > 0) {
425
- callback(this.pendingMessages.shift());
426
- }
427
- }
428
- /**
429
- * Send message to session
430
- * @param body - Message body (can be MessageContent or raw content for agent messages)
431
- */
432
- sendClaudeSessionMessage(body) {
433
- let content;
434
- if (body.type === "user" && typeof body.message.content === "string") {
435
- content = {
436
- role: "user",
437
- content: {
438
- type: "text",
439
- text: body.message.content
440
- }
441
- };
442
- } else {
443
- content = {
444
- role: "agent",
445
- content: {
446
- type: "output",
447
- data: body
448
- // This wraps the entire Claude message
449
- }
450
- };
451
- }
452
- exports.logger.debugLargeJson("[SOCKET] Sending message through socket:", content);
453
- const encrypted = encodeBase64(encrypt(content, this.secret));
454
- this.socket.emit("message", {
455
- sid: this.sessionId,
456
- message: encrypted
457
- });
458
- if (body.type === "assistant" && body.message.usage) {
459
- try {
460
- this.sendUsageData(body.message.usage);
461
- } catch (error) {
462
- exports.logger.debug("[SOCKET] Failed to send usage data:", error);
463
- }
464
- }
465
- if (body.type === "summary" && "summary" in body && "leafUuid" in body) {
466
- this.updateMetadata((metadata) => ({
467
- ...metadata,
468
- summary: {
469
- text: body.summary,
470
- updatedAt: Date.now()
471
- }
472
- }));
473
- }
474
- }
475
- /**
476
- * Send a ping message to keep the connection alive
477
- */
478
- keepAlive(thinking) {
479
- this.socket.volatile.emit("session-alive", {
480
- sid: this.sessionId,
481
- time: Date.now(),
482
- thinking
483
- });
484
- }
485
- /**
486
- * Send session death message
487
- */
488
- sendSessionDeath() {
489
- this.socket.emit("session-end", { sid: this.sessionId, time: Date.now() });
490
- }
491
- /**
492
- * Send usage data to the server
493
- */
494
- sendUsageData(usage) {
495
- const totalTokens = usage.input_tokens + usage.output_tokens + (usage.cache_creation_input_tokens || 0) + (usage.cache_read_input_tokens || 0);
496
- const usageReport = {
497
- key: "claude-session",
498
- sessionId: this.sessionId,
499
- tokens: {
500
- total: totalTokens,
501
- input: usage.input_tokens,
502
- output: usage.output_tokens,
503
- cache_creation: usage.cache_creation_input_tokens || 0,
504
- cache_read: usage.cache_read_input_tokens || 0
505
- },
506
- cost: {
507
- // TODO: Calculate actual costs based on pricing
508
- // For now, using placeholder values
509
- total: 0,
510
- input: 0,
511
- output: 0
512
- }
513
- };
514
- exports.logger.debugLargeJson("[SOCKET] Sending usage data:", usageReport);
515
- this.socket.emit("usage-report", usageReport);
516
- }
517
- /**
518
- * Update session metadata
519
- * @param handler - Handler function that returns the updated metadata
520
- */
521
- updateMetadata(handler) {
522
- backoff(async () => {
523
- let updated = handler(this.metadata);
524
- const answer = await this.socket.emitWithAck("update-metadata", { sid: this.sessionId, expectedVersion: this.metadataVersion, metadata: encodeBase64(encrypt(updated, this.secret)) });
525
- if (answer.result === "success") {
526
- this.metadata = decrypt(decodeBase64(answer.metadata), this.secret);
527
- this.metadataVersion = answer.version;
528
- } else if (answer.result === "version-mismatch") {
529
- if (answer.version > this.metadataVersion) {
530
- this.metadataVersion = answer.version;
531
- this.metadata = decrypt(decodeBase64(answer.metadata), this.secret);
532
- }
533
- throw new Error("Metadata version mismatch");
534
- } else if (answer.result === "error") ;
535
- });
536
- }
537
- /**
538
- * Update session agent state
539
- * @param handler - Handler function that returns the updated agent state
540
- */
541
- updateAgentState(handler) {
542
- console.log("Updating agent state", this.agentState);
543
- backoff(async () => {
544
- let updated = handler(this.agentState || {});
545
- const answer = await this.socket.emitWithAck("update-state", { sid: this.sessionId, expectedVersion: this.agentStateVersion, agentState: updated ? encodeBase64(encrypt(updated, this.secret)) : null });
546
- if (answer.result === "success") {
547
- this.agentState = answer.agentState ? decrypt(decodeBase64(answer.agentState), this.secret) : null;
548
- this.agentStateVersion = answer.version;
549
- console.log("Agent state updated", this.agentState);
550
- } else if (answer.result === "version-mismatch") {
551
- if (answer.version > this.agentStateVersion) {
552
- this.agentStateVersion = answer.version;
553
- this.agentState = answer.agentState ? decrypt(decodeBase64(answer.agentState), this.secret) : null;
554
- }
555
- throw new Error("Agent state version mismatch");
556
- } else if (answer.result === "error") {
557
- console.error("Agent state update error", answer);
558
- }
559
- });
560
- }
561
- /**
562
- * Set a custom RPC handler for a specific method with encrypted arguments and responses
563
- * @param method - The method name to handle
564
- * @param handler - The handler function to call when the method is invoked
565
- */
566
- setHandler(method, handler) {
567
- const prefixedMethod = `${this.sessionId}:${method}`;
568
- this.rpcHandlers.set(prefixedMethod, handler);
569
- this.socket.emit("rpc-register", { method: prefixedMethod });
570
- exports.logger.debug("Registered RPC handler", { method, prefixedMethod });
571
- }
572
- /**
573
- * Re-register all RPC handlers after reconnection
574
- */
575
- reregisterHandlers() {
576
- exports.logger.debug("Re-registering RPC handlers after reconnection", {
577
- totalMethods: this.rpcHandlers.size
578
- });
579
- for (const [prefixedMethod] of this.rpcHandlers) {
580
- this.socket.emit("rpc-register", { method: prefixedMethod });
581
- exports.logger.debug("Re-registered method", { prefixedMethod });
582
- }
583
- }
584
- /**
585
- * Wait for socket buffer to flush
586
- */
587
- async flush() {
588
- if (!this.socket.connected) {
589
- return;
590
- }
591
- return new Promise((resolve) => {
592
- this.socket.emit("ping", () => {
593
- resolve();
594
- });
595
- setTimeout(() => {
596
- resolve();
597
- }, 1e4);
598
- });
599
- }
600
- async close() {
601
- this.socket.close();
602
- }
603
- }
604
-
605
- class PushNotificationClient {
606
- token;
607
- baseUrl;
608
- expo;
609
- constructor(token, baseUrl = "https://handy-api.korshakov.org") {
610
- this.token = token;
611
- this.baseUrl = baseUrl;
612
- this.expo = new expoServerSdk.Expo();
613
- }
614
- /**
615
- * Fetch all push tokens for the authenticated user
616
- */
617
- async fetchPushTokens() {
618
- try {
619
- const response = await axios.get(
620
- `${this.baseUrl}/v1/push-tokens`,
621
- {
622
- headers: {
623
- "Authorization": `Bearer ${this.token}`,
624
- "Content-Type": "application/json"
625
- }
626
- }
627
- );
628
- exports.logger.info(`Fetched ${response.data.tokens.length} push tokens`);
629
- return response.data.tokens;
630
- } catch (error) {
631
- exports.logger.debug("[PUSH] [ERROR] Failed to fetch push tokens:", error);
632
- throw new Error(`Failed to fetch push tokens: ${error instanceof Error ? error.message : "Unknown error"}`);
633
- }
634
- }
635
- /**
636
- * Send push notification via Expo Push API with retry
637
- * @param messages - Array of push messages to send
638
- */
639
- async sendPushNotifications(messages) {
640
- exports.logger.info(`Sending ${messages.length} push notifications`);
641
- const validMessages = messages.filter((message) => {
642
- if (Array.isArray(message.to)) {
643
- return message.to.every((token) => expoServerSdk.Expo.isExpoPushToken(token));
644
- }
645
- return expoServerSdk.Expo.isExpoPushToken(message.to);
646
- });
647
- if (validMessages.length === 0) {
648
- exports.logger.info("No valid Expo push tokens found");
649
- return;
650
- }
651
- const chunks = this.expo.chunkPushNotifications(validMessages);
652
- for (const chunk of chunks) {
653
- const startTime = Date.now();
654
- const timeout = 3e5;
655
- let attempt = 0;
656
- while (true) {
657
- try {
658
- const ticketChunk = await this.expo.sendPushNotificationsAsync(chunk);
659
- const errors = ticketChunk.filter((ticket) => ticket.status === "error");
660
- if (errors.length > 0) {
661
- exports.logger.debug("[PUSH] Some notifications failed:", errors);
662
- }
663
- if (errors.length === ticketChunk.length) {
664
- throw new Error("All push notifications in chunk failed");
665
- }
666
- break;
667
- } catch (error) {
668
- const elapsed = Date.now() - startTime;
669
- if (elapsed >= timeout) {
670
- exports.logger.debug("[PUSH] Timeout reached after 5 minutes, giving up on chunk");
671
- break;
672
- }
673
- attempt++;
674
- const delay = Math.min(1e3 * Math.pow(2, attempt), 3e4);
675
- const remainingTime = timeout - elapsed;
676
- const waitTime = Math.min(delay, remainingTime);
677
- if (waitTime > 0) {
678
- exports.logger.debug(`[PUSH] Retrying in ${waitTime}ms (attempt ${attempt})`);
679
- await new Promise((resolve) => setTimeout(resolve, waitTime));
680
- }
681
- }
682
- }
683
- }
684
- exports.logger.info(`Push notifications sent successfully`);
685
- }
686
- /**
687
- * Send a push notification to all registered devices for the user
688
- * @param title - Notification title
689
- * @param body - Notification body
690
- * @param data - Additional data to send with the notification
691
- */
692
- async sendToAllDevices(title, body, data) {
693
- const tokens = await this.fetchPushTokens();
694
- if (tokens.length === 0) {
695
- exports.logger.info("No push tokens found for user");
696
- return;
697
- }
698
- const messages = tokens.map((token) => ({
699
- to: token.token,
700
- title,
701
- body,
702
- data,
703
- sound: "default",
704
- priority: "high"
705
- }));
706
- await this.sendPushNotifications(messages);
707
- }
708
- }
709
-
710
- class ApiClient {
711
- token;
712
- secret;
713
- pushClient;
714
- constructor(token, secret) {
715
- this.token = token;
716
- this.secret = secret;
717
- this.pushClient = new PushNotificationClient(token);
718
- }
719
- /**
720
- * Create a new session or load existing one with the given tag
721
- */
722
- async getOrCreateSession(opts) {
723
- try {
724
- const response = await axios.post(
725
- `${exports.configuration.serverUrl}/v1/sessions`,
726
- {
727
- tag: opts.tag,
728
- metadata: encodeBase64(encrypt(opts.metadata, this.secret)),
729
- agentState: opts.state ? encodeBase64(encrypt(opts.state, this.secret)) : null
730
- },
731
- {
732
- headers: {
733
- "Authorization": `Bearer ${this.token}`,
734
- "Content-Type": "application/json"
735
- }
736
- }
737
- );
738
- exports.logger.debug(`Session created/loaded: ${response.data.session.id} (tag: ${opts.tag})`);
739
- let raw = response.data.session;
740
- let session = {
741
- id: raw.id,
742
- createdAt: raw.createdAt,
743
- updatedAt: raw.updatedAt,
744
- seq: raw.seq,
745
- metadata: decrypt(decodeBase64(raw.metadata), this.secret),
746
- metadataVersion: raw.metadataVersion,
747
- agentState: raw.agentState ? decrypt(decodeBase64(raw.agentState), this.secret) : null,
748
- agentStateVersion: raw.agentStateVersion
749
- };
750
- return session;
751
- } catch (error) {
752
- exports.logger.debug("[API] [ERROR] Failed to get or create session:", error);
753
- throw new Error(`Failed to get or create session: ${error instanceof Error ? error.message : "Unknown error"}`);
754
- }
755
- }
756
- /**
757
- * Start realtime session client
758
- * @param id - Session ID
759
- * @returns Session client
760
- */
761
- session(session) {
762
- return new ApiSessionClient(this.token, this.secret, session);
763
- }
764
- /**
765
- * Get push notification client
766
- * @returns Push notification client
767
- */
768
- push() {
769
- return this.pushClient;
770
- }
771
- }
772
-
773
- const UsageSchema = z.z.object({
774
- input_tokens: z.z.number().int().nonnegative(),
775
- cache_creation_input_tokens: z.z.number().int().nonnegative().optional(),
776
- cache_read_input_tokens: z.z.number().int().nonnegative().optional(),
777
- output_tokens: z.z.number().int().nonnegative(),
778
- service_tier: z.z.string().optional()
779
- });
780
- const TextContentSchema = z.z.object({
781
- type: z.z.literal("text"),
782
- text: z.z.string()
783
- });
784
- const ThinkingContentSchema = z.z.object({
785
- type: z.z.literal("thinking"),
786
- thinking: z.z.string(),
787
- signature: z.z.string()
788
- });
789
- const ToolUseContentSchema = z.z.object({
790
- type: z.z.literal("tool_use"),
791
- id: z.z.string(),
792
- name: z.z.string(),
793
- input: z.z.unknown()
794
- // Tool-specific input parameters
795
- });
796
- const ToolResultContentSchema = z.z.object({
797
- tool_use_id: z.z.string(),
798
- type: z.z.literal("tool_result"),
799
- content: z.z.union([
800
- z.z.string(),
801
- // For simple string responses
802
- z.z.array(TextContentSchema)
803
- // For structured content blocks (typically text)
804
- ]),
805
- is_error: z.z.boolean().optional()
806
- });
807
- const ContentSchema = z.z.union([
808
- TextContentSchema,
809
- ThinkingContentSchema,
810
- ToolUseContentSchema,
811
- ToolResultContentSchema
812
- ]);
813
- const UserMessageSchema = z.z.object({
814
- role: z.z.literal("user"),
815
- content: z.z.union([
816
- z.z.string(),
817
- // Simple string content
818
- z.z.array(z.z.union([ToolResultContentSchema, TextContentSchema]))
819
- ])
820
- });
821
- const AssistantMessageSchema = z.z.object({
822
- id: z.z.string(),
823
- type: z.z.literal("message"),
824
- role: z.z.literal("assistant"),
825
- model: z.z.string(),
826
- content: z.z.array(ContentSchema),
827
- stop_reason: z.z.string().nullable(),
828
- stop_sequence: z.z.string().nullable(),
829
- usage: UsageSchema
830
- });
831
- const BaseEntrySchema = z.z.object({
832
- cwd: z.z.string(),
833
- sessionId: z.z.string(),
834
- version: z.z.string(),
835
- uuid: z.z.string(),
836
- timestamp: z.z.string().datetime(),
837
- parent_tool_use_id: z.z.string().nullable().optional()
838
- });
839
- const SummaryEntrySchema = z.z.object({
840
- type: z.z.literal("summary"),
841
- summary: z.z.string(),
842
- leafUuid: z.z.string()
843
- });
844
- const UserEntrySchema = BaseEntrySchema.extend({
845
- type: z.z.literal("user"),
846
- message: UserMessageSchema,
847
- isMeta: z.z.boolean().optional(),
848
- toolUseResult: z.z.unknown().optional()
849
- // Present when user responds to tool use
850
- });
851
- const AssistantEntrySchema = BaseEntrySchema.extend({
852
- type: z.z.literal("assistant"),
853
- message: AssistantMessageSchema,
854
- requestId: z.z.string().optional()
855
- });
856
- const SystemEntrySchema = BaseEntrySchema.extend({
857
- type: z.z.literal("system"),
858
- content: z.z.string(),
859
- isMeta: z.z.boolean().optional(),
860
- level: z.z.string().optional(),
861
- parentUuid: z.z.string().optional(),
862
- isSidechain: z.z.boolean().optional(),
863
- userType: z.z.string().optional()
864
- });
865
- const RawJSONLinesSchema = z.z.discriminatedUnion("type", [
866
- UserEntrySchema,
867
- AssistantEntrySchema,
868
- SummaryEntrySchema,
869
- SystemEntrySchema
870
- ]);
871
-
872
- exports.ApiClient = ApiClient;
873
- exports.ApiSessionClient = ApiSessionClient;
874
- exports.RawJSONLinesSchema = RawJSONLinesSchema;
875
- exports.backoff = backoff;
876
- exports.decodeBase64 = decodeBase64;
877
- exports.decrypt = decrypt;
878
- exports.delay = delay;
879
- exports.encodeBase64 = encodeBase64;
880
- exports.encodeBase64Url = encodeBase64Url;
881
- exports.encrypt = encrypt;
882
- exports.initLoggerWithGlobalConfiguration = initLoggerWithGlobalConfiguration;
883
- exports.initializeConfiguration = initializeConfiguration;