tabby-ai-tools 0.9.4 → 1.1.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.
@@ -0,0 +1,801 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // runtime/mcp/electron-host.cts
21
+ var electron_host_exports = {};
22
+ __export(electron_host_exports, {
23
+ install: () => install
24
+ });
25
+ module.exports = __toCommonJS(electron_host_exports);
26
+ var import_node_fs3 = require("node:fs");
27
+ var import_node_path3 = require("node:path");
28
+ var import_node_url = require("node:url");
29
+
30
+ // runtime/mcp/policy.cts
31
+ var import_node_crypto = require("node:crypto");
32
+ var import_node_fs = require("node:fs");
33
+ var import_node_path = require("node:path");
34
+ var failure = (code) => Object.assign(new Error(code), { code });
35
+ var randomId = () => (0, import_node_crypto.randomBytes)(24).toString("base64url");
36
+ var tokenDigest = (value) => (0, import_node_crypto.createHash)("sha256").update(value).digest("hex");
37
+ var LOCAL_CLIENT_ID = "local";
38
+ var McpPolicy = class {
39
+ enabled = false;
40
+ port = 0;
41
+ clients = /* @__PURE__ */ new Map();
42
+ targets = /* @__PURE__ */ new Map();
43
+ file;
44
+ constructor(directory) {
45
+ this.clients.set(LOCAL_CLIENT_ID, { id: LOCAL_CLIENT_ID, name: "Local connection (no token)", digest: "", revision: 1, mode: "auto", targets: /* @__PURE__ */ new Set() });
46
+ (0, import_node_fs.mkdirSync)(directory, { recursive: true, mode: 448 });
47
+ if ((0, import_node_fs.lstatSync)(directory).isSymbolicLink()) throw new Error("MCP state directory must not be a symlink");
48
+ if (process.platform !== "win32") (0, import_node_fs.chmodSync)(directory, 448);
49
+ this.file = (0, import_node_path.join)(directory, "state.json");
50
+ try {
51
+ if ((0, import_node_fs.lstatSync)(this.file).isSymbolicLink()) throw new Error("MCP state must not be a symlink");
52
+ if ((0, import_node_fs.lstatSync)(this.file).size > 128 * 1024) throw new Error("MCP state exceeds size limit");
53
+ if (process.platform !== "win32") (0, import_node_fs.chmodSync)(this.file, 384);
54
+ const data = JSON.parse((0, import_node_fs.readFileSync)(this.file, "utf8"));
55
+ if (data.version !== 1 || !Array.isArray(data.clients) || data.clients.length > 32 || !Number.isInteger(data.port) || data.port < 0 || data.port > 65535) throw new Error("Invalid MCP state");
56
+ this.enabled = data.enabled === true;
57
+ this.port = data.port;
58
+ for (const item of data.clients) {
59
+ if (typeof item.id !== "string" || item.id === LOCAL_CLIENT_ID || !/^[a-f0-9]{64}$/.test(item.digest) || typeof item.name !== "string" || !item.name.trim() || item.name.length > 80 || !Number.isSafeInteger(item.revision) || item.revision < 1) throw new Error("Invalid MCP client state");
60
+ this.clients.set(item.id, { ...item, targets: /* @__PURE__ */ new Set(), mode: "read_only", revision: item.revision + 1, lastSeen: void 0 });
61
+ }
62
+ } catch (error) {
63
+ if (error.code !== "ENOENT") throw error;
64
+ }
65
+ }
66
+ save() {
67
+ const temporary = this.file + "." + randomId() + ".tmp";
68
+ const data = { version: 1, enabled: this.enabled, port: this.port, clients: [...this.clients.values()].filter((c) => c.id !== LOCAL_CLIENT_ID).map(({ id, name, digest, revision }) => ({ id, name, digest, revision })) };
69
+ try {
70
+ (0, import_node_fs.writeFileSync)(temporary, JSON.stringify(data) + "\n", { mode: 384, flag: "wx" });
71
+ (0, import_node_fs.renameSync)(temporary, this.file);
72
+ } finally {
73
+ (0, import_node_fs.rmSync)(temporary, { force: true });
74
+ }
75
+ }
76
+ add(name) {
77
+ if (typeof name !== "string" || !name.trim() || name.trim().length > 80) throw new Error("Client name must contain 1\u201380 characters");
78
+ if (this.clients.size >= 33) throw new Error("At most 32 MCP clients are allowed");
79
+ const id = randomId(), token = (0, import_node_crypto.randomBytes)(32).toString("base64url");
80
+ this.clients.set(id, { id, name: name.trim(), digest: tokenDigest(token), revision: 1, mode: "read_only", targets: /* @__PURE__ */ new Set() });
81
+ return { id, token };
82
+ }
83
+ rotate(id) {
84
+ if (id === LOCAL_CLIENT_ID) throw new Error("The local connection does not use a token");
85
+ const client = this.client(id), token = (0, import_node_crypto.randomBytes)(32).toString("base64url");
86
+ client.digest = tokenDigest(token);
87
+ client.revision++;
88
+ client.lastSeen = void 0;
89
+ return { id, token };
90
+ }
91
+ client(id) {
92
+ const client = this.clients.get(id);
93
+ if (!client) throw failure("permission_denied");
94
+ return client;
95
+ }
96
+ setScope(id, targetIds) {
97
+ if (id === LOCAL_CLIENT_ID) throw failure("permission_denied");
98
+ if (!Array.isArray(targetIds) || targetIds.length > 256 || targetIds.some((id2) => typeof id2 !== "string" || !this.targets.has(id2))) throw failure("target_stale");
99
+ const client = this.client(id);
100
+ client.targets = new Set(targetIds);
101
+ client.revision++;
102
+ }
103
+ setMode(id, mode) {
104
+ if (id === LOCAL_CLIENT_ID) throw failure("permission_denied");
105
+ if (!["read_only", "confirm", "auto"].includes(mode)) throw failure("permission_denied");
106
+ const client = this.client(id);
107
+ client.mode = mode;
108
+ client.revision++;
109
+ }
110
+ removeTarget(id) {
111
+ this.targets.delete(id);
112
+ for (const client of this.clients.values()) if (client.targets.delete(id) && client.id !== LOCAL_CLIENT_ID) client.revision++;
113
+ }
114
+ register(owner, entries) {
115
+ if (!Array.isArray(entries) || entries.length > 256 || entries.some((t) => !t || typeof t.key !== "string" || t.key.length > 128 || typeof t.session !== "string" || t.session.length > 128 || typeof t.title !== "string" || t.title.length > 200)) throw new Error("Invalid terminal registration");
116
+ if (new Set(entries.map((t) => t.key)).size !== entries.length) throw new Error("Duplicate terminal key");
117
+ for (const target of [...this.targets.values()]) if (target.owner === owner && !entries.some((e) => e.key === target.key && e.session === target.session)) this.removeTarget(target.id);
118
+ for (const entry of entries) {
119
+ const current = [...this.targets.values()].find((t) => t.owner === owner && t.key === entry.key && t.session === entry.session);
120
+ if (current) current.title = entry.title;
121
+ else {
122
+ const id = randomId();
123
+ this.targets.set(id, { ...entry, id, owner });
124
+ this.client(LOCAL_CLIENT_ID).targets.add(id);
125
+ }
126
+ }
127
+ }
128
+ removeOwner(owner) {
129
+ for (const target of [...this.targets.values()]) if (target.owner === owner) this.removeTarget(target.id);
130
+ }
131
+ authorize(id, revision, targetId) {
132
+ const client = this.client(id);
133
+ if (!this.enabled || client.revision !== revision) throw failure("permission_denied");
134
+ if (targetId && (!client.targets.has(targetId) || !this.targets.has(targetId))) throw failure("permission_denied");
135
+ return client;
136
+ }
137
+ snapshot() {
138
+ return { enabled: this.enabled, clients: [...this.clients.values()].map((c) => ({ id: c.id, digest: c.digest, revision: c.revision, mode: c.mode })) };
139
+ }
140
+ publicState() {
141
+ const view = (c) => ({ id: c.id, name: c.name, mode: c.mode, revision: c.revision, targets: [...c.targets], lastSeen: c.lastSeen });
142
+ return { enabled: this.enabled, localClient: view(this.client(LOCAL_CLIENT_ID)), clients: [...this.clients.values()].filter((c) => c.id !== LOCAL_CLIENT_ID).map(view), targets: [...this.targets.values()].map((t) => ({ id: t.id, title: t.title, window: t.owner })) };
143
+ }
144
+ };
145
+
146
+ // runtime/mcp/discovery.cts
147
+ var import_node_crypto2 = require("node:crypto");
148
+ var import_node_path2 = require("node:path");
149
+ var import_node_fs2 = require("node:fs");
150
+ var McpDiscovery = class {
151
+ constructor(home, configSpace, skillSource, version) {
152
+ this.home = home;
153
+ this.skillSource = skillSource;
154
+ this.version = version;
155
+ this.registry = (0, import_node_path2.join)(home, ".agents", "tabby", "mcp");
156
+ this.profile = (0, import_node_crypto2.createHash)("sha256").update(configSpace).digest("hex").slice(0, 24);
157
+ }
158
+ home;
159
+ skillSource;
160
+ version;
161
+ registry;
162
+ profile;
163
+ last = "";
164
+ connectionInstructions() {
165
+ return (0, import_node_fs2.readFileSync)((0, import_node_path2.join)(this.skillSource, "references/connection.md"), "utf8");
166
+ }
167
+ directory(path) {
168
+ (0, import_node_fs2.mkdirSync)(path, { recursive: true, mode: 448 });
169
+ if ((0, import_node_fs2.lstatSync)(path).isSymbolicLink() || !(0, import_node_fs2.lstatSync)(path).isDirectory()) throw new Error("Discovery directory is not a regular directory");
170
+ }
171
+ installSkill() {
172
+ const roots = [(0, import_node_path2.join)(this.home, ".agents", "skills")];
173
+ for (const client of [".claude"]) if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(this.home, client))) roots.push((0, import_node_path2.join)(this.home, client, "skills"));
174
+ const files = {
175
+ "SKILL.md": (0, import_node_fs2.readFileSync)((0, import_node_path2.join)(this.skillSource, "SKILL.md"), "utf8"),
176
+ "references/connection.md": (0, import_node_fs2.readFileSync)((0, import_node_path2.join)(this.skillSource, "references/connection.md"), "utf8"),
177
+ "references/local-discovery.json": JSON.stringify({ format: "tabby-mcp-locator-v1", registry: this.registry, credentialsIncluded: false }, null, 2) + "\n"
178
+ };
179
+ return roots.map((root) => {
180
+ const destination = (0, import_node_path2.join)(root, "tabby-mcp"), created = [];
181
+ let own = false;
182
+ try {
183
+ this.directory(root);
184
+ if ((0, import_node_fs2.existsSync)(destination) || (() => {
185
+ try {
186
+ (0, import_node_fs2.lstatSync)(destination);
187
+ return true;
188
+ } catch {
189
+ return false;
190
+ }
191
+ })()) {
192
+ const plain = (0, import_node_fs2.lstatSync)(destination).isDirectory() && !(0, import_node_fs2.lstatSync)(destination).isSymbolicLink();
193
+ const matching = plain && (0, import_node_fs2.existsSync)((0, import_node_path2.join)(destination, "references")) && !(0, import_node_fs2.lstatSync)((0, import_node_path2.join)(destination, "references")).isSymbolicLink() && Object.entries(files).every(([file, text]) => {
194
+ try {
195
+ const path = (0, import_node_path2.join)(destination, file);
196
+ return !(0, import_node_fs2.lstatSync)(path).isSymbolicLink() && (0, import_node_fs2.readFileSync)(path, "utf8") === text;
197
+ } catch {
198
+ return false;
199
+ }
200
+ });
201
+ return { path: destination, status: matching ? "present" : "conflict" };
202
+ }
203
+ (0, import_node_fs2.mkdirSync)(destination, { mode: 448 });
204
+ own = true;
205
+ (0, import_node_fs2.mkdirSync)((0, import_node_path2.join)(destination, "references"), { mode: 448 });
206
+ for (const file of ["references/connection.md", "references/local-discovery.json", "SKILL.md"]) {
207
+ const path = (0, import_node_path2.join)(destination, file);
208
+ (0, import_node_fs2.writeFileSync)(path, files[file], { mode: 384, flag: "wx" });
209
+ created.push(file);
210
+ }
211
+ return { path: destination, status: "installed" };
212
+ } catch {
213
+ if (own) for (const file of created) {
214
+ const path = (0, import_node_path2.join)(destination, file);
215
+ try {
216
+ if (!(0, import_node_fs2.lstatSync)(path).isSymbolicLink() && (0, import_node_fs2.readFileSync)(path, "utf8") === files[file]) (0, import_node_fs2.rmSync)(path);
217
+ } catch {
218
+ }
219
+ }
220
+ if (own) {
221
+ try {
222
+ (0, import_node_fs2.rmdirSync)((0, import_node_path2.join)(destination, "references"));
223
+ } catch {
224
+ }
225
+ ;
226
+ try {
227
+ (0, import_node_fs2.rmdirSync)(destination);
228
+ } catch {
229
+ }
230
+ }
231
+ return { path: destination, status: "error" };
232
+ }
233
+ });
234
+ }
235
+ update(state) {
236
+ const status = state.running ? "running" : state.enabled ? "unavailable" : "disabled";
237
+ const payload = { format: "tabby-mcp-discovery-v1", profile: this.profile, application: "Tabby AI Tools", version: this.version, status, endpoint: state.running ? state.endpoint : "", authentication: "local_no_token", credentialsIncluded: false, setup: "Tabby > Settings > AI Tools > External AI connections (MCP)", skill: "tabby-mcp" };
238
+ if (payload.endpoint && !/^http:\/\/127\.0\.0\.1:\d+\/mcp$/.test(payload.endpoint)) throw new Error("Invalid discovery endpoint");
239
+ const value = JSON.stringify(payload);
240
+ if (this.last === value && (0, import_node_fs2.existsSync)((0, import_node_path2.join)(this.registry, this.profile + ".json"))) return;
241
+ this.directory(this.registry);
242
+ const target = (0, import_node_path2.join)(this.registry, this.profile + ".json"), temporary = target + "." + randomId() + ".tmp";
243
+ try {
244
+ if ((0, import_node_fs2.existsSync)(target) && (0, import_node_fs2.lstatSync)(target).isSymbolicLink()) throw new Error("Discovery record must not be a symlink");
245
+ (0, import_node_fs2.writeFileSync)(temporary, JSON.stringify({ ...payload, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2) + "\n", { mode: 384, flag: "wx" });
246
+ (0, import_node_fs2.renameSync)(temporary, target);
247
+ this.last = value;
248
+ } finally {
249
+ (0, import_node_fs2.rmSync)(temporary, { force: true });
250
+ }
251
+ }
252
+ };
253
+
254
+ // runtime/mcp/electron-host.cts
255
+ var { app, ipcMain, utilityProcess } = require("electron");
256
+ var CHANNEL = "tabby-ai-mcp-v1";
257
+ var singleton = /* @__PURE__ */ Symbol.for("tabby-ai.mcp.host.v1");
258
+ function install() {
259
+ const globalState = globalThis;
260
+ if (globalState[singleton]) return;
261
+ if (!app.isReady() || typeof utilityProcess?.fork !== "function" || Number(process.versions.node.split(".")[0]) < 20) throw new Error("MCP requires a Tabby host with Node 20+ and utilityProcess support");
262
+ const configSpace = (0, import_node_fs3.realpathSync)(process.env.TABBY_CONFIG_DIRECTORY || app.getPath("userData"));
263
+ const discovery = new McpDiscovery(app.getPath("home"), configSpace, (0, import_node_path3.join)(__dirname, "../../skills/tabby-mcp"), "1.1.0");
264
+ let skillInstallations = [], discoveryError = "";
265
+ const installSkill = () => {
266
+ try {
267
+ skillInstallations = discovery.installSkill();
268
+ discoveryError = "";
269
+ } catch {
270
+ discoveryError = "Agent skill could not be installed; the bundled skill can be copied manually.";
271
+ }
272
+ };
273
+ installSkill();
274
+ const policy = new McpPolicy((0, import_node_path3.join)(configSpace, "ai-tools-mcp"));
275
+ const expectedUrl = (0, import_node_url.pathToFileURL)((0, import_node_path3.join)(app.getAppPath(), "dist/index.html")).href;
276
+ const owners = /* @__PURE__ */ new Map();
277
+ const controls = /* @__PURE__ */ new Map();
278
+ const leases = /* @__PURE__ */ new Map();
279
+ const observations = /* @__PURE__ */ new Map();
280
+ const exits = /* @__PURE__ */ new WeakMap(), exitedChildren = /* @__PURE__ */ new WeakSet();
281
+ let child, faulted, port = 0, error = "", utilityNode = "", chain = Promise.resolve(), stopping;
282
+ const trusted = (event) => {
283
+ try {
284
+ return !event.sender.isDestroyed() && event.senderFrame === event.sender.mainFrame && event.sender.getURL() === expectedUrl;
285
+ } catch {
286
+ return false;
287
+ }
288
+ };
289
+ const enqueue = (action) => {
290
+ const next = chain.then(action);
291
+ chain = next.then(() => void 0, () => void 0);
292
+ return next;
293
+ };
294
+ const state = () => ({ ...policy.publicState(), discovery: { registry: discovery.registry, source: discovery.skillSource, skillInstallations, error: discoveryError }, approvals: [...observations].filter(([, o]) => o.approval).map(([id, o]) => ({ id, ...o.approval, target: o.target, window: o.sender.id })), leases: [...leases.values()].map((l) => ({ id: l.id, client: policy.clients.get(l.clientId)?.name || "", target: l.targetId, title: policy.targets.get(l.targetId)?.title || "", window: l.sender.id, expiresAt: l.expiresAt })), running: !!child && !faulted && !!port, port: policy.port, endpoint: port ? `http://127.0.0.1:${port}/mcp` : "", error, hostNode: process.versions.node, utilityNode });
295
+ const releaseLease = (id) => {
296
+ const lease = leases.get(id);
297
+ if (!lease) return;
298
+ leases.delete(id);
299
+ clearTimeout(lease.timer);
300
+ sendRenderer(lease.sender, { type: "release", leaseId: id });
301
+ };
302
+ const touchLease = (id) => {
303
+ const lease = leases.get(id);
304
+ if (!lease) return;
305
+ clearTimeout(lease.timer);
306
+ lease.expiresAt = Date.now() + 12e4;
307
+ lease.timer = setTimeout(() => {
308
+ releaseLease(id);
309
+ for (const [key, item] of observations) if (item.leaseId === id) cancelObservation(key, "lease_expired");
310
+ synchronize();
311
+ }, 12e4);
312
+ lease.timer.unref?.();
313
+ };
314
+ const clearScopes = () => {
315
+ for (const id of leases.keys()) releaseLease(id);
316
+ for (const client of policy.clients.values()) {
317
+ if (client.id !== LOCAL_CLIENT_ID) client.targets.clear();
318
+ client.revision++;
319
+ }
320
+ };
321
+ const rejectControls = (reason = "MCP process unavailable") => {
322
+ for (const waiter of controls.values()) {
323
+ clearTimeout(waiter.timer);
324
+ waiter.reject(new Error(reason));
325
+ }
326
+ controls.clear();
327
+ };
328
+ const cancelObservation = (id, code, notify = true) => {
329
+ const item = observations.get(id);
330
+ if (!item) return;
331
+ observations.delete(id);
332
+ clearTimeout(item.timer);
333
+ item.reject(failure(item.sent && item.leaseId ? "unknown_outcome" : code));
334
+ if (item.leaseId) releaseLease(item.leaseId);
335
+ if (notify) sendRenderer(item.sender, { type: "cancel", id });
336
+ };
337
+ const dropOwner = (id) => {
338
+ const owner = owners.get(id);
339
+ if (!owner) return;
340
+ owner.cleanup();
341
+ owners.delete(id);
342
+ policy.removeOwner(id);
343
+ for (const [key, lease] of leases) if (lease.sender === owner.sender) {
344
+ leases.delete(key);
345
+ clearTimeout(lease.timer);
346
+ }
347
+ for (const [key, item] of observations) if (item.sender === owner.sender) cancelObservation(key, "target_closed", false);
348
+ };
349
+ const sendRenderer = (sender, message) => {
350
+ try {
351
+ if (sender.isDestroyed()) throw new Error("Renderer unavailable");
352
+ sender.send(CHANNEL, message);
353
+ return true;
354
+ } catch {
355
+ if (owners.has(sender.id)) {
356
+ dropOwner(sender.id);
357
+ void enqueue(async () => {
358
+ synchronize();
359
+ if (!owners.size) await stop();
360
+ }).catch(() => void 0);
361
+ }
362
+ return false;
363
+ }
364
+ };
365
+ const faultChild = (own, message) => {
366
+ if (child !== own || faulted === own || exitedChildren.has(own)) return;
367
+ faulted = own;
368
+ port = 0;
369
+ utilityNode = "";
370
+ error = message;
371
+ clearScopes();
372
+ for (const id of observations.keys()) cancelObservation(id, "cancelled");
373
+ rejectControls();
374
+ try {
375
+ own.postMessage({ type: "update", snapshot: { enabled: false, clients: [] } });
376
+ } catch {
377
+ }
378
+ synchronize();
379
+ void enqueue(async () => {
380
+ await stop();
381
+ }).catch(() => void 0);
382
+ };
383
+ const postChild = (own, message) => {
384
+ if (child !== own || exitedChildren.has(own)) return false;
385
+ try {
386
+ own.postMessage(message);
387
+ return true;
388
+ } catch {
389
+ faultChild(own, "MCP IPC failed. Waiting for process exit; no request was replayed.");
390
+ return false;
391
+ }
392
+ };
393
+ const synchronize = () => {
394
+ try {
395
+ discovery.update(state());
396
+ } catch {
397
+ discoveryError = "Agent discovery could not be saved; MCP access is unchanged.";
398
+ }
399
+ if (child && !faulted) postChild(child, { type: "update", snapshot: policy.snapshot() });
400
+ for (const [id, lease] of leases) {
401
+ try {
402
+ const client = policy.authorize(lease.clientId, lease.revision, lease.targetId);
403
+ if (client.mode === "read_only" || faulted) throw failure("permission_denied");
404
+ } catch {
405
+ releaseLease(id);
406
+ }
407
+ }
408
+ for (const [id, item] of observations) {
409
+ try {
410
+ policy.authorize(item.clientId, item.revision, item.target);
411
+ } catch {
412
+ cancelObservation(id, "permission_denied");
413
+ }
414
+ }
415
+ for (const owner of owners.values()) sendRenderer(owner.sender, {
416
+ type: "state",
417
+ state: state(),
418
+ leases: [...leases.values()].filter((l) => l.sender === owner.sender).map((l) => {
419
+ const target = policy.targets.get(l.targetId);
420
+ return { id: l.id, clientId: l.clientId, revision: l.revision, targetId: l.targetId, key: target.key, session: target.session, expiresAt: l.expiresAt };
421
+ }),
422
+ grants: policy.enabled && !faulted ? [...policy.clients.values()].flatMap((c) => [...c.targets].map((id) => policy.targets.get(id)).filter((t) => t?.owner === owner.sender.id).map((t) => ({ clientId: c.id, mode: c.mode, revision: c.revision, targetId: t.id, key: t.key, session: t.session }))) : []
423
+ });
424
+ };
425
+ const control = (type, data = {}) => new Promise((resolve, reject) => {
426
+ const own = child;
427
+ if (!own) return reject(new Error("MCP process unavailable"));
428
+ const timeoutMs = type === "start" ? 2e4 : 5e3;
429
+ const id = randomId(), timer = setTimeout(() => {
430
+ controls.delete(id);
431
+ reject(new Error(type === "start" ? "MCP HTTP listener did not reply within 20 seconds; no request replayed" : "MCP control observation timed out; no request replayed"));
432
+ }, timeoutMs);
433
+ controls.set(id, { resolve, reject, timer });
434
+ if (!postChild(own, { type, ...data, id })) {
435
+ controls.delete(id);
436
+ clearTimeout(timer);
437
+ reject(new Error("MCP process unavailable"));
438
+ }
439
+ });
440
+ const dispatch = async (message) => {
441
+ if (faulted || !port) throw failure("cancelled");
442
+ const client = policy.authorize(message.clientId, message.revision);
443
+ if (message.tool === "list_tabs") return [...client.targets].map((id) => policy.targets.get(id)).filter(Boolean).map((t) => ({ tabId: t.id, title: t.title }));
444
+ const writing = ["send_input", "send_keys", "attach_process", "release_tab"].includes(message.tool);
445
+ if (!writing && message.tool !== "read_tab" || !message.args || typeof message.args.tabId !== "string") throw failure("permission_denied");
446
+ policy.authorize(message.clientId, message.revision, message.args.tabId);
447
+ const target = policy.targets.get(message.args.tabId), owner = owners.get(target.owner);
448
+ if (!owner) throw failure("target_closed");
449
+ if (observations.size >= 16) throw failure("busy");
450
+ let lease;
451
+ if (writing) {
452
+ if (client.mode === "read_only") throw failure("permission_denied");
453
+ if (message.args.leaseId) {
454
+ const existing = leases.get(message.args.leaseId);
455
+ if (!existing || existing.clientId !== client.id || existing.revision !== client.revision || existing.targetId !== target.id || existing.expiresAt <= Date.now()) throw failure("invalid_lease");
456
+ lease = existing;
457
+ if ([...observations.values()].some((o) => o.leaseId === lease.id)) throw failure("busy");
458
+ } else {
459
+ if (message.tool !== "attach_process" && !(message.tool === "send_input" && message.args.mode !== "stdin")) throw failure("invalid_lease");
460
+ if ([...leases.values()].some((l) => l.targetId === target.id)) throw failure("busy");
461
+ lease = { id: randomId(), clientId: client.id, revision: client.revision, targetId: target.id, sender: owner.sender, expiresAt: 0, timer: void 0 };
462
+ leases.set(lease.id, lease);
463
+ touchLease(lease.id);
464
+ }
465
+ }
466
+ const value = await new Promise((resolve, reject) => {
467
+ const id = randomId(), confirm = writing && message.tool !== "release_tab" && client.mode === "confirm";
468
+ const timer = setTimeout(() => {
469
+ cancelObservation(id, confirm ? "approval_timeout" : "observation_timeout");
470
+ synchronize();
471
+ }, confirm ? 25e3 : 32e3);
472
+ const item = { sender: owner.sender, target: target.id, clientId: client.id, revision: client.revision, resolve, reject, timer, callId: message.id, leaseId: writing ? lease.id : void 0, sent: false, approval: void 0, launch: void 0 };
473
+ item.launch = () => {
474
+ item.approval = void 0;
475
+ clearTimeout(item.timer);
476
+ item.timer = setTimeout(() => {
477
+ cancelObservation(id, "observation_timeout");
478
+ synchronize();
479
+ }, 32e3);
480
+ try {
481
+ policy.authorize(client.id, client.revision, target.id);
482
+ if (writing && !leases.has(lease.id)) throw failure("invalid_lease");
483
+ } catch {
484
+ cancelObservation(id, "permission_denied");
485
+ return;
486
+ }
487
+ item.sent = true;
488
+ if (!sendRenderer(owner.sender, { type: writing ? "execute" : "read", id, tool: message.tool, leaseId: item.leaseId, clientId: client.id, revision: client.revision, targetId: target.id, key: target.key, session: target.session, args: message.args })) cancelObservation(id, "target_closed", false);
489
+ };
490
+ observations.set(id, item);
491
+ if (confirm) item.approval = { client: client.name, title: target.title, tool: message.tool, input: JSON.stringify(message.args, null, 2), expiresAt: Date.now() + 25e3 };
492
+ synchronize();
493
+ if (!confirm && observations.has(id)) item.launch();
494
+ }).catch((error2) => {
495
+ if (writing) {
496
+ releaseLease(lease.id);
497
+ synchronize();
498
+ }
499
+ ;
500
+ throw error2;
501
+ });
502
+ if (writing) {
503
+ if (message.tool === "release_tab" || value.sent === false) releaseLease(lease.id);
504
+ else touchLease(lease.id);
505
+ synchronize();
506
+ }
507
+ policy.authorize(message.clientId, message.revision, target.id);
508
+ if (policy.targets.get(target.id) !== target) throw failure("target_stale");
509
+ return writing ? { ...value, tabId: target.id, ...leases.has(lease.id) ? { leaseId: lease.id, leaseExpiresAt: lease.expiresAt } : {} } : value;
510
+ };
511
+ const start = async () => {
512
+ if (stopping) await stopping;
513
+ if (child) {
514
+ if (faulted || !port) throw new Error(error || "MCP process exit has not been observed");
515
+ return;
516
+ }
517
+ if (!policy.enabled || !owners.size) return;
518
+ error = "";
519
+ let own;
520
+ const env = { ...process.env };
521
+ for (const key of Object.keys(env)) if (/^(path|node_options|node_path|electron_run_as_node)$/i.test(key)) env[key] = "";
522
+ Object.assign(env, { NODE_OPTIONS: "", NODE_PATH: "", ELECTRON_RUN_AS_NODE: "", PATH: "" });
523
+ try {
524
+ own = utilityProcess.fork((0, import_node_path3.join)(__dirname, "utility.cjs"), [], { stdio: "pipe", serviceName: "Tabby AI Tools \u2014 MCP", env });
525
+ } catch {
526
+ error = "MCP process could not be launched";
527
+ synchronize();
528
+ throw new Error(error);
529
+ }
530
+ child = own;
531
+ faulted = void 0;
532
+ let spawned = false, runtimeReady = false, diagnostics = "", stderr;
533
+ const drain = () => {
534
+ own.stdout?.resume();
535
+ if (own.stderr && stderr !== own.stderr) {
536
+ stderr = own.stderr;
537
+ stderr.on("data", (chunk) => {
538
+ diagnostics = (diagnostics + chunk.toString()).slice(-4096);
539
+ });
540
+ }
541
+ };
542
+ drain();
543
+ own.once("spawn", () => {
544
+ spawned = true;
545
+ drain();
546
+ });
547
+ const ready = new Promise((resolve, reject) => {
548
+ const timer = setTimeout(() => {
549
+ controls.delete("runtime-ready");
550
+ reject(new Error(spawned ? "MCP runtime did not become ready within 20 seconds (loading the bundled runtime)" : "MCP utility process did not spawn within 20 seconds"));
551
+ }, 2e4);
552
+ controls.set("runtime-ready", { resolve, reject, timer });
553
+ });
554
+ let resolveExit;
555
+ exits.set(own, new Promise((resolve) => {
556
+ resolveExit = resolve;
557
+ }));
558
+ own.once("exit", (code) => {
559
+ exitedChildren.add(own);
560
+ resolveExit();
561
+ if (child !== own) return;
562
+ const wasRunning = !!port;
563
+ child = void 0;
564
+ faulted = void 0;
565
+ port = 0;
566
+ utilityNode = "";
567
+ if (!stopping && policy.enabled && !error) {
568
+ const detail = diagnostics.match(/\b(MODULE_NOT_FOUND|ERR_MODULE_NOT_FOUND|ERR_REQUIRE_ESM|ERR_REQUIRE_ASYNC_MODULE|ERR_UNKNOWN_BUILTIN_MODULE|SyntaxError|ReferenceError|TypeError)\b/)?.[0];
569
+ error = wasRunning ? "MCP process exited. Disable and enable to restart; no request was replayed." : `MCP process exited ${runtimeReady ? "while starting the HTTP listener" : "before the runtime became ready"} (exit ${code}${detail ? "; " + detail : ""}). Disable and enable to restart; no request was replayed.`;
570
+ }
571
+ for (const id of observations.keys()) cancelObservation(id, "cancelled");
572
+ rejectControls(error || void 0);
573
+ clearScopes();
574
+ synchronize();
575
+ });
576
+ own.once("error", () => faultChild(own, "MCP process failed. Waiting for process exit; no request was replayed."));
577
+ own.on("message", (message) => {
578
+ if (child !== own || !message) return;
579
+ if (message.type === "ready" && !faulted) {
580
+ const waiter = controls.get("runtime-ready");
581
+ if (!waiter) return;
582
+ runtimeReady = true;
583
+ controls.delete("runtime-ready");
584
+ clearTimeout(waiter.timer);
585
+ waiter.resolve(void 0);
586
+ } else if (message.type === "tool") {
587
+ void dispatch(message).then((value) => {
588
+ postChild(own, { type: "tool-result", id: message.id, value });
589
+ }, (error2) => {
590
+ postChild(own, { type: "tool-result", id: message.id, error: error2.code || "internal_error" });
591
+ });
592
+ } else if (message.type === "cancel") {
593
+ for (const [id, item] of observations) if (item.callId === message.id) cancelObservation(id, "cancelled");
594
+ synchronize();
595
+ } else if (message.type === "activity" && !faulted) {
596
+ const client = policy.clients.get(message.clientId);
597
+ if (client) {
598
+ client.lastSeen = (/* @__PURE__ */ new Date()).toISOString();
599
+ synchronize();
600
+ }
601
+ } else if (message.type === "control-result") {
602
+ const waiter = controls.get(message.id);
603
+ if (!waiter) return;
604
+ controls.delete(message.id);
605
+ clearTimeout(waiter.timer);
606
+ if (message.error) waiter.reject(new Error(message.error));
607
+ else waiter.resolve(message.value);
608
+ }
609
+ });
610
+ try {
611
+ await ready;
612
+ const info = await control("start", { port: policy.port, snapshot: policy.snapshot() });
613
+ if (child !== own || faulted) throw new Error("MCP process unavailable");
614
+ port = info.port;
615
+ utilityNode = info.node;
616
+ policy.port = port;
617
+ policy.save();
618
+ synchronize();
619
+ } catch (failure2) {
620
+ error = failure2.message === "EADDRINUSE" ? "MCP port is occupied. Disable the service and choose another port." : error || "MCP could not start: " + failure2.message;
621
+ await stop();
622
+ synchronize();
623
+ throw new Error(error);
624
+ }
625
+ };
626
+ const stop = () => stopping ||= (async () => {
627
+ port = 0;
628
+ for (const id of leases.keys()) releaseLease(id);
629
+ for (const id of observations.keys()) cancelObservation(id, "cancelled");
630
+ const own = child;
631
+ if (!own || exitedChildren.has(own)) return;
632
+ postChild(own, { type: "update", snapshot: { enabled: false, clients: [] } });
633
+ const exit = exits.get(own);
634
+ const kill = () => {
635
+ if (child === own && !exitedChildren.has(own)) {
636
+ try {
637
+ own.kill();
638
+ } catch {
639
+ }
640
+ }
641
+ };
642
+ const soft = setTimeout(kill, 250);
643
+ const force = setTimeout(() => {
644
+ if (child === own && !exitedChildren.has(own) && own.pid) {
645
+ try {
646
+ process.kill(own.pid, "SIGKILL");
647
+ } catch {
648
+ }
649
+ }
650
+ }, 1500);
651
+ let timeout;
652
+ const limit = new Promise((_resolve, reject) => {
653
+ timeout = setTimeout(() => reject(new Error("MCP process exit not observed. The process slot is retained; restart Tabby if it remains unavailable.")), 5e3);
654
+ });
655
+ void control("stop").then(kill, kill);
656
+ try {
657
+ await Promise.race([exit, limit]);
658
+ } catch (failure2) {
659
+ faulted = own;
660
+ error = failure2.message;
661
+ clearScopes();
662
+ synchronize();
663
+ throw failure2;
664
+ } finally {
665
+ clearTimeout(soft);
666
+ clearTimeout(force);
667
+ clearTimeout(timeout);
668
+ }
669
+ })().finally(() => {
670
+ stopping = void 0;
671
+ });
672
+ const commit = async () => {
673
+ try {
674
+ policy.save();
675
+ } catch {
676
+ policy.enabled = false;
677
+ error = "Could not save MCP permissions. Service disabled.";
678
+ synchronize();
679
+ await stop();
680
+ throw new Error(error);
681
+ }
682
+ synchronize();
683
+ };
684
+ const removeOwner = async (id) => {
685
+ dropOwner(id);
686
+ synchronize();
687
+ if (!owners.size) await stop();
688
+ };
689
+ ipcMain.on(CHANNEL + "-reply", (event, message) => {
690
+ const item = observations.get(message?.id);
691
+ if (!item || !trusted(event) || event.sender !== item.sender) return;
692
+ observations.delete(message.id);
693
+ clearTimeout(item.timer);
694
+ try {
695
+ policy.authorize(item.clientId, item.revision, item.target);
696
+ if (message.error) item.reject(failure(message.error));
697
+ else if (Buffer.byteLength(JSON.stringify(message.value ?? null)) > 128 * 1024) item.reject(failure("internal_error"));
698
+ else item.resolve(message.value);
699
+ } catch {
700
+ item.reject(failure("permission_denied"));
701
+ }
702
+ });
703
+ ipcMain.handle(CHANNEL, (event, message) => enqueue(async () => {
704
+ if (!trusted(event) || !message || typeof message.type !== "string") throw new Error("Untrusted MCP control request");
705
+ const sender = event.sender;
706
+ if (message.type === "register") {
707
+ if (!owners.has(sender.id)) {
708
+ const gone = () => {
709
+ void enqueue(() => removeOwner(sender.id)).catch(() => void 0);
710
+ };
711
+ owners.set(sender.id, { sender, cleanup: () => {
712
+ sender.off("destroyed", gone);
713
+ sender.off("render-process-gone", gone);
714
+ } });
715
+ sender.once("destroyed", gone);
716
+ sender.once("render-process-gone", gone);
717
+ }
718
+ if (policy.enabled && !error) {
719
+ try {
720
+ await start();
721
+ } catch {
722
+ }
723
+ }
724
+ synchronize();
725
+ return state();
726
+ }
727
+ if (!owners.has(sender.id)) throw new Error("MCP renderer is not registered");
728
+ if (message.type === "agent-connection-instructions") return discovery.connectionInstructions();
729
+ let value;
730
+ if (message.type === "install-agent-skill") installSkill();
731
+ else if (message.type === "decide") {
732
+ const item = observations.get(message.id);
733
+ if (!item?.approval || item.sender !== sender) throw failure("permission_denied");
734
+ if (item.approval.expiresAt <= Date.now()) cancelObservation(message.id, "approval_timeout");
735
+ else if (message.accept === true) item.launch?.();
736
+ else cancelObservation(message.id, "approval_denied");
737
+ } else if (message.type === "release-lease") {
738
+ const lease = leases.get(message.id);
739
+ if (!lease || lease.sender !== sender) throw failure("permission_denied");
740
+ for (const [id, item] of observations) if (item.leaseId === lease.id) cancelObservation(id, "cancelled");
741
+ releaseLease(lease.id);
742
+ } else if (message.type === "mode") {
743
+ policy.setMode(message.id, message.mode);
744
+ await commit();
745
+ } else if (message.type === "targets") {
746
+ policy.register(sender.id, message.targets);
747
+ synchronize();
748
+ } else if (message.type === "state") return state();
749
+ else if (message.type === "enabled") {
750
+ policy.enabled = message.enabled === true;
751
+ for (const client of policy.clients.values()) {
752
+ client.revision++;
753
+ if (!policy.enabled && client.id !== LOCAL_CLIENT_ID) client.targets.clear();
754
+ }
755
+ await commit();
756
+ if (policy.enabled) await start();
757
+ else {
758
+ error = "";
759
+ await stop();
760
+ }
761
+ } else if (message.type === "port") {
762
+ if (policy.enabled) throw new Error("Disable MCP before changing its port");
763
+ if (!Number.isInteger(message.port) || message.port < 0 || message.port > 65535) throw new Error("Port must be between 0 and 65535");
764
+ policy.port = message.port;
765
+ await commit();
766
+ } else if (message.type === "add") {
767
+ value = policy.add(message.name);
768
+ await commit();
769
+ } else if (message.type === "rotate") {
770
+ value = policy.rotate(message.id);
771
+ await commit();
772
+ } else if (message.type === "revoke") {
773
+ if (message.id === LOCAL_CLIENT_ID) throw new Error("Disable MCP to revoke local access");
774
+ policy.client(message.id);
775
+ policy.clients.delete(message.id);
776
+ await commit();
777
+ } else if (message.type === "scope") {
778
+ policy.setScope(message.id, message.targets);
779
+ await commit();
780
+ } else if (message.type === "unregister") await removeOwner(sender.id);
781
+ else throw new Error("Unknown MCP action");
782
+ synchronize();
783
+ return value ?? state();
784
+ }));
785
+ app.once("before-quit", () => {
786
+ try {
787
+ discovery.update({ enabled: policy.enabled, running: false, endpoint: "" });
788
+ } catch {
789
+ }
790
+ ;
791
+ try {
792
+ child?.kill();
793
+ } catch {
794
+ }
795
+ });
796
+ globalState[singleton] = true;
797
+ }
798
+ // Annotate the CommonJS export names for ESM import in node:
799
+ 0 && (module.exports = {
800
+ install
801
+ });