tabby-ai-tools 1.0.0 → 1.2.1

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.
@@ -34,6 +34,7 @@ var import_node_path = require("node:path");
34
34
  var failure = (code) => Object.assign(new Error(code), { code });
35
35
  var randomId = () => (0, import_node_crypto.randomBytes)(24).toString("base64url");
36
36
  var tokenDigest = (value) => (0, import_node_crypto.createHash)("sha256").update(value).digest("hex");
37
+ var LOCAL_CLIENT_ID = "local";
37
38
  var McpPolicy = class {
38
39
  enabled = false;
39
40
  port = 0;
@@ -41,6 +42,7 @@ var McpPolicy = class {
41
42
  targets = /* @__PURE__ */ new Map();
42
43
  file;
43
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() });
44
46
  (0, import_node_fs.mkdirSync)(directory, { recursive: true, mode: 448 });
45
47
  if ((0, import_node_fs.lstatSync)(directory).isSymbolicLink()) throw new Error("MCP state directory must not be a symlink");
46
48
  if (process.platform !== "win32") (0, import_node_fs.chmodSync)(directory, 448);
@@ -54,7 +56,7 @@ var McpPolicy = class {
54
56
  this.enabled = data.enabled === true;
55
57
  this.port = data.port;
56
58
  for (const item of data.clients) {
57
- if (typeof item.id !== "string" || !/^[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");
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");
58
60
  this.clients.set(item.id, { ...item, targets: /* @__PURE__ */ new Set(), mode: "read_only", revision: item.revision + 1, lastSeen: void 0 });
59
61
  }
60
62
  } catch (error) {
@@ -63,7 +65,7 @@ var McpPolicy = class {
63
65
  }
64
66
  save() {
65
67
  const temporary = this.file + "." + randomId() + ".tmp";
66
- const data = { version: 1, enabled: this.enabled, port: this.port, clients: [...this.clients.values()].map(({ id, name, digest, revision }) => ({ id, name, digest, revision })) };
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 })) };
67
69
  try {
68
70
  (0, import_node_fs.writeFileSync)(temporary, JSON.stringify(data) + "\n", { mode: 384, flag: "wx" });
69
71
  (0, import_node_fs.renameSync)(temporary, this.file);
@@ -73,12 +75,13 @@ var McpPolicy = class {
73
75
  }
74
76
  add(name) {
75
77
  if (typeof name !== "string" || !name.trim() || name.trim().length > 80) throw new Error("Client name must contain 1\u201380 characters");
76
- if (this.clients.size >= 32) throw new Error("At most 32 MCP clients are allowed");
78
+ if (this.clients.size >= 33) throw new Error("At most 32 MCP clients are allowed");
77
79
  const id = randomId(), token = (0, import_node_crypto.randomBytes)(32).toString("base64url");
78
80
  this.clients.set(id, { id, name: name.trim(), digest: tokenDigest(token), revision: 1, mode: "read_only", targets: /* @__PURE__ */ new Set() });
79
81
  return { id, token };
80
82
  }
81
83
  rotate(id) {
84
+ if (id === LOCAL_CLIENT_ID) throw new Error("The local connection does not use a token");
82
85
  const client = this.client(id), token = (0, import_node_crypto.randomBytes)(32).toString("base64url");
83
86
  client.digest = tokenDigest(token);
84
87
  client.revision++;
@@ -91,12 +94,14 @@ var McpPolicy = class {
91
94
  return client;
92
95
  }
93
96
  setScope(id, targetIds) {
94
- if (!Array.isArray(targetIds) || targetIds.length > 256 || targetIds.some((id2) => typeof id2 !== "string" || !this.targets.has(id2))) throw failure("target_stale");
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) || this.targets.get(id2)?.connected === false)) throw failure("target_stale");
95
99
  const client = this.client(id);
96
100
  client.targets = new Set(targetIds);
97
101
  client.revision++;
98
102
  }
99
103
  setMode(id, mode) {
104
+ if (id === LOCAL_CLIENT_ID) throw failure("permission_denied");
100
105
  if (!["read_only", "confirm", "auto"].includes(mode)) throw failure("permission_denied");
101
106
  const client = this.client(id);
102
107
  client.mode = mode;
@@ -104,18 +109,19 @@ var McpPolicy = class {
104
109
  }
105
110
  removeTarget(id) {
106
111
  this.targets.delete(id);
107
- for (const client of this.clients.values()) if (client.targets.delete(id)) client.revision++;
112
+ for (const client of this.clients.values()) if (client.targets.delete(id) && client.id !== LOCAL_CLIENT_ID) client.revision++;
108
113
  }
109
114
  register(owner, entries) {
110
- 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");
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 || t.connected !== void 0 && typeof t.connected !== "boolean")) throw new Error("Invalid terminal registration");
111
116
  if (new Set(entries.map((t) => t.key)).size !== entries.length) throw new Error("Duplicate terminal key");
112
- 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);
117
+ for (const target of [...this.targets.values()]) if (target.owner === owner && !entries.some((e) => e.key === target.key && e.session === target.session && e.connected === false === (target.connected === false))) this.removeTarget(target.id);
113
118
  for (const entry of entries) {
114
119
  const current = [...this.targets.values()].find((t) => t.owner === owner && t.key === entry.key && t.session === entry.session);
115
120
  if (current) current.title = entry.title;
116
121
  else {
117
122
  const id = randomId();
118
123
  this.targets.set(id, { ...entry, id, owner });
124
+ this.client(LOCAL_CLIENT_ID).targets.add(id);
119
125
  }
120
126
  }
121
127
  }
@@ -132,7 +138,8 @@ var McpPolicy = class {
132
138
  return { enabled: this.enabled, clients: [...this.clients.values()].map((c) => ({ id: c.id, digest: c.digest, revision: c.revision, mode: c.mode })) };
133
139
  }
134
140
  publicState() {
135
- return { enabled: this.enabled, clients: [...this.clients.values()].map((c) => ({ id: c.id, name: c.name, mode: c.mode, revision: c.revision, targets: [...c.targets], lastSeen: c.lastSeen })), targets: [...this.targets.values()].map((t) => ({ id: t.id, title: t.title, window: t.owner })) };
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()].filter((t) => t.connected !== false).map((t) => ({ id: t.id, title: t.title, window: t.owner })) };
136
143
  }
137
144
  };
138
145
 
@@ -154,6 +161,9 @@ var McpDiscovery = class {
154
161
  registry;
155
162
  profile;
156
163
  last = "";
164
+ connectionInstructions() {
165
+ return (0, import_node_fs2.readFileSync)((0, import_node_path2.join)(this.skillSource, "references/connection.md"), "utf8");
166
+ }
157
167
  directory(path) {
158
168
  (0, import_node_fs2.mkdirSync)(path, { recursive: true, mode: 448 });
159
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");
@@ -161,6 +171,7 @@ var McpDiscovery = class {
161
171
  installSkill() {
162
172
  const roots = [(0, import_node_path2.join)(this.home, ".agents", "skills")];
163
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
+ if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(this.home, ".gemini"))) roots.push((0, import_node_path2.join)(this.home, ".gemini", "config", "skills"));
164
175
  const files = {
165
176
  "SKILL.md": (0, import_node_fs2.readFileSync)((0, import_node_path2.join)(this.skillSource, "SKILL.md"), "utf8"),
166
177
  "references/connection.md": (0, import_node_fs2.readFileSync)((0, import_node_path2.join)(this.skillSource, "references/connection.md"), "utf8"),
@@ -224,7 +235,7 @@ var McpDiscovery = class {
224
235
  }
225
236
  update(state) {
226
237
  const status = state.running ? "running" : state.enabled ? "unavailable" : "disabled";
227
- const payload = { format: "tabby-mcp-discovery-v1", profile: this.profile, application: "Tabby AI Tools", version: this.version, status, endpoint: state.running ? state.endpoint : "", authentication: "independent_client_bearer", credentialsIncluded: false, setup: "Tabby > Settings > AI Tools > External AI connections (MCP)", skill: "tabby-mcp" };
238
+ 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" };
228
239
  if (payload.endpoint && !/^http:\/\/127\.0\.0\.1:\d+\/mcp$/.test(payload.endpoint)) throw new Error("Invalid discovery endpoint");
229
240
  const value = JSON.stringify(payload);
230
241
  if (this.last === value && (0, import_node_fs2.existsSync)((0, import_node_path2.join)(this.registry, this.profile + ".json"))) return;
@@ -245,12 +256,14 @@ var McpDiscovery = class {
245
256
  var { app, ipcMain, utilityProcess } = require("electron");
246
257
  var CHANNEL = "tabby-ai-mcp-v1";
247
258
  var singleton = /* @__PURE__ */ Symbol.for("tabby-ai.mcp.host.v1");
259
+ var transferIdPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
260
+ var transferView = ({ signature: _signature, revision: _revision, finishedAt: _finishedAt, ...result }) => result;
248
261
  function install() {
249
262
  const globalState = globalThis;
250
263
  if (globalState[singleton]) return;
251
264
  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");
252
265
  const configSpace = (0, import_node_fs3.realpathSync)(process.env.TABBY_CONFIG_DIRECTORY || app.getPath("userData"));
253
- const discovery = new McpDiscovery(app.getPath("home"), configSpace, (0, import_node_path3.join)(__dirname, "../../skills/tabby-mcp"), "1.0.0");
266
+ const discovery = new McpDiscovery(app.getPath("home"), configSpace, (0, import_node_path3.join)(__dirname, "../../skills/tabby-mcp"), "1.2.1");
254
267
  let skillInstallations = [], discoveryError = "";
255
268
  const installSkill = () => {
256
269
  try {
@@ -267,6 +280,7 @@ function install() {
267
280
  const controls = /* @__PURE__ */ new Map();
268
281
  const leases = /* @__PURE__ */ new Map();
269
282
  const observations = /* @__PURE__ */ new Map();
283
+ const transfers = /* @__PURE__ */ new Map();
270
284
  const exits = /* @__PURE__ */ new WeakMap(), exitedChildren = /* @__PURE__ */ new WeakSet();
271
285
  let child, faulted, port = 0, error = "", utilityNode = "", chain = Promise.resolve(), stopping;
272
286
  const trusted = (event) => {
@@ -281,7 +295,7 @@ function install() {
281
295
  chain = next.then(() => void 0, () => void 0);
282
296
  return next;
283
297
  };
284
- const state = () => ({ ...policy.publicState(), discovery: { registry: discovery.registry, 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 });
298
+ 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 });
285
299
  const releaseLease = (id) => {
286
300
  const lease = leases.get(id);
287
301
  if (!lease) return;
@@ -304,14 +318,14 @@ function install() {
304
318
  const clearScopes = () => {
305
319
  for (const id of leases.keys()) releaseLease(id);
306
320
  for (const client of policy.clients.values()) {
307
- client.targets.clear();
321
+ if (client.id !== LOCAL_CLIENT_ID) client.targets.clear();
308
322
  client.revision++;
309
323
  }
310
324
  };
311
- const rejectControls = () => {
325
+ const rejectControls = (reason = "MCP process unavailable") => {
312
326
  for (const waiter of controls.values()) {
313
327
  clearTimeout(waiter.timer);
314
- waiter.reject(new Error("MCP process unavailable"));
328
+ waiter.reject(new Error(reason));
315
329
  }
316
330
  controls.clear();
317
331
  };
@@ -397,7 +411,7 @@ function install() {
397
411
  }
398
412
  for (const [id, item] of observations) {
399
413
  try {
400
- policy.authorize(item.clientId, item.revision, item.target);
414
+ policy.authorize(item.clientId, item.revision, item.replacesTarget && item.sent ? void 0 : item.target);
401
415
  } catch {
402
416
  cancelObservation(id, "permission_denied");
403
417
  }
@@ -415,10 +429,11 @@ function install() {
415
429
  const control = (type, data = {}) => new Promise((resolve, reject) => {
416
430
  const own = child;
417
431
  if (!own) return reject(new Error("MCP process unavailable"));
432
+ const timeoutMs = type === "start" ? 2e4 : 5e3;
418
433
  const id = randomId(), timer = setTimeout(() => {
419
434
  controls.delete(id);
420
- reject(new Error("MCP control observation timed out; no request replayed"));
421
- }, 5e3);
435
+ 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"));
436
+ }, timeoutMs);
422
437
  controls.set(id, { resolve, reject, timer });
423
438
  if (!postChild(own, { type, ...data, id })) {
424
439
  controls.delete(id);
@@ -426,15 +441,53 @@ function install() {
426
441
  reject(new Error("MCP process unavailable"));
427
442
  }
428
443
  });
429
- const dispatch = async (message) => {
444
+ const dispatch = async (message, transfer) => {
430
445
  if (faulted || !port) throw failure("cancelled");
431
446
  const client = policy.authorize(message.clientId, message.revision);
432
- if (message.tool === "list_tabs") return [...client.targets].map((id) => policy.targets.get(id)).filter(Boolean).map((t) => ({ tabId: t.id, title: t.title }));
433
- const writing = ["send_input", "send_keys", "attach_process", "release_tab"].includes(message.tool);
447
+ if (message.tool === "sftp_status" || message.tool === "sftp_transfer") {
448
+ const now = Date.now();
449
+ for (const [key, value2] of transfers) if (value2.finishedAt !== void 0 && now - value2.finishedAt >= 9e5) transfers.delete(key);
450
+ }
451
+ if (message.tool === "sftp_status") {
452
+ const receipt = transfers.get(client.id + ":" + message.args?.transferId);
453
+ if (!receipt || receipt.revision !== client.revision) throw failure("transfer_not_found");
454
+ return transferView(receipt);
455
+ }
456
+ if (message.tool === "list_tabs") return [...client.targets].map((id) => policy.targets.get(id)).filter(Boolean).map((t) => ({ tabId: t.id, title: t.title, ...t.connected === false ? { connected: false } : {} }));
457
+ const oneShot = ["ssh_exec", "manage_tab", "sftp_transfer"].includes(message.tool);
458
+ const writing = oneShot || ["send_input", "send_keys", "attach_process", "release_tab"].includes(message.tool);
434
459
  if (!writing && message.tool !== "read_tab" || !message.args || typeof message.args.tabId !== "string") throw failure("permission_denied");
435
460
  policy.authorize(message.clientId, message.revision, message.args.tabId);
461
+ const manageAction = message.tool === "manage_tab" ? message.args.action : void 0;
462
+ const replacesTarget = manageAction === "close" || manageAction === "reconnect";
463
+ if (["close", "open_profile", "list_profiles", "reconnect"].includes(manageAction) && client.id !== LOCAL_CLIENT_ID) throw failure("permission_denied");
464
+ if (oneShot && message.args.leaseId !== void 0) throw failure("permission_denied");
436
465
  const target = policy.targets.get(message.args.tabId), owner = owners.get(target.owner);
437
- if (!owner) throw failure("target_closed");
466
+ if (!owner || target.connected === false && message.tool !== "manage_tab") throw failure("target_closed");
467
+ if (message.tool === "sftp_transfer" && !transfer) {
468
+ if (client.mode === "read_only") throw failure("permission_denied");
469
+ const { requestId, direction, localPath, remotePath, allowPtyFallback } = message.args;
470
+ if (typeof requestId !== "string" || !transferIdPattern.test(requestId) || !["upload", "download"].includes(direction) || [localPath, remotePath].some((value2) => typeof value2 !== "string" || !value2.length || value2.length > 4096 || /[\x00-\x1f\x7f]/.test(value2)) || !(0, import_node_path3.isAbsolute)(localPath) || !import_node_path3.posix.isAbsolute(remotePath) || ["", ".", ".."].includes((0, import_node_path3.basename)(localPath)) || allowPtyFallback !== void 0 && typeof allowPtyFallback !== "boolean") throw failure("operation_failed");
471
+ const key = client.id + ":" + requestId;
472
+ const signature = JSON.stringify([target.id, direction, localPath, remotePath, allowPtyFallback === true]);
473
+ const existing = transfers.get(key);
474
+ if (existing) {
475
+ if (existing.revision !== client.revision || existing.signature !== signature) throw failure("transfer_conflict");
476
+ return transferView(existing);
477
+ }
478
+ if (transfers.size >= 128 || observations.size >= 16 || [...leases.values()].some((lease2) => lease2.targetId === target.id)) throw failure("busy");
479
+ const destination = direction === "upload" ? import_node_path3.posix.join(remotePath, ".tabby-mcp-" + requestId, (0, import_node_path3.basename)(localPath)) : import_node_path3.posix.normalize(remotePath);
480
+ if (destination.length > 4096) throw failure("operation_failed");
481
+ const receipt = { transferId: requestId, revision: client.revision, signature, direction, localPath, remotePath: destination, status: "awaiting_approval" };
482
+ transfers.set(key, receipt);
483
+ void dispatch({ ...message, id: randomId(), args: { ...message.args, remotePath: destination, allowPtyFallback: allowPtyFallback === true } }, receipt).then((value2) => {
484
+ Object.assign(receipt, { status: "completed", bytes: value2.bytes, hash: value2.hash, ...value2.transport ? { transport: value2.transport } : {}, finishedAt: Date.now() });
485
+ }, (error2) => {
486
+ const code = error2.code || "internal_error";
487
+ Object.assign(receipt, { status: code === "unknown_outcome" ? "unknown" : "failed", code, finishedAt: Date.now() });
488
+ });
489
+ return transferView(receipt);
490
+ }
438
491
  if (observations.size >= 16) throw failure("busy");
439
492
  let lease;
440
493
  if (writing) {
@@ -445,7 +498,7 @@ function install() {
445
498
  lease = existing;
446
499
  if ([...observations.values()].some((o) => o.leaseId === lease.id)) throw failure("busy");
447
500
  } else {
448
- if (message.tool !== "attach_process" && !(message.tool === "send_input" && message.args.mode !== "stdin")) throw failure("invalid_lease");
501
+ if (!oneShot && message.tool !== "attach_process" && !(message.tool === "send_input" && message.args.mode !== "stdin")) throw failure("invalid_lease");
449
502
  if ([...leases.values()].some((l) => l.targetId === target.id)) throw failure("busy");
450
503
  lease = { id: randomId(), clientId: client.id, revision: client.revision, targetId: target.id, sender: owner.sender, expiresAt: 0, timer: void 0 };
451
504
  leases.set(lease.id, lease);
@@ -453,19 +506,19 @@ function install() {
453
506
  }
454
507
  }
455
508
  const value = await new Promise((resolve, reject) => {
456
- const id = randomId(), confirm = writing && message.tool !== "release_tab" && client.mode === "confirm";
509
+ const id = randomId(), confirm = message.tool === "sftp_transfer" || replacesTarget || writing && message.tool !== "release_tab" && client.mode === "confirm";
457
510
  const timer = setTimeout(() => {
458
511
  cancelObservation(id, confirm ? "approval_timeout" : "observation_timeout");
459
512
  synchronize();
460
513
  }, confirm ? 25e3 : 32e3);
461
- 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 };
514
+ 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, replacesTarget, sent: false, approval: void 0, launch: void 0 };
462
515
  item.launch = () => {
463
516
  item.approval = void 0;
464
517
  clearTimeout(item.timer);
465
518
  item.timer = setTimeout(() => {
466
519
  cancelObservation(id, "observation_timeout");
467
520
  synchronize();
468
- }, 32e3);
521
+ }, transfer ? 9e4 : 32e3);
469
522
  try {
470
523
  policy.authorize(client.id, client.revision, target.id);
471
524
  if (writing && !leases.has(lease.id)) throw failure("invalid_lease");
@@ -474,10 +527,14 @@ function install() {
474
527
  return;
475
528
  }
476
529
  item.sent = true;
530
+ if (transfer) transfer.status = "running";
477
531
  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);
478
532
  };
479
533
  observations.set(id, item);
480
- if (confirm) item.approval = { client: client.name, title: target.title, tool: message.tool, input: JSON.stringify(message.args, null, 2), expiresAt: Date.now() + 25e3 };
534
+ if (confirm) {
535
+ const input = transfer && message.args.allowPtyFallback ? { ...message.args, fallbackEndpoint: "The shell in this pane, which may be on a nested SSH host or in a container." } : message.args;
536
+ item.approval = { client: client.name, title: target.title, tool: message.tool, input: JSON.stringify(input, null, 2), expiresAt: Date.now() + 25e3 };
537
+ }
481
538
  synchronize();
482
539
  if (!confirm && observations.has(id)) item.launch();
483
540
  }).catch((error2) => {
@@ -489,12 +546,12 @@ function install() {
489
546
  throw error2;
490
547
  });
491
548
  if (writing) {
492
- if (message.tool === "release_tab" || value.sent === false) releaseLease(lease.id);
549
+ if (oneShot || message.tool === "release_tab" || value.sent === false) releaseLease(lease.id);
493
550
  else touchLease(lease.id);
494
551
  synchronize();
495
552
  }
496
- policy.authorize(message.clientId, message.revision, target.id);
497
- if (policy.targets.get(target.id) !== target) throw failure("target_stale");
553
+ policy.authorize(message.clientId, message.revision, replacesTarget ? void 0 : target.id);
554
+ if (!replacesTarget && policy.targets.get(target.id) !== target) throw failure("target_stale");
498
555
  return writing ? { ...value, tabId: target.id, ...leases.has(lease.id) ? { leaseId: lease.id, leaseExpiresAt: lease.expiresAt } : {} } : value;
499
556
  };
500
557
  const start = async () => {
@@ -506,8 +563,11 @@ function install() {
506
563
  if (!policy.enabled || !owners.size) return;
507
564
  error = "";
508
565
  let own;
566
+ const env = { ...process.env };
567
+ for (const key of Object.keys(env)) if (/^(path|node_options|node_path|electron_run_as_node)$/i.test(key)) env[key] = "";
568
+ Object.assign(env, { NODE_OPTIONS: "", NODE_PATH: "", ELECTRON_RUN_AS_NODE: "", PATH: "" });
509
569
  try {
510
- own = utilityProcess.fork((0, import_node_path3.join)(__dirname, "utility.cjs"), [], { stdio: "pipe", serviceName: "Tabby AI Tools \u2014 MCP", env: { NODE_OPTIONS: "", NODE_PATH: "", ELECTRON_RUN_AS_NODE: "", PATH: "" } });
570
+ own = utilityProcess.fork((0, import_node_path3.join)(__dirname, "utility.cjs"), [], { stdio: "pipe", serviceName: "Tabby AI Tools \u2014 MCP", env });
511
571
  } catch {
512
572
  error = "MCP process could not be launched";
513
573
  synchronize();
@@ -515,30 +575,61 @@ function install() {
515
575
  }
516
576
  child = own;
517
577
  faulted = void 0;
518
- own.stdout?.resume();
519
- own.stderr?.resume();
578
+ let spawned = false, runtimeReady = false, diagnostics = "", stderr;
579
+ const drain = () => {
580
+ own.stdout?.resume();
581
+ if (own.stderr && stderr !== own.stderr) {
582
+ stderr = own.stderr;
583
+ stderr.on("data", (chunk) => {
584
+ diagnostics = (diagnostics + chunk.toString()).slice(-4096);
585
+ });
586
+ }
587
+ };
588
+ drain();
589
+ own.once("spawn", () => {
590
+ spawned = true;
591
+ drain();
592
+ });
593
+ const ready = new Promise((resolve, reject) => {
594
+ const timer = setTimeout(() => {
595
+ controls.delete("runtime-ready");
596
+ 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"));
597
+ }, 2e4);
598
+ controls.set("runtime-ready", { resolve, reject, timer });
599
+ });
520
600
  let resolveExit;
521
601
  exits.set(own, new Promise((resolve) => {
522
602
  resolveExit = resolve;
523
603
  }));
524
- own.once("exit", () => {
604
+ own.once("exit", (code) => {
525
605
  exitedChildren.add(own);
526
606
  resolveExit();
527
607
  if (child !== own) return;
608
+ const wasRunning = !!port;
528
609
  child = void 0;
529
610
  faulted = void 0;
530
611
  port = 0;
531
612
  utilityNode = "";
532
- if (!stopping && policy.enabled && !error) error = "MCP process exited. Disable and enable to restart; no request was replayed.";
613
+ if (!stopping && policy.enabled && !error) {
614
+ 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];
615
+ 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.`;
616
+ }
533
617
  for (const id of observations.keys()) cancelObservation(id, "cancelled");
534
- rejectControls();
618
+ rejectControls(error || void 0);
535
619
  clearScopes();
536
620
  synchronize();
537
621
  });
538
622
  own.once("error", () => faultChild(own, "MCP process failed. Waiting for process exit; no request was replayed."));
539
623
  own.on("message", (message) => {
540
624
  if (child !== own || !message) return;
541
- if (message.type === "tool") {
625
+ if (message.type === "ready" && !faulted) {
626
+ const waiter = controls.get("runtime-ready");
627
+ if (!waiter) return;
628
+ runtimeReady = true;
629
+ controls.delete("runtime-ready");
630
+ clearTimeout(waiter.timer);
631
+ waiter.resolve(void 0);
632
+ } else if (message.type === "tool") {
542
633
  void dispatch(message).then((value) => {
543
634
  postChild(own, { type: "tool-result", id: message.id, value });
544
635
  }, (error2) => {
@@ -563,6 +654,7 @@ function install() {
563
654
  }
564
655
  });
565
656
  try {
657
+ await ready;
566
658
  const info = await control("start", { port: policy.port, snapshot: policy.snapshot() });
567
659
  if (child !== own || faulted) throw new Error("MCP process unavailable");
568
660
  port = info.port;
@@ -646,7 +738,7 @@ function install() {
646
738
  observations.delete(message.id);
647
739
  clearTimeout(item.timer);
648
740
  try {
649
- policy.authorize(item.clientId, item.revision, item.target);
741
+ policy.authorize(item.clientId, item.revision, item.replacesTarget && item.sent ? void 0 : item.target);
650
742
  if (message.error) item.reject(failure(message.error));
651
743
  else if (Buffer.byteLength(JSON.stringify(message.value ?? null)) > 128 * 1024) item.reject(failure("internal_error"));
652
744
  else item.resolve(message.value);
@@ -679,6 +771,7 @@ function install() {
679
771
  return state();
680
772
  }
681
773
  if (!owners.has(sender.id)) throw new Error("MCP renderer is not registered");
774
+ if (message.type === "agent-connection-instructions") return discovery.connectionInstructions();
682
775
  let value;
683
776
  if (message.type === "install-agent-skill") installSkill();
684
777
  else if (message.type === "decide") {
@@ -703,7 +796,7 @@ function install() {
703
796
  policy.enabled = message.enabled === true;
704
797
  for (const client of policy.clients.values()) {
705
798
  client.revision++;
706
- if (!policy.enabled) client.targets.clear();
799
+ if (!policy.enabled && client.id !== LOCAL_CLIENT_ID) client.targets.clear();
707
800
  }
708
801
  await commit();
709
802
  if (policy.enabled) await start();
@@ -723,6 +816,7 @@ function install() {
723
816
  value = policy.rotate(message.id);
724
817
  await commit();
725
818
  } else if (message.type === "revoke") {
819
+ if (message.id === LOCAL_CLIENT_ID) throw new Error("Disable MCP to revoke local access");
726
820
  policy.client(message.id);
727
821
  policy.clients.delete(message.id);
728
822
  await commit();