-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared.js
More file actions
421 lines (370 loc) · 15.3 KB
/
Copy pathshared.js
File metadata and controls
421 lines (370 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
(function(){
function hasAnyMethod(bridge, names) {
if (!bridge) return false;
return names.some(function (name) { return typeof bridge[name] === 'function'; });
}
function isInferenceBridge(bridge) {
return hasAnyMethod(bridge, ['chatCompletion', 'generate']);
}
function isFileBridge(bridge) {
return hasAnyMethod(bridge, ['selectFolder', 'triggerSelectFolder', 'readFile', 'triggerReadFile', 'writeFile', 'triggerWriteFile']);
}
var bridge=window.SignalLMNativeBridge||window.lmStudioLiteNative||window.NativeFileBridge||window.NativeInferenceBridge||window.AndroidBridge||window.AndroidFileBridge||window.AndroidWorkspaceBridge||window.AndroidInferenceBridge||null;
if(!bridge)return;
if(!window.lmStudioLiteNative)window.lmStudioLiteNative=bridge;
if(!window.NativeFileBridge&&isFileBridge(bridge))window.NativeFileBridge=bridge;
if(!window.NativeInferenceBridge&&isInferenceBridge(bridge))window.NativeInferenceBridge=bridge;
if(!window.AndroidBridge)window.AndroidBridge=bridge;
})();
(function () {
if (window.__signalLmThemeLoader) return;
window.__signalLmThemeLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-theme.js?v=2';
script.defer = false;
script.onerror = function () { console.warn('Signal-LM theme helper was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmMcpDarkCssLoader) return;
window.__signalLmMcpDarkCssLoader = true;
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'signal-lm-mcp-dark.css?v=5';
link.onerror = function () { console.warn('Signal-LM MCP dark stylesheet was not found.'); };
document.head.appendChild(link);
})();
// Viewport Height Listener
(function () {
function updateAppViewportHeight() {
const viewport = window.visualViewport;
const height = viewport && viewport.height ? viewport.height : window.innerHeight;
if (height) document.documentElement.style.setProperty('--app-height', height + 'px');
}
updateAppViewportHeight();
window.addEventListener('resize', updateAppViewportHeight, { passive: true });
window.addEventListener('orientationchange', function () { setTimeout(updateAppViewportHeight, 80); }, { passive: true });
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', updateAppViewportHeight, { passive: true });
window.visualViewport.addEventListener('scroll', updateAppViewportHeight, { passive: true });
}
})();
(function () {
if (window.__lmStudioLiteNativeFetchPatch) return;
window.__lmStudioLiteNativeFetchPatch = true;
const SETTINGS_KEY = 'lmStudioLite.settings.v1';
const originalFetch = window.fetch ? window.fetch.bind(window) : null;
const LM_STUDIO_CHAT_FORBIDDEN_KEYS = new Set([
'response_id',
'previous_response_id',
'conversation',
'conversation_id',
'thread_id',
'session_id'
]);
function createAbortError() {
try {
return new DOMException('The request was stopped.', 'AbortError');
} catch {
const error = new Error('The request was stopped.');
error.name = 'AbortError';
return error;
}
}
function throwIfAborted(signal) {
if (signal && signal.aborted) throw createAbortError();
}
function nativeRequestId() {
return 'req_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2);
}
function cancelBridgeRequest(bridge, requestId) {
try {
if (bridge && typeof bridge.cancelHttpRequest === 'function') bridge.cancelHttpRequest(requestId);
else if (bridge && typeof bridge.cancelGeneration === 'function') bridge.cancelGeneration();
} catch {}
}
function getBridge() {
return window.SignalLMNativeBridge || window.lmStudioLiteNative || window.NativeFileBridge || window.AndroidBridge || window.AndroidFileBridge || window.AndroidWorkspaceBridge || null;
}
function readSettings() {
try {
return JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}') || {};
} catch {
return {};
}
}
function nativeHttpBridgeEnabled() {
const settings = readSettings();
const mode = settings.runtimeMode || 'server';
return mode === 'server' || mode === 'hybrid';
}
function bridgeCanRequest(url) {
const bridge = getBridge();
return Boolean(nativeHttpBridgeEnabled() && bridge && /^https?:\/\//i.test(String(url || '')) && (bridge.httpRequest || bridge.request || bridge.fetchJson));
}
function isLmStudioChatRequest(url) {
const clean = String(url || '').split('?')[0].replace(/\/+$/, '');
return /\/(?:v\d+\/chat\/completions|api\/v\d+\/chat(?:\/completions)?)$/i.test(clean);
}
function sanitizeLmStudioRequestBody(url, body) {
if (!isLmStudioChatRequest(url) || typeof body !== 'string') return body;
const trimmed = body.trim();
if (!trimmed || trimmed[0] !== '{') return body;
try {
const parsed = JSON.parse(trimmed);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return body;
let changed = false;
LM_STUDIO_CHAT_FORBIDDEN_KEYS.forEach(key => {
if (Object.prototype.hasOwnProperty.call(parsed, key)) {
delete parsed[key];
changed = true;
}
});
return changed ? JSON.stringify(parsed) : body;
} catch {
return body;
}
}
function mergeHeaders(inputHeaders, initHeaders) {
const headers = {};
const add = source => {
if (!source) return;
if (typeof Headers !== 'undefined' && source instanceof Headers) {
source.forEach((value, key) => { headers[key] = value; });
} else if (Array.isArray(source)) {
source.forEach(pair => { if (pair && pair.length >= 2) headers[pair[0]] = pair[1]; });
} else if (typeof source === 'object') {
Object.keys(source).forEach(key => { headers[key] = source[key]; });
}
};
add(inputHeaders);
add(initHeaders);
return headers;
}
function callTriggerHttpRequest(bridge, payload, signal) {
const requestId = payload.requestId || nativeRequestId();
payload.requestId = requestId;
payload._requestId = requestId;
return new Promise((resolve, reject) => {
let settled = false;
let abortHandler = null;
const resolveName = '__httpResolve_' + requestId;
const rejectName = '__httpReject_' + requestId;
const cleanup = () => {
delete window[resolveName];
delete window[rejectName];
if (signal && abortHandler) signal.removeEventListener('abort', abortHandler);
};
const finish = (fn, value) => {
if (settled) return;
settled = true;
cleanup();
fn(value);
};
abortHandler = () => {
cancelBridgeRequest(bridge, requestId);
finish(reject, createAbortError());
};
if (signal && signal.aborted) {
abortHandler();
return;
}
window[resolveName] = result => finish(resolve, result);
window[rejectName] = message => finish(reject, new Error(message || 'Native HTTP bridge failed.'));
if (signal) signal.addEventListener('abort', abortHandler, { once: true });
try {
bridge.triggerHttpRequest(JSON.stringify(payload), requestId);
} catch (error) {
finish(reject, error);
}
});
}
async function callBridgeHttpMethod(bridge, payload, signal) {
throwIfAborted(signal);
const requestId = payload.requestId;
let abortHandler = null;
const request = Promise.resolve().then(() => {
const json = JSON.stringify(payload);
if (bridge.httpRequest) return bridge.httpRequest(json);
if (bridge.request) return bridge.request(json);
return bridge.fetchJson(json);
});
if (!signal) return await request;
const abort = new Promise((_, reject) => {
abortHandler = () => {
cancelBridgeRequest(bridge, requestId);
reject(createAbortError());
};
signal.addEventListener('abort', abortHandler, { once: true });
});
try {
return await Promise.race([request, abort]);
} finally {
if (abortHandler) signal.removeEventListener('abort', abortHandler);
}
}
async function callNativeHttpBridge(bridge, payload, signal) {
throwIfAborted(signal);
if (bridge && typeof bridge.triggerHttpRequest === 'function') {
return await callTriggerHttpRequest(bridge, payload, signal);
}
return await callBridgeHttpMethod(bridge, payload, signal);
}
async function nativeFetch(input, init) {
const options = init || {};
const url = typeof input === 'string' ? input : (input && input.url) || String(input || '');
const method = options.method || (input && input.method) || 'GET';
const headers = mergeHeaders(input && input.headers, options.headers);
const signal = options.signal || (input && input.signal) || null;
let body = options.body || null;
if (body && typeof body !== 'string') body = String(body);
body = sanitizeLmStudioRequestBody(url, body);
const requestId = nativeRequestId();
const payload = { url, method, headers, body, requestId, _requestId: requestId };
const bridge = getBridge();
const raw = await callNativeHttpBridge(bridge, payload, signal);
throwIfAborted(signal);
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (!parsed || typeof parsed !== 'object') throw new Error('Native HTTP bridge returned an empty response.');
if (parsed.error) {
if (/aborted|cancelled|canceled|stopped/i.test(parsed.error)) throw createAbortError();
throw new Error(parsed.error);
}
const responseHeaders = new Headers(parsed.headers || {});
if (!responseHeaders.has('content-type')) responseHeaders.set('content-type', parsed.contentType || 'application/json');
return new Response(parsed.body || '', {
status: parsed.status || 200,
statusText: parsed.statusText || 'OK',
headers: responseHeaders
});
}
if (originalFetch) {
window.fetch = function (input, init) {
const url = typeof input === 'string' ? input : (input && input.url) || String(input || '');
let nextInit = init;
if (nextInit && typeof nextInit.body === 'string' && isLmStudioChatRequest(url)) {
const cleanBody = sanitizeLmStudioRequestBody(url, nextInit.body);
if (cleanBody !== nextInit.body) nextInit = { ...nextInit, body: cleanBody };
}
if (bridgeCanRequest(url)) return nativeFetch(input, nextInit);
return originalFetch(input, nextInit);
};
}
})();
(function () {
if (window.__signalLmRuntimePatchLoader) return;
window.__signalLmRuntimePatchLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-runtime-fix.js';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM runtime restore patch was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmModelLoaderFixLoader) return;
window.__signalLmModelLoaderFixLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-model-loader-fix.js?v=3';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM model loader fix was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmWebSearchLoader) return;
window.__signalLmWebSearchLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-web-search.js?v=4';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM web search helper was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmMcpPipelineLoader) return;
window.__signalLmMcpPipelineLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-mcp-pipeline.js?v=2';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM MCP pipeline helper was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmMcpFilePathLoader) return;
window.__signalLmMcpFilePathLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-mcp-file-path.js?v=10';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM MCP file path helper was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmJsonEditEnforcerLoader) return;
window.__signalLmJsonEditEnforcerLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-json-edit-enforcer.js?v=write-create-2';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM JSON edit enforcer was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmWriteCommandFixLoader) return;
window.__signalLmWriteCommandFixLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-write-command-fix.js?v=3';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM write command fix was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmMcpWriteFileFixLoader) return;
window.__signalLmMcpWriteFileFixLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-mcp-write-file-fix.js?v=3';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM MCP write_file schema guard was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmMcpApplyFixLoader) return;
window.__signalLmMcpApplyFixLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-mcp-apply-fix.js?v=1';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM MCP staged apply helper was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmChatbotSafetyFixLoader) return;
window.__signalLmChatbotSafetyFixLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-chatbot-safety-fix.js?v=2';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM chatbot safety guard was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmPcFileAccessFixLoader) return;
window.__signalLmPcFileAccessFixLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-pc-file-access-fix.js?v=2';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM PC file access guard was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmNativeFallbackLabelLoader) return;
window.__signalLmNativeFallbackLabelLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-native-fallback-label.js?v=1';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM native fallback label helper was not found.'); };
document.head.appendChild(script);
})();
(function () {
if (window.__signalLmMcpChatBridgeLoader) return;
window.__signalLmMcpChatBridgeLoader = true;
var script = document.createElement('script');
script.src = 'signal-lm-mcp-chat-bridge.js?v=content-uri-1';
script.defer = true;
script.onerror = function () { console.warn('Signal-LM MCP chat bridge was not found.'); };
document.head.appendChild(script);
})();