@zonease/happy 0.6.42 → 0.6.43
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.
- package/dist/{api-CIE4_cWd.cjs → api-B-PlVQY6.cjs} +49 -3
- package/dist/{api-Ew6xr81i.mjs → api-BUCtd3cB.mjs} +49 -3
- package/dist/{auth-G9fZpVJ2.cjs → auth-BqGkUXvq.cjs} +2 -2
- package/dist/{auth-BzYevJo2.mjs → auth-DQH6q_q-.mjs} +4 -4
- package/dist/{auth-Dor79zTL.cjs → auth-OL3nNcDX.cjs} +4 -4
- package/dist/{auth-Q2STUNI-.mjs → auth-qM2eojWx.mjs} +2 -2
- package/dist/{browser-qDIIAL7S.cjs → browser-CY7VNU0C.cjs} +1 -1
- package/dist/{browser-BI7s-V8E.mjs → browser-D5RN_Axa.mjs} +1 -1
- package/dist/{claudeLocal-Db2tDC4X.mjs → claudeLocal-BXK_vQXS.mjs} +1 -1
- package/dist/{claudeLocal-f4uBLJaM.cjs → claudeLocal-HAXk0deK.cjs} +1 -1
- package/dist/{config-CHjDs8AS.mjs → config-2wMjzcHl.mjs} +1 -1
- package/dist/{config-CSBlEik9.cjs → config-CaKxWGVe.cjs} +1 -1
- package/dist/{connect-O_nA5BOC.mjs → connect-BAunPyp_.mjs} +4 -4
- package/dist/{connect-CJoTliii.cjs → connect-Dt1vY1BC.cjs} +4 -4
- package/dist/{controlClient-DoS9JqQC.mjs → controlClient-BzzTNSfl.mjs} +1 -1
- package/dist/{controlClient-CEz_p1zc.cjs → controlClient-yTkpwcOq.cjs} +1 -1
- package/dist/{cursorApprovalHook-DRAHfTXU.cjs → cursorApprovalHook-B2chnVni.cjs} +29 -11
- package/dist/{cursorApprovalHook-B0v1kGa7.mjs → cursorApprovalHook-BDLPzI5l.mjs} +29 -11
- package/dist/{cursorApprovalServer-JjPkdjGR.mjs → cursorApprovalServer-Ba1yOUCA.mjs} +109 -10
- package/dist/{cursorApprovalServer-DzY8yJlI.cjs → cursorApprovalServer-xwxVGL3u.cjs} +109 -8
- package/dist/{deviceKeys-B4aqjnE6.mjs → deviceKeys-CQyFFPtt.mjs} +2 -2
- package/dist/{deviceKeys-DyUn0bEx.cjs → deviceKeys-CdW-HPnz.cjs} +2 -2
- package/dist/{doctor-BJSuVRUZ.cjs → doctor-D4xWXiE7.cjs} +2 -2
- package/dist/{doctor-DRnft_5-.mjs → doctor-DDT2TXHH.mjs} +2 -2
- package/dist/{downloadImage-Cijmufpr.cjs → downloadImage-3A6zY5AX.cjs} +1 -372
- package/dist/downloadImage-BqNp0l7y.mjs +485 -0
- package/dist/{enroll-CysDL6ee.mjs → enroll-BlZ0giJI.mjs} +3 -3
- package/dist/{enroll-C2gunHdt.cjs → enroll-DeYs89Ic.cjs} +3 -3
- package/dist/{evidence-DsQ-h-_W.cjs → evidence-Bn1JXtdz.cjs} +1 -1
- package/dist/{evidence-DPutCuUr.mjs → evidence-PUnN9yPK.mjs} +1 -1
- package/dist/{formatImageMessage-6aV9YFWr.mjs → formatImageMessage-BRHeLf0-.mjs} +1 -1
- package/dist/{formatImageMessage-BPK_Ivfe.cjs → formatImageMessage-bVFGFDJl.cjs} +1 -1
- package/dist/index.cjs +50 -46
- package/dist/index.mjs +50 -46
- package/dist/{install-BsTA2tZn.mjs → install-BLPNuSeM.mjs} +2 -2
- package/dist/{install-DBg0xQ3g.mjs → install-BOIcR_Wr.mjs} +1 -1
- package/dist/{install-Tyhs6rUp.cjs → install-Jrs6YUu8.cjs} +1 -1
- package/dist/{install-DlOppA-e.cjs → install-Q-YMwwwg.cjs} +2 -2
- package/dist/lib.cjs +3 -3
- package/dist/lib.d.cts +1 -0
- package/dist/lib.d.mts +1 -0
- package/dist/lib.mjs +3 -3
- package/dist/{loadableToolOutput-DPGTtKJM.cjs → loadableToolOutput-B3qpMqXT.cjs} +2 -2
- package/dist/{loadableToolOutput-2dMPAp4N.mjs → loadableToolOutput-DzReWITb.mjs} +2 -2
- package/dist/{persistence-BcQmjobZ.cjs → persistence-D7zNFI-d.cjs} +1 -1
- package/dist/{persistence-D9tMm6bj.mjs → persistence-DbLMvLvk.mjs} +1 -1
- package/dist/{push-Cnm6JQMD.cjs → push-RT6Y0Hr3.cjs} +6 -6
- package/dist/{push-Dxsugkes.mjs → push-z5wQ4Ki_.mjs} +6 -6
- package/dist/registerKillSessionHandler-DmfnJ0zq.mjs +407 -0
- package/dist/registerKillSessionHandler-MoLdSQxM.cjs +411 -0
- package/dist/{run-BEflQaQ2.mjs → run-BFnSUK1o.mjs} +10 -8
- package/dist/{run-CiPWWhXt.cjs → run-C5StYRIB.cjs} +10 -8
- package/dist/{runClaude-BVXsyCHb.cjs → runClaude-ChRp6f5G.cjs} +26 -26
- package/dist/{runClaude-sPkSqHWY.mjs → runClaude-CjENBdrX.mjs} +21 -21
- package/dist/{runCodex-C4rHkIyw.mjs → runCodex-BzQWlRoj.mjs} +26 -26
- package/dist/{runCodex-BAwhdmSA.cjs → runCodex-DcQGyotH.cjs} +28 -28
- package/dist/{runCursor-DiHLWMs8.mjs → runCursor-B73z6MCN.mjs} +210 -34
- package/dist/{runCursor-CD5wC3gA.cjs → runCursor-BlPAxaTy.cjs} +210 -34
- package/dist/{runGemini-B-93gOqB.mjs → runGemini-BPv4UzuF.mjs} +17 -17
- package/dist/{runGemini-Cto-adir.cjs → runGemini-JFqaIC3u.cjs} +19 -19
- package/dist/{runOneShot-BfIzE9W4.cjs → runOneShot-2iV11e9L.cjs} +2 -2
- package/dist/{runOneShot-DGjlYVhR.mjs → runOneShot-DTukim2A.mjs} +2 -2
- package/dist/{serve-CqL6NWDr.cjs → serve-BDwuAIK4.cjs} +6 -6
- package/dist/{serve-ttlqF5jn.mjs → serve-BnlYj5ek.mjs} +6 -6
- package/dist/{session-BZhGpQUJ.cjs → session-Cp9LEESM.cjs} +5 -5
- package/dist/{session-Co0REU9e.mjs → session-gfeFU8CA.mjs} +5 -5
- package/dist/{sessionKeyCache-BwFUGgMs.cjs → sessionKeyCache-3Pme04yL.cjs} +1 -1
- package/dist/{sessionKeyCache-pXTjpETo.mjs → sessionKeyCache-DtBS_Sb3.mjs} +1 -1
- package/dist/{sessionList-DaufR-sA.mjs → sessionList-B1w4BUdv.mjs} +2 -2
- package/dist/{sessionList-fG5uAPzU.cjs → sessionList-BR_5UDZJ.cjs} +2 -2
- package/dist/{sessionSummary-CjZPt6nr.cjs → sessionSummary-DLweYgHO.cjs} +3 -3
- package/dist/{sessionSummary-Dv6dPABg.mjs → sessionSummary-E-a2bg8W.mjs} +3 -3
- package/dist/{setupOfflineReconnection-DW5il97B.mjs → setupOfflineReconnection-DHwthFtd.mjs} +5 -3
- package/dist/{setupOfflineReconnection-B6coH9QN.cjs → setupOfflineReconnection-Dkp00dC9.cjs} +7 -5
- package/dist/{spawnHappyCLI-Cfu7C1uM.cjs → spawnHappyCLI-C2uY9WV-.cjs} +1 -1
- package/dist/{spawnHappyCLI-DhUeycct.mjs → spawnHappyCLI-Dt7fbmbk.mjs} +1 -1
- package/dist/{ssh-8tPIKk-i.mjs → ssh-C-nEZiGP.mjs} +5 -5
- package/dist/{ssh-C4YTSHXL.cjs → ssh-CsnS89Lr.cjs} +5 -5
- package/dist/{task-CH-oidFy.mjs → task-B-8_QGGX.mjs} +6 -6
- package/dist/{task-DFW-PecP.cjs → task-lrLb4FCL.cjs} +6 -6
- package/dist/{uninstall-CeioRZNI.mjs → uninstall-CirMt_WC.mjs} +2 -2
- package/dist/{uninstall-yTSL3X6Y.cjs → uninstall-DMjUlEXT.cjs} +2 -2
- package/dist/{update-Derd2hoX.mjs → update-CfXbYshs.mjs} +3 -3
- package/dist/{update-Bju28vNP.cjs → update-mx2p28IP.cjs} +3 -3
- package/package.json +1 -1
- package/dist/downloadImage-BpVF7A79.mjs +0 -854
- package/dist/gitWorktree-C6jLoaMw.cjs +0 -39
- package/dist/gitWorktree-CzJDU2BV.mjs +0 -37
|
@@ -1,854 +0,0 @@
|
|
|
1
|
-
import { l as logger, r as readCredentials } from './persistence-D9tMm6bj.mjs';
|
|
2
|
-
import { createHash } from 'crypto';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
import { p as projectPath } from './projectPath-BTBIMB57.mjs';
|
|
5
|
-
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
6
|
-
import { createServer } from 'node:http';
|
|
7
|
-
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
8
|
-
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
9
|
-
import { z } from 'zod';
|
|
10
|
-
import { l as listDevices, d as deviceExec } from './deviceKeys-B4aqjnE6.mjs';
|
|
11
|
-
import { randomUUID } from 'node:crypto';
|
|
12
|
-
import { s as shouldEnableOrchestratorTools } from './prompt-BsAZsPbo.mjs';
|
|
13
|
-
import './mcpToolSchemas-CjeTfrAs.mjs';
|
|
14
|
-
import './index-DTV7drqs.mjs';
|
|
15
|
-
import axios from 'axios';
|
|
16
|
-
import 'node:events';
|
|
17
|
-
import 'socket.io-client';
|
|
18
|
-
import './api-Ew6xr81i.mjs';
|
|
19
|
-
import 'tweetnacl';
|
|
20
|
-
import 'ws';
|
|
21
|
-
import '@stablelib/base64';
|
|
22
|
-
import 'node:os';
|
|
23
|
-
import 'node:fs/promises';
|
|
24
|
-
import 'node:fs';
|
|
25
|
-
import 'node:readline';
|
|
26
|
-
import 'node:child_process';
|
|
27
|
-
import 'expo-server-sdk';
|
|
28
|
-
import 'chalk';
|
|
29
|
-
import './types-BoJh4Qfv.mjs';
|
|
30
|
-
|
|
31
|
-
function parseCompact(message) {
|
|
32
|
-
const trimmed = message.trim();
|
|
33
|
-
if (trimmed === "/compact") {
|
|
34
|
-
return {
|
|
35
|
-
isCompact: true,
|
|
36
|
-
originalMessage: trimmed
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
if (trimmed.startsWith("/compact ")) {
|
|
40
|
-
return {
|
|
41
|
-
isCompact: true,
|
|
42
|
-
originalMessage: trimmed
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
return {
|
|
46
|
-
isCompact: false,
|
|
47
|
-
originalMessage: message
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
function parseClear(message) {
|
|
51
|
-
const trimmed = message.trim();
|
|
52
|
-
return {
|
|
53
|
-
isClear: trimmed === "/clear"
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
function parseSpecialCommand(message) {
|
|
57
|
-
const compactResult = parseCompact(message);
|
|
58
|
-
if (compactResult.isCompact) {
|
|
59
|
-
return {
|
|
60
|
-
type: "compact",
|
|
61
|
-
originalMessage: compactResult.originalMessage
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
const clearResult = parseClear(message);
|
|
65
|
-
if (clearResult.isClear) {
|
|
66
|
-
return {
|
|
67
|
-
type: "clear"
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
return {
|
|
71
|
-
type: null
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
class MessageQueue2 {
|
|
76
|
-
queue = [];
|
|
77
|
-
// Made public for testing
|
|
78
|
-
waiter = null;
|
|
79
|
-
closed = false;
|
|
80
|
-
onMessageHandler = null;
|
|
81
|
-
modeHasher;
|
|
82
|
-
constructor(modeHasher, onMessageHandler = null) {
|
|
83
|
-
this.modeHasher = modeHasher;
|
|
84
|
-
this.onMessageHandler = onMessageHandler;
|
|
85
|
-
logger.debug(`[MessageQueue2] Initialized`);
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Set a handler that will be called when a message arrives
|
|
89
|
-
*/
|
|
90
|
-
setOnMessage(handler) {
|
|
91
|
-
this.onMessageHandler = handler;
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Push a message to the queue with a mode.
|
|
95
|
-
*/
|
|
96
|
-
push(message, mode) {
|
|
97
|
-
if (this.closed) {
|
|
98
|
-
throw new Error("Cannot push to closed queue");
|
|
99
|
-
}
|
|
100
|
-
const modeHash = this.modeHasher(mode);
|
|
101
|
-
logger.debug(`[MessageQueue2] push() called with mode hash: ${modeHash}`);
|
|
102
|
-
this.queue.push({
|
|
103
|
-
message,
|
|
104
|
-
mode,
|
|
105
|
-
modeHash,
|
|
106
|
-
isolate: false
|
|
107
|
-
});
|
|
108
|
-
if (this.onMessageHandler) {
|
|
109
|
-
this.onMessageHandler(message, mode);
|
|
110
|
-
}
|
|
111
|
-
if (this.waiter) {
|
|
112
|
-
logger.debug(`[MessageQueue2] Notifying waiter`);
|
|
113
|
-
const waiter = this.waiter;
|
|
114
|
-
this.waiter = null;
|
|
115
|
-
waiter(true);
|
|
116
|
-
}
|
|
117
|
-
logger.debug(`[MessageQueue2] push() completed. Queue size: ${this.queue.length}`);
|
|
118
|
-
}
|
|
119
|
-
/**
|
|
120
|
-
* Push a message immediately without batching delay.
|
|
121
|
-
* Does not clear the queue or enforce isolation.
|
|
122
|
-
*/
|
|
123
|
-
pushImmediate(message, mode) {
|
|
124
|
-
if (this.closed) {
|
|
125
|
-
throw new Error("Cannot push to closed queue");
|
|
126
|
-
}
|
|
127
|
-
const modeHash = this.modeHasher(mode);
|
|
128
|
-
logger.debug(`[MessageQueue2] pushImmediate() called with mode hash: ${modeHash}`);
|
|
129
|
-
this.queue.push({
|
|
130
|
-
message,
|
|
131
|
-
mode,
|
|
132
|
-
modeHash,
|
|
133
|
-
isolate: false
|
|
134
|
-
});
|
|
135
|
-
if (this.onMessageHandler) {
|
|
136
|
-
this.onMessageHandler(message, mode);
|
|
137
|
-
}
|
|
138
|
-
if (this.waiter) {
|
|
139
|
-
logger.debug(`[MessageQueue2] Notifying waiter for immediate message`);
|
|
140
|
-
const waiter = this.waiter;
|
|
141
|
-
this.waiter = null;
|
|
142
|
-
waiter(true);
|
|
143
|
-
}
|
|
144
|
-
logger.debug(`[MessageQueue2] pushImmediate() completed. Queue size: ${this.queue.length}`);
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Push a message that must be processed in complete isolation.
|
|
148
|
-
* Clears any pending messages and ensures this message is never batched with others.
|
|
149
|
-
* Used for special commands that require dedicated processing.
|
|
150
|
-
*/
|
|
151
|
-
pushIsolateAndClear(message, mode) {
|
|
152
|
-
if (this.closed) {
|
|
153
|
-
throw new Error("Cannot push to closed queue");
|
|
154
|
-
}
|
|
155
|
-
const modeHash = this.modeHasher(mode);
|
|
156
|
-
logger.debug(`[MessageQueue2] pushIsolateAndClear() called with mode hash: ${modeHash} - clearing ${this.queue.length} pending messages`);
|
|
157
|
-
this.queue = [];
|
|
158
|
-
this.queue.push({
|
|
159
|
-
message,
|
|
160
|
-
mode,
|
|
161
|
-
modeHash,
|
|
162
|
-
isolate: true
|
|
163
|
-
});
|
|
164
|
-
if (this.onMessageHandler) {
|
|
165
|
-
this.onMessageHandler(message, mode);
|
|
166
|
-
}
|
|
167
|
-
if (this.waiter) {
|
|
168
|
-
logger.debug(`[MessageQueue2] Notifying waiter for isolated message`);
|
|
169
|
-
const waiter = this.waiter;
|
|
170
|
-
this.waiter = null;
|
|
171
|
-
waiter(true);
|
|
172
|
-
}
|
|
173
|
-
logger.debug(`[MessageQueue2] pushIsolateAndClear() completed. Queue size: ${this.queue.length}`);
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
|
-
* Push a message to the beginning of the queue with a mode.
|
|
177
|
-
*/
|
|
178
|
-
unshift(message, mode) {
|
|
179
|
-
if (this.closed) {
|
|
180
|
-
throw new Error("Cannot unshift to closed queue");
|
|
181
|
-
}
|
|
182
|
-
const modeHash = this.modeHasher(mode);
|
|
183
|
-
logger.debug(`[MessageQueue2] unshift() called with mode hash: ${modeHash}`);
|
|
184
|
-
this.queue.unshift({
|
|
185
|
-
message,
|
|
186
|
-
mode,
|
|
187
|
-
modeHash,
|
|
188
|
-
isolate: false
|
|
189
|
-
});
|
|
190
|
-
if (this.onMessageHandler) {
|
|
191
|
-
this.onMessageHandler(message, mode);
|
|
192
|
-
}
|
|
193
|
-
if (this.waiter) {
|
|
194
|
-
logger.debug(`[MessageQueue2] Notifying waiter`);
|
|
195
|
-
const waiter = this.waiter;
|
|
196
|
-
this.waiter = null;
|
|
197
|
-
waiter(true);
|
|
198
|
-
}
|
|
199
|
-
logger.debug(`[MessageQueue2] unshift() completed. Queue size: ${this.queue.length}`);
|
|
200
|
-
}
|
|
201
|
-
/**
|
|
202
|
-
* Reset the queue - clears all messages and resets to empty state
|
|
203
|
-
*/
|
|
204
|
-
reset() {
|
|
205
|
-
logger.debug(`[MessageQueue2] reset() called. Clearing ${this.queue.length} messages`);
|
|
206
|
-
this.queue = [];
|
|
207
|
-
this.closed = false;
|
|
208
|
-
this.waiter = null;
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* Close the queue - no more messages can be pushed
|
|
212
|
-
*/
|
|
213
|
-
close() {
|
|
214
|
-
logger.debug(`[MessageQueue2] close() called`);
|
|
215
|
-
this.closed = true;
|
|
216
|
-
if (this.waiter) {
|
|
217
|
-
const waiter = this.waiter;
|
|
218
|
-
this.waiter = null;
|
|
219
|
-
waiter(false);
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
/**
|
|
223
|
-
* Check if the queue is closed
|
|
224
|
-
*/
|
|
225
|
-
isClosed() {
|
|
226
|
-
return this.closed;
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* Get the current queue size
|
|
230
|
-
*/
|
|
231
|
-
size() {
|
|
232
|
-
return this.queue.length;
|
|
233
|
-
}
|
|
234
|
-
/**
|
|
235
|
-
* Wait for messages and return all messages with the same mode.
|
|
236
|
-
* For string messages, multiple messages are joined with newlines.
|
|
237
|
-
* For object messages (e.g., mixed content with images), returns them one at a time.
|
|
238
|
-
* Returns { message: M, mode: T } or null if aborted/closed
|
|
239
|
-
*/
|
|
240
|
-
async waitForMessagesAndGetAsString(abortSignal) {
|
|
241
|
-
if (this.queue.length > 0) {
|
|
242
|
-
return this.collectBatch();
|
|
243
|
-
}
|
|
244
|
-
if (this.closed || abortSignal?.aborted) {
|
|
245
|
-
return null;
|
|
246
|
-
}
|
|
247
|
-
const hasMessages = await this.waitForMessages(abortSignal);
|
|
248
|
-
if (!hasMessages) {
|
|
249
|
-
return null;
|
|
250
|
-
}
|
|
251
|
-
return this.collectBatch();
|
|
252
|
-
}
|
|
253
|
-
/**
|
|
254
|
-
* Collect a batch of messages with the same mode, respecting isolation requirements.
|
|
255
|
-
* For string messages, joins them with newlines.
|
|
256
|
-
* For object messages (like mixed content with images), returns one at a time.
|
|
257
|
-
*/
|
|
258
|
-
collectBatch() {
|
|
259
|
-
if (this.queue.length === 0) {
|
|
260
|
-
return null;
|
|
261
|
-
}
|
|
262
|
-
const firstItem = this.queue[0];
|
|
263
|
-
let mode = firstItem.mode;
|
|
264
|
-
let isolate = firstItem.isolate ?? false;
|
|
265
|
-
const targetModeHash = firstItem.modeHash;
|
|
266
|
-
if (firstItem.isolate) {
|
|
267
|
-
const item = this.queue.shift();
|
|
268
|
-
logger.debug(`[MessageQueue2] Collected isolated message with mode hash: ${targetModeHash}`);
|
|
269
|
-
return {
|
|
270
|
-
message: item.message,
|
|
271
|
-
mode,
|
|
272
|
-
hash: targetModeHash,
|
|
273
|
-
isolate
|
|
274
|
-
};
|
|
275
|
-
}
|
|
276
|
-
if (typeof firstItem.message !== "string") {
|
|
277
|
-
const item = this.queue.shift();
|
|
278
|
-
logger.debug(`[MessageQueue2] Collected single object message with mode hash: ${targetModeHash}`);
|
|
279
|
-
return {
|
|
280
|
-
message: item.message,
|
|
281
|
-
mode,
|
|
282
|
-
hash: targetModeHash,
|
|
283
|
-
isolate
|
|
284
|
-
};
|
|
285
|
-
}
|
|
286
|
-
const sameModeMessages = [];
|
|
287
|
-
while (this.queue.length > 0 && this.queue[0].modeHash === targetModeHash && !this.queue[0].isolate && typeof this.queue[0].message === "string") {
|
|
288
|
-
const item = this.queue.shift();
|
|
289
|
-
sameModeMessages.push(item.message);
|
|
290
|
-
}
|
|
291
|
-
logger.debug(`[MessageQueue2] Collected batch of ${sameModeMessages.length} messages with mode hash: ${targetModeHash}`);
|
|
292
|
-
const combinedMessage = sameModeMessages.join("\n");
|
|
293
|
-
return {
|
|
294
|
-
message: combinedMessage,
|
|
295
|
-
mode,
|
|
296
|
-
hash: targetModeHash,
|
|
297
|
-
isolate
|
|
298
|
-
};
|
|
299
|
-
}
|
|
300
|
-
/**
|
|
301
|
-
* Wait for messages to arrive
|
|
302
|
-
*/
|
|
303
|
-
waitForMessages(abortSignal) {
|
|
304
|
-
return new Promise((resolve) => {
|
|
305
|
-
let abortHandler = null;
|
|
306
|
-
if (abortSignal) {
|
|
307
|
-
abortHandler = () => {
|
|
308
|
-
logger.debug("[MessageQueue2] Wait aborted");
|
|
309
|
-
if (this.waiter === waiterFunc) {
|
|
310
|
-
this.waiter = null;
|
|
311
|
-
}
|
|
312
|
-
resolve(false);
|
|
313
|
-
};
|
|
314
|
-
abortSignal.addEventListener("abort", abortHandler);
|
|
315
|
-
}
|
|
316
|
-
const waiterFunc = (hasMessages) => {
|
|
317
|
-
if (abortHandler && abortSignal) {
|
|
318
|
-
abortSignal.removeEventListener("abort", abortHandler);
|
|
319
|
-
}
|
|
320
|
-
resolve(hasMessages);
|
|
321
|
-
};
|
|
322
|
-
if (this.queue.length > 0) {
|
|
323
|
-
if (abortHandler && abortSignal) {
|
|
324
|
-
abortSignal.removeEventListener("abort", abortHandler);
|
|
325
|
-
}
|
|
326
|
-
resolve(true);
|
|
327
|
-
return;
|
|
328
|
-
}
|
|
329
|
-
if (this.closed || abortSignal?.aborted) {
|
|
330
|
-
if (abortHandler && abortSignal) {
|
|
331
|
-
abortSignal.removeEventListener("abort", abortHandler);
|
|
332
|
-
}
|
|
333
|
-
resolve(false);
|
|
334
|
-
return;
|
|
335
|
-
}
|
|
336
|
-
this.waiter = waiterFunc;
|
|
337
|
-
logger.debug("[MessageQueue2] Waiting for messages...");
|
|
338
|
-
});
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
function deterministicStringify(obj, options = {}) {
|
|
343
|
-
const {
|
|
344
|
-
undefinedBehavior = "omit",
|
|
345
|
-
sortArrays = false,
|
|
346
|
-
replacer,
|
|
347
|
-
includeSymbols = false
|
|
348
|
-
} = options;
|
|
349
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
350
|
-
function processValue(value, key) {
|
|
351
|
-
if (replacer && key !== void 0) {
|
|
352
|
-
value = replacer(key, value);
|
|
353
|
-
}
|
|
354
|
-
if (value === null) return null;
|
|
355
|
-
if (value === void 0) {
|
|
356
|
-
switch (undefinedBehavior) {
|
|
357
|
-
case "omit":
|
|
358
|
-
return void 0;
|
|
359
|
-
case "null":
|
|
360
|
-
return null;
|
|
361
|
-
case "throw":
|
|
362
|
-
throw new Error(`Undefined value at key: ${key}`);
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
|
|
366
|
-
return value;
|
|
367
|
-
}
|
|
368
|
-
if (value instanceof Date) {
|
|
369
|
-
return value.toISOString();
|
|
370
|
-
}
|
|
371
|
-
if (value instanceof RegExp) {
|
|
372
|
-
return value.toString();
|
|
373
|
-
}
|
|
374
|
-
if (typeof value === "function") {
|
|
375
|
-
return void 0;
|
|
376
|
-
}
|
|
377
|
-
if (typeof value === "symbol") {
|
|
378
|
-
return includeSymbols ? value.toString() : void 0;
|
|
379
|
-
}
|
|
380
|
-
if (typeof value === "bigint") {
|
|
381
|
-
return value.toString() + "n";
|
|
382
|
-
}
|
|
383
|
-
if (seen.has(value)) {
|
|
384
|
-
throw new Error("Circular reference detected");
|
|
385
|
-
}
|
|
386
|
-
seen.add(value);
|
|
387
|
-
if (Array.isArray(value)) {
|
|
388
|
-
const processed2 = value.map((item, index) => processValue(item, String(index))).filter((item) => item !== void 0);
|
|
389
|
-
if (sortArrays) {
|
|
390
|
-
processed2.sort((a, b) => {
|
|
391
|
-
const aStr = JSON.stringify(processValue(a));
|
|
392
|
-
const bStr = JSON.stringify(processValue(b));
|
|
393
|
-
return aStr.localeCompare(bStr);
|
|
394
|
-
});
|
|
395
|
-
}
|
|
396
|
-
seen.delete(value);
|
|
397
|
-
return processed2;
|
|
398
|
-
}
|
|
399
|
-
if (value.constructor === Object || value.constructor === void 0) {
|
|
400
|
-
const processed2 = {};
|
|
401
|
-
const keys = Object.keys(value).sort();
|
|
402
|
-
for (const k of keys) {
|
|
403
|
-
const processedValue = processValue(value[k], k);
|
|
404
|
-
if (processedValue !== void 0) {
|
|
405
|
-
processed2[k] = processedValue;
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
seen.delete(value);
|
|
409
|
-
return processed2;
|
|
410
|
-
}
|
|
411
|
-
try {
|
|
412
|
-
const plain = { ...value };
|
|
413
|
-
seen.delete(value);
|
|
414
|
-
return processValue(plain, key);
|
|
415
|
-
} catch {
|
|
416
|
-
seen.delete(value);
|
|
417
|
-
return String(value);
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
const processed = processValue(obj);
|
|
421
|
-
return JSON.stringify(processed);
|
|
422
|
-
}
|
|
423
|
-
function hashObject(obj, options, encoding = "hex") {
|
|
424
|
-
const jsonString = deterministicStringify(obj, options);
|
|
425
|
-
return createHash("sha256").update(jsonString).digest(encoding);
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
function createMcpServer(client, options) {
|
|
429
|
-
const mcp = new McpServer({
|
|
430
|
-
name: "Happy MCP",
|
|
431
|
-
version: "1.0.0"
|
|
432
|
-
});
|
|
433
|
-
const handler = async (title) => {
|
|
434
|
-
logger.debug("[happyMCP] Changing title to:", title);
|
|
435
|
-
if (client.isTitlePinned) {
|
|
436
|
-
return { success: false, error: "Title is pinned by user and cannot be changed automatically" };
|
|
437
|
-
}
|
|
438
|
-
try {
|
|
439
|
-
client.sendClaudeSessionMessage({
|
|
440
|
-
type: "summary",
|
|
441
|
-
summary: title,
|
|
442
|
-
leafUuid: randomUUID()
|
|
443
|
-
});
|
|
444
|
-
return { success: true };
|
|
445
|
-
} catch (error) {
|
|
446
|
-
return { success: false, error: String(error) };
|
|
447
|
-
}
|
|
448
|
-
};
|
|
449
|
-
mcp.registerTool("device_list", {
|
|
450
|
-
description: "List enrolled Happy devices (servers and computers) with their online state. Use before device_exec when you need a device id.",
|
|
451
|
-
title: "List Devices",
|
|
452
|
-
inputSchema: {}
|
|
453
|
-
}, async () => {
|
|
454
|
-
const credentials = await readCredentials();
|
|
455
|
-
if (!credentials) {
|
|
456
|
-
return { content: [{ type: "text", text: "No Happy credentials on this machine." }] };
|
|
457
|
-
}
|
|
458
|
-
try {
|
|
459
|
-
const devices = await listDevices(credentials);
|
|
460
|
-
const target = client.targetDevices.map((device) => device.id);
|
|
461
|
-
const lines = devices.map((device) => {
|
|
462
|
-
const marks = [device.active ? "online" : "offline"];
|
|
463
|
-
if (target.includes(device.id)) marks.push("session default");
|
|
464
|
-
return `${device.id} ${device.name}${device.platform ? ` (${device.platform})` : ""} [${marks.join(", ")}]${device.description ? ` \u2014 ${device.description}` : ""}`;
|
|
465
|
-
});
|
|
466
|
-
return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No devices enrolled yet." }] };
|
|
467
|
-
} catch (error) {
|
|
468
|
-
return { content: [{ type: "text", text: `Failed to list devices: ${error instanceof Error ? error.message : String(error)}` }] };
|
|
469
|
-
}
|
|
470
|
-
});
|
|
471
|
-
mcp.registerTool("device_exec", {
|
|
472
|
-
description: "Run a shell command on an enrolled device (a server or computer registered in Happy). Omit deviceId to use the device the user selected for this session. Returns stdout, stderr and exit code.",
|
|
473
|
-
title: "Run Command on Device",
|
|
474
|
-
inputSchema: {
|
|
475
|
-
command: z.string().describe("Shell command to run on the device"),
|
|
476
|
-
deviceId: z.string().optional().describe("Target device id. Defaults to the session's selected device."),
|
|
477
|
-
cwd: z.string().optional().describe("Working directory on the device"),
|
|
478
|
-
timeout: z.number().optional().describe("Timeout in milliseconds (default 60000)")
|
|
479
|
-
}
|
|
480
|
-
}, async (args) => {
|
|
481
|
-
const credentials = await readCredentials();
|
|
482
|
-
if (!credentials) {
|
|
483
|
-
return { content: [{ type: "text", text: "No Happy credentials on this machine." }] };
|
|
484
|
-
}
|
|
485
|
-
const targets = client.targetDevices;
|
|
486
|
-
const deviceId = args.deviceId || (targets.length === 1 ? targets[0].id : null);
|
|
487
|
-
if (!deviceId && targets.length > 1) {
|
|
488
|
-
return { content: [{ type: "text", text: `This session targets several devices \u2014 pass deviceId: ${targets.map((device) => `${device.name} (${device.id})`).join(", ")}` }] };
|
|
489
|
-
}
|
|
490
|
-
if (!deviceId) {
|
|
491
|
-
return { content: [{ type: "text", text: "No device selected for this session. Pick one in the app or pass deviceId (see device_list)." }] };
|
|
492
|
-
}
|
|
493
|
-
try {
|
|
494
|
-
const result = await deviceExec(client.rpcSocket, credentials, deviceId, args.command, {
|
|
495
|
-
cwd: args.cwd,
|
|
496
|
-
timeout: args.timeout,
|
|
497
|
-
deviceKeyBase64: targets.find((device) => device.id === deviceId)?.key ?? null
|
|
498
|
-
});
|
|
499
|
-
const parts = [`exit code: ${result.exitCode}`];
|
|
500
|
-
if (result.stdout) parts.push(`stdout:
|
|
501
|
-
${result.stdout}`);
|
|
502
|
-
if (result.stderr) parts.push(`stderr:
|
|
503
|
-
${result.stderr}`);
|
|
504
|
-
return { content: [{ type: "text", text: parts.join("\n\n") }] };
|
|
505
|
-
} catch (error) {
|
|
506
|
-
return { content: [{ type: "text", text: `Device command failed: ${error instanceof Error ? error.message : String(error)}` }] };
|
|
507
|
-
}
|
|
508
|
-
});
|
|
509
|
-
mcp.registerTool("change_title", {
|
|
510
|
-
description: "Change the title of the current chat session",
|
|
511
|
-
title: "Change Chat Title",
|
|
512
|
-
inputSchema: {
|
|
513
|
-
title: z.string().describe("The new title for the chat session")
|
|
514
|
-
}
|
|
515
|
-
}, async (args) => {
|
|
516
|
-
const response = await handler(args.title);
|
|
517
|
-
logger.debug("[happyMCP] Response:", response);
|
|
518
|
-
if (response.success) {
|
|
519
|
-
return {
|
|
520
|
-
content: [
|
|
521
|
-
{
|
|
522
|
-
type: "text",
|
|
523
|
-
text: `Successfully changed chat title to: "${args.title}"`
|
|
524
|
-
}
|
|
525
|
-
],
|
|
526
|
-
isError: false
|
|
527
|
-
};
|
|
528
|
-
} else {
|
|
529
|
-
return {
|
|
530
|
-
content: [
|
|
531
|
-
{
|
|
532
|
-
type: "text",
|
|
533
|
-
text: `Failed to change chat title: ${response.error || "Unknown error"}`
|
|
534
|
-
}
|
|
535
|
-
],
|
|
536
|
-
isError: true
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
});
|
|
540
|
-
mcp.registerTool("preview_html", {
|
|
541
|
-
description: "Preview an HTML page in the client app. The HTML must be a complete, self-contained document with all CSS and JS inlined.",
|
|
542
|
-
title: "Preview HTML",
|
|
543
|
-
inputSchema: {
|
|
544
|
-
html: z.string().describe("Complete self-contained HTML document string"),
|
|
545
|
-
title: z.string().optional().describe("Display title for the preview")
|
|
546
|
-
}
|
|
547
|
-
}, async (args) => {
|
|
548
|
-
logger.debug("[happyMCP] Preview HTML:", args.title || "Untitled");
|
|
549
|
-
return {
|
|
550
|
-
content: [{
|
|
551
|
-
type: "text",
|
|
552
|
-
text: `HTML preview ready: ${args.title || "Untitled"}`
|
|
553
|
-
}],
|
|
554
|
-
isError: false
|
|
555
|
-
};
|
|
556
|
-
});
|
|
557
|
-
return mcp;
|
|
558
|
-
}
|
|
559
|
-
async function startHappyServer(client) {
|
|
560
|
-
const transports = /* @__PURE__ */ new Map();
|
|
561
|
-
const enableOrchestratorTools = shouldEnableOrchestratorTools();
|
|
562
|
-
const toolNames = ["change_title", "preview_html", "device_list", "device_exec"];
|
|
563
|
-
const originalConsoleError = console.error;
|
|
564
|
-
console.error = (...args) => {
|
|
565
|
-
logger.debug("[happyMCP] console.error:", ...args);
|
|
566
|
-
originalConsoleError.apply(console, args);
|
|
567
|
-
};
|
|
568
|
-
const server = createServer(async (req, res) => {
|
|
569
|
-
const sessionId = req.headers["mcp-session-id"];
|
|
570
|
-
logger.debug("[happyMCP] Received request:", req.method, req.url, "sessionId:", sessionId);
|
|
571
|
-
try {
|
|
572
|
-
if (req.method === "POST") {
|
|
573
|
-
const body = await readRequestBody(req);
|
|
574
|
-
const parsedBody = JSON.parse(body);
|
|
575
|
-
let transport;
|
|
576
|
-
if (sessionId && transports.has(sessionId)) {
|
|
577
|
-
transport = transports.get(sessionId);
|
|
578
|
-
logger.debug("[happyMCP] Reusing transport for session:", sessionId);
|
|
579
|
-
} else if (!sessionId && isInitializeRequest(parsedBody)) {
|
|
580
|
-
logger.debug("[happyMCP] New initialize request, creating transport");
|
|
581
|
-
transport = new StreamableHTTPServerTransport({
|
|
582
|
-
sessionIdGenerator: () => randomUUID(),
|
|
583
|
-
onsessioninitialized: (newSessionId) => {
|
|
584
|
-
logger.debug("[happyMCP] Session initialized:", newSessionId);
|
|
585
|
-
transports.set(newSessionId, transport);
|
|
586
|
-
}
|
|
587
|
-
});
|
|
588
|
-
transport.onclose = () => {
|
|
589
|
-
const sid = transport.sessionId;
|
|
590
|
-
if (sid && transports.has(sid)) {
|
|
591
|
-
logger.debug("[happyMCP] Transport closed, removing session:", sid);
|
|
592
|
-
transports.delete(sid);
|
|
593
|
-
}
|
|
594
|
-
};
|
|
595
|
-
transport.onerror = (error) => {
|
|
596
|
-
logger.debug("[happyMCP] Transport error:", error);
|
|
597
|
-
};
|
|
598
|
-
const mcp = createMcpServer(client, { enableOrchestratorTools });
|
|
599
|
-
await mcp.connect(transport);
|
|
600
|
-
await transport.handleRequest(req, res, parsedBody);
|
|
601
|
-
logger.debug("[happyMCP] Initialize request handled successfully");
|
|
602
|
-
return;
|
|
603
|
-
} else {
|
|
604
|
-
logger.debug("[happyMCP] Bad request: no session ID and not initialize");
|
|
605
|
-
res.writeHead(400, { "Content-Type": "application/json" });
|
|
606
|
-
res.end(JSON.stringify({
|
|
607
|
-
jsonrpc: "2.0",
|
|
608
|
-
error: {
|
|
609
|
-
code: -32e3,
|
|
610
|
-
message: "Bad Request: No valid session ID provided"
|
|
611
|
-
},
|
|
612
|
-
id: null
|
|
613
|
-
}));
|
|
614
|
-
return;
|
|
615
|
-
}
|
|
616
|
-
await transport.handleRequest(req, res, parsedBody);
|
|
617
|
-
logger.debug("[happyMCP] Request handled successfully");
|
|
618
|
-
} else if (req.method === "GET" || req.method === "DELETE") {
|
|
619
|
-
if (!sessionId || !transports.has(sessionId)) {
|
|
620
|
-
logger.debug("[happyMCP] Bad request: invalid session for GET/DELETE");
|
|
621
|
-
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
622
|
-
res.end("Invalid or missing session ID");
|
|
623
|
-
return;
|
|
624
|
-
}
|
|
625
|
-
const transport = transports.get(sessionId);
|
|
626
|
-
await transport.handleRequest(req, res);
|
|
627
|
-
logger.debug("[happyMCP] GET/DELETE request handled successfully");
|
|
628
|
-
} else {
|
|
629
|
-
res.writeHead(405, { "Content-Type": "text/plain" });
|
|
630
|
-
res.end("Method not allowed");
|
|
631
|
-
}
|
|
632
|
-
} catch (error) {
|
|
633
|
-
logger.debug("[happyMCP] Error handling request:", error);
|
|
634
|
-
if (!res.headersSent) {
|
|
635
|
-
res.writeHead(500).end();
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
});
|
|
639
|
-
const baseUrl = await new Promise((resolve) => {
|
|
640
|
-
server.listen(0, "127.0.0.1", () => {
|
|
641
|
-
const addr = server.address();
|
|
642
|
-
resolve(new URL(`http://127.0.0.1:${addr.port}`));
|
|
643
|
-
});
|
|
644
|
-
});
|
|
645
|
-
logger.debug("[happyMCP] Server started at:", baseUrl.toString());
|
|
646
|
-
return {
|
|
647
|
-
url: baseUrl.toString(),
|
|
648
|
-
toolNames,
|
|
649
|
-
stop: async () => {
|
|
650
|
-
logger.debug("[happyMCP] Stopping server");
|
|
651
|
-
for (const [sessionId, transport] of transports) {
|
|
652
|
-
logger.debug("[happyMCP] Closing transport for session:", sessionId);
|
|
653
|
-
try {
|
|
654
|
-
await transport.close();
|
|
655
|
-
} catch (error) {
|
|
656
|
-
logger.debug("[happyMCP] Error closing transport:", error);
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
transports.clear();
|
|
660
|
-
server.close();
|
|
661
|
-
}
|
|
662
|
-
};
|
|
663
|
-
}
|
|
664
|
-
function readRequestBody(req) {
|
|
665
|
-
return new Promise((resolve, reject) => {
|
|
666
|
-
let body = "";
|
|
667
|
-
req.on("data", (chunk) => body += chunk);
|
|
668
|
-
req.on("end", () => resolve(body));
|
|
669
|
-
req.on("error", reject);
|
|
670
|
-
});
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
const getBridgeCommand = () => join(projectPath(), "bin", "happy-mcp.mjs");
|
|
674
|
-
function adaptForClaude(def) {
|
|
675
|
-
return { type: "http", url: def.url, ...def.headers && { headers: def.headers } };
|
|
676
|
-
}
|
|
677
|
-
function adaptForStdio(def) {
|
|
678
|
-
const args = ["--url", def.url];
|
|
679
|
-
if (def.headers) {
|
|
680
|
-
for (const [k, v] of Object.entries(def.headers)) {
|
|
681
|
-
args.push("--header", `${k}: ${v}`);
|
|
682
|
-
}
|
|
683
|
-
}
|
|
684
|
-
return { command: getBridgeCommand(), args };
|
|
685
|
-
}
|
|
686
|
-
function adaptForHttp(def) {
|
|
687
|
-
return { type: "http", url: def.url, headers: def.headers || {} };
|
|
688
|
-
}
|
|
689
|
-
async function createMcpContext(session) {
|
|
690
|
-
const happyServer = await startHappyServer(session);
|
|
691
|
-
const servers = {
|
|
692
|
-
happy: {
|
|
693
|
-
url: happyServer.url,
|
|
694
|
-
toolNames: happyServer.toolNames,
|
|
695
|
-
stop: () => happyServer.stop()
|
|
696
|
-
}
|
|
697
|
-
};
|
|
698
|
-
const extraServersJson = process.env.HAPPY_EXTRA_MCP_SERVERS;
|
|
699
|
-
if (extraServersJson) {
|
|
700
|
-
try {
|
|
701
|
-
const extraServers = JSON.parse(extraServersJson);
|
|
702
|
-
for (const srv of extraServers) {
|
|
703
|
-
servers[srv.name] = {
|
|
704
|
-
url: srv.url,
|
|
705
|
-
toolNames: [],
|
|
706
|
-
// External MCP — tools discovered by agent, not whitelisted
|
|
707
|
-
headers: srv.headers,
|
|
708
|
-
stop: () => {
|
|
709
|
-
}
|
|
710
|
-
// No lifecycle management for external servers
|
|
711
|
-
};
|
|
712
|
-
}
|
|
713
|
-
} catch (e) {
|
|
714
|
-
console.warn("Failed to parse HAPPY_EXTRA_MCP_SERVERS:", e);
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
return {
|
|
718
|
-
configForClaude() {
|
|
719
|
-
const result = {};
|
|
720
|
-
for (const [name, def] of Object.entries(servers)) {
|
|
721
|
-
result[name] = adaptForClaude(def);
|
|
722
|
-
}
|
|
723
|
-
return result;
|
|
724
|
-
},
|
|
725
|
-
configForStdio() {
|
|
726
|
-
const result = {};
|
|
727
|
-
for (const [name, def] of Object.entries(servers)) {
|
|
728
|
-
result[name] = adaptForStdio(def);
|
|
729
|
-
}
|
|
730
|
-
return result;
|
|
731
|
-
},
|
|
732
|
-
configForHttp() {
|
|
733
|
-
const result = {};
|
|
734
|
-
for (const [name, def] of Object.entries(servers)) {
|
|
735
|
-
result[name] = adaptForHttp(def);
|
|
736
|
-
}
|
|
737
|
-
return result;
|
|
738
|
-
},
|
|
739
|
-
allowedToolNames() {
|
|
740
|
-
return Object.entries(servers).flatMap(
|
|
741
|
-
([name, def]) => def.toolNames.map((tool) => `mcp__${name}__${tool}`)
|
|
742
|
-
);
|
|
743
|
-
},
|
|
744
|
-
normalizeToolName(rawName) {
|
|
745
|
-
for (const [name, def] of Object.entries(servers)) {
|
|
746
|
-
if (def.toolNames.includes(rawName)) {
|
|
747
|
-
return `mcp:${name}:${rawName}`;
|
|
748
|
-
}
|
|
749
|
-
}
|
|
750
|
-
return rawName;
|
|
751
|
-
},
|
|
752
|
-
stop() {
|
|
753
|
-
for (const def of Object.values(servers)) {
|
|
754
|
-
def.stop();
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
};
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
class MessageBuffer {
|
|
761
|
-
messages = [];
|
|
762
|
-
listeners = [];
|
|
763
|
-
nextId = 1;
|
|
764
|
-
addMessage(content, type = "assistant") {
|
|
765
|
-
const message = {
|
|
766
|
-
id: `msg-${this.nextId++}`,
|
|
767
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
768
|
-
content,
|
|
769
|
-
type
|
|
770
|
-
};
|
|
771
|
-
this.messages.push(message);
|
|
772
|
-
this.notifyListeners();
|
|
773
|
-
}
|
|
774
|
-
/**
|
|
775
|
-
* Update the last message of a specific type by appending content to it
|
|
776
|
-
* Useful for streaming responses where deltas should accumulate in one message
|
|
777
|
-
*/
|
|
778
|
-
updateLastMessage(contentDelta, type = "assistant") {
|
|
779
|
-
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
780
|
-
if (this.messages[i].type === type) {
|
|
781
|
-
const oldMessage = this.messages[i];
|
|
782
|
-
const updatedMessage = {
|
|
783
|
-
...oldMessage,
|
|
784
|
-
content: oldMessage.content + contentDelta
|
|
785
|
-
};
|
|
786
|
-
this.messages[i] = updatedMessage;
|
|
787
|
-
this.notifyListeners();
|
|
788
|
-
return;
|
|
789
|
-
}
|
|
790
|
-
}
|
|
791
|
-
this.addMessage(contentDelta, type);
|
|
792
|
-
}
|
|
793
|
-
/**
|
|
794
|
-
* Remove the last message of a specific type
|
|
795
|
-
* Useful for removing placeholder messages like "Thinking..." when actual response starts
|
|
796
|
-
*/
|
|
797
|
-
removeLastMessage(type) {
|
|
798
|
-
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
799
|
-
if (this.messages[i].type === type) {
|
|
800
|
-
this.messages.splice(i, 1);
|
|
801
|
-
this.notifyListeners();
|
|
802
|
-
return true;
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
return false;
|
|
806
|
-
}
|
|
807
|
-
getMessages() {
|
|
808
|
-
return [...this.messages];
|
|
809
|
-
}
|
|
810
|
-
clear() {
|
|
811
|
-
this.messages = [];
|
|
812
|
-
this.nextId = 1;
|
|
813
|
-
this.notifyListeners();
|
|
814
|
-
}
|
|
815
|
-
onUpdate(listener) {
|
|
816
|
-
this.listeners.push(listener);
|
|
817
|
-
return () => {
|
|
818
|
-
const index = this.listeners.indexOf(listener);
|
|
819
|
-
if (index > -1) {
|
|
820
|
-
this.listeners.splice(index, 1);
|
|
821
|
-
}
|
|
822
|
-
};
|
|
823
|
-
}
|
|
824
|
-
notifyListeners() {
|
|
825
|
-
const messages = this.getMessages();
|
|
826
|
-
this.listeners.forEach((listener) => listener(messages));
|
|
827
|
-
}
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
function registerKillSessionHandler(rpcHandlerManager, killThisHappy) {
|
|
831
|
-
rpcHandlerManager.registerHandler("killSession", async () => {
|
|
832
|
-
logger.debug("Kill session request received");
|
|
833
|
-
void killThisHappy();
|
|
834
|
-
return {
|
|
835
|
-
success: true,
|
|
836
|
-
message: "Killing happy-cli process"
|
|
837
|
-
};
|
|
838
|
-
});
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
async function downloadImage(url) {
|
|
842
|
-
const response = await axios.get(url, {
|
|
843
|
-
responseType: "arraybuffer"
|
|
844
|
-
});
|
|
845
|
-
const buffer = Buffer.from(response.data);
|
|
846
|
-
const base64 = buffer.toString("base64");
|
|
847
|
-
let mimeType = response.headers["content-type"] || "image/jpeg";
|
|
848
|
-
if (mimeType.includes(";")) {
|
|
849
|
-
mimeType = mimeType.split(";")[0].trim();
|
|
850
|
-
}
|
|
851
|
-
return { base64, mimeType };
|
|
852
|
-
}
|
|
853
|
-
|
|
854
|
-
export { MessageQueue2 as M, MessageBuffer as a, parseSpecialCommand as b, createMcpContext as c, downloadImage as d, hashObject as h, parseClear as p, registerKillSessionHandler as r };
|