clauder-hub 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/package.json +1 -1
  2. package/server/dist/index.js +928 -787
  3. package/web/dist/assets/{MonacoEditor-7a1aZ6Pf.js → MonacoEditor-BlAuC60r.js} +3 -3
  4. package/web/dist/assets/{cssMode-D42SG8q2.js → cssMode-CGWHF7SU.js} +1 -1
  5. package/web/dist/assets/{freemarker2-HuLVqAyk.js → freemarker2-ButExUy0.js} +1 -1
  6. package/web/dist/assets/{handlebars-CQbtHmDj.js → handlebars-C-tQtMw_.js} +1 -1
  7. package/web/dist/assets/{html-DCQkaSoP.js → html-DO0qZYYU.js} +1 -1
  8. package/web/dist/assets/{htmlMode-Occ0oux7.js → htmlMode-HWw8frC7.js} +1 -1
  9. package/web/dist/assets/{index-DB6lAoRD.js → index-B1_0WNjk.js} +1 -1
  10. package/web/dist/assets/index-CFwNi7rE.js +594 -0
  11. package/web/dist/assets/index-CWyPZ8VA.css +32 -0
  12. package/web/dist/assets/{javascript-DkkoffJP.js → javascript-E0rNv6Hb.js} +1 -1
  13. package/web/dist/assets/{jsonMode-CvTmblXx.js → jsonMode-BtA3wy3C.js} +1 -1
  14. package/web/dist/assets/{liquid-DhsiR38F.js → liquid-DFyLG9q1.js} +1 -1
  15. package/web/dist/assets/{lspLanguageFeatures-lfpHn74b.js → lspLanguageFeatures-7Y9rDBgH.js} +1 -1
  16. package/web/dist/assets/{mdx-LuMf9AxQ.js → mdx-DHheCJGf.js} +1 -1
  17. package/web/dist/assets/{python-BkVjahJB.js → python-Dp4jpU9A.js} +1 -1
  18. package/web/dist/assets/{razor-CoVA4mXW.js → razor-CpNDoj91.js} +1 -1
  19. package/web/dist/assets/{tsMode-C3jqF6o4.js → tsMode-DmUtjqNQ.js} +1 -1
  20. package/web/dist/assets/{typescript-DzEhu0NR.js → typescript-BJ_xD_P2.js} +1 -1
  21. package/web/dist/assets/{workers-DO15KvMQ.js → workers-i2coOX7v.js} +1 -1
  22. package/web/dist/assets/{xml-Dnv-hWWk.js → xml-ISewjn85.js} +1 -1
  23. package/web/dist/assets/{yaml-hUd7D5AP.js → yaml-B0DsFM2T.js} +1 -1
  24. package/web/dist/index.html +2 -2
  25. package/web/dist/assets/index-382ZKQ6T.js +0 -527
  26. package/web/dist/assets/index-YQ0zZelJ.css +0 -32
@@ -1665,8 +1665,8 @@ var require_node = __commonJS({
1665
1665
  break;
1666
1666
  case "PIPE":
1667
1667
  case "TCP":
1668
- var net = __require("net");
1669
- stream2 = new net.Socket({
1668
+ var net2 = __require("net");
1669
+ stream2 = new net2.Socket({
1670
1670
  fd: fd2,
1671
1671
  readable: false,
1672
1672
  writable: true
@@ -25418,7 +25418,7 @@ var require_websocket = __commonJS({
25418
25418
  var EventEmitter = __require("events");
25419
25419
  var https = __require("https");
25420
25420
  var http = __require("http");
25421
- var net = __require("net");
25421
+ var net2 = __require("net");
25422
25422
  var tls = __require("tls");
25423
25423
  var { randomBytes, createHash } = __require("crypto");
25424
25424
  var { Duplex, Readable } = __require("stream");
@@ -26175,12 +26175,12 @@ var require_websocket = __commonJS({
26175
26175
  }
26176
26176
  function netConnect(options) {
26177
26177
  options.path = options.socketPath;
26178
- return net.connect(options);
26178
+ return net2.connect(options);
26179
26179
  }
26180
26180
  function tlsConnect(options) {
26181
26181
  options.path = void 0;
26182
26182
  if (!options.servername && options.servername !== "") {
26183
- options.servername = net.isIP(options.host) ? "" : options.host;
26183
+ options.servername = net2.isIP(options.host) ? "" : options.host;
26184
26184
  }
26185
26185
  return tls.connect(options);
26186
26186
  }
@@ -29070,6 +29070,294 @@ var init_categories = __esm({
29070
29070
  }
29071
29071
  });
29072
29072
 
29073
+ // server/src/channels/markdown.ts
29074
+ function pieces(markdown) {
29075
+ const out = [];
29076
+ let prose = [];
29077
+ let code = null;
29078
+ for (const line of markdown.split("\n")) {
29079
+ if (code) {
29080
+ if (/^\s*```/.test(line)) {
29081
+ out.push({ code: true, text: code.join("\n") });
29082
+ code = null;
29083
+ } else code.push(line);
29084
+ } else if (/^\s*```[^`]*$/.test(line)) {
29085
+ if (prose.length) out.push({ code: false, text: prose.join("\n") });
29086
+ prose = [];
29087
+ code = [];
29088
+ } else prose.push(line);
29089
+ }
29090
+ if (code) out.push({ code: true, text: code.join("\n") });
29091
+ if (prose.length) out.push({ code: false, text: prose.join("\n") });
29092
+ return out;
29093
+ }
29094
+ function holdLinks(text, render2, rewrite) {
29095
+ const links = [];
29096
+ const held = text.replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, (_whole, label, url) => `${links.push(render2(label, url)) - 1}`);
29097
+ return rewrite(held).replace(/\u0002(\d+)\u0002/g, (_whole, index) => links[Number(index)]);
29098
+ }
29099
+ function lines(text, bold) {
29100
+ return text.split("\n").map((line) => {
29101
+ if (/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/.test(line)) return null;
29102
+ if (/^\s*\|.*\|\s*$/.test(line))
29103
+ return line.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim()).filter(Boolean).join(" \xB7 ");
29104
+ if (/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(line)) return "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
29105
+ const heading = /^\s*#{1,6}\s+(.*)$/.exec(line);
29106
+ if (heading) return bold(heading[1].replace(/\*\*/g, ""));
29107
+ const bullet = /^(\s*)[-*+]\s+(.*)$/.exec(line);
29108
+ if (bullet) return `${bullet[1].length >= 2 ? " \u25E6 " : "\u2022 "}${bullet[2]}`;
29109
+ return line.replace(/^\s*>\s?/, "");
29110
+ }).filter((line) => line !== null).join("\n").replace(/\n{3,}/g, "\n\n");
29111
+ }
29112
+ function inline(text, codeOf, rest) {
29113
+ const codes = [];
29114
+ const held = text.replace(/`{1,3}([^`\n]+)`{1,3}/g, (_whole, code) => `\0${codes.push(code) - 1}\0`);
29115
+ return rest(held).replace(/\u0000(\d+)\u0000/g, (_whole, index) => codeOf(codes[Number(index)]));
29116
+ }
29117
+ function toTelegramHtml(markdown, { inQuote = false } = {}) {
29118
+ return pieces(markdown).map((piece) => {
29119
+ if (piece.code) return inQuote ? `<code>${escapeHtml(piece.text)}</code>` : `<pre>${escapeHtml(piece.text)}</pre>`;
29120
+ return inline(
29121
+ lines(piece.text, (heading) => `**${heading}**`),
29122
+ (code) => `<code>${escapeHtml(code)}</code>`,
29123
+ (text) => holdLinks(
29124
+ escapeHtml(text),
29125
+ (label, url) => `<a href="${url.replace(/"/g, "&quot;")}">${label}</a>`,
29126
+ (prose) => prose.replace(/\*\*([^*\n]+)\*\*/g, "<b>$1</b>").replace(/(^|[\s(])__([^_\n]+)__(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1<b>$2</b>").replace(/~~([^~\n]+)~~/g, "<s>$1</s>").replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1<i>$2</i>").replace(/(^|[\s(])_([^_\s][^_\n]*?)_(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1<i>$2</i>")
29127
+ )
29128
+ );
29129
+ }).join("\n").replace(/\n{3,}/g, "\n\n").trim();
29130
+ }
29131
+ function toSlackMrkdwn(markdown) {
29132
+ return pieces(markdown).map((piece) => {
29133
+ if (piece.code) return `\`\`\`
29134
+ ${escapeHtml(piece.text)}
29135
+ \`\`\``;
29136
+ return inline(
29137
+ lines(piece.text, (heading) => `**${heading}**`),
29138
+ // Escaped like the rest: "<https://x>" or "<!here>" in code would otherwise become a link or a mention.
29139
+ (code) => `\`${escapeHtml(code)}\``,
29140
+ (text) => holdLinks(
29141
+ escapeHtml(text),
29142
+ (label, url) => `<${url}|${label}>`,
29143
+ (prose) => prose.replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1$2").replace(/\*\*([^*\n]+)\*\*/g, "*$1*").replace(/(^|[\s(])__([^_\n]+)__(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1*$2*").replace(/~~([^~\n]+)~~/g, "~$1~").replace(/\u0001/g, "_")
29144
+ )
29145
+ );
29146
+ }).join("\n").replace(/\n{3,}/g, "\n\n").trim();
29147
+ }
29148
+ function gistOf(markdown, skip = "") {
29149
+ const prose = pieces(markdown).filter((piece) => !piece.code).map((piece) => piece.text).join("\n");
29150
+ const strip = (text) => text.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/^\s*#+\s+/, "").replace(/`+|\*\*|~~/g, "").replace(/(^|[\s(])(__|_|\*)([^_*\n]+?)\2(?=[\s),:;!?]|\.(?!\w)|$)/g, "$1$3").replace(/\s+/g, " ").trim();
29151
+ const short2 = (text, max) => text.length > max ? `${text.slice(0, max - 1).trimEnd()}\u2026` : text;
29152
+ const items = prose.split("\n").map((line) => /^\s{0,1}(?:[-*+]|\d+[.)])\s+(.*)$/.exec(line)?.[1]).filter((item) => Boolean(item)).map(strip).filter(Boolean);
29153
+ if (items.length >= 2) {
29154
+ const shown = items.slice(0, 4).map((item) => `\u2022 ${short2(item, 110)}`);
29155
+ return items.length > 4 ? [...shown, `\u2026and ${items.length - 4} more`] : shown;
29156
+ }
29157
+ const opening = strip(
29158
+ prose.split(/\n\s*\n/).map((part) => part.trim()).find((part) => part && !/^\s*(#|\|)/.test(part)) ?? ""
29159
+ );
29160
+ const sentences = opening.split(/(?<=[.?!])\s+/).slice(0, 2).join(" ");
29161
+ const gist = short2(sentences, 260);
29162
+ return gist && strip(skip) !== gist ? [gist] : [];
29163
+ }
29164
+ var escapeHtml;
29165
+ var init_markdown = __esm({
29166
+ "server/src/channels/markdown.ts"() {
29167
+ "use strict";
29168
+ escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
29169
+ }
29170
+ });
29171
+
29172
+ // server/src/presentation.ts
29173
+ function mainQuestion(message) {
29174
+ const paragraphs = plain(message).split(/\n\s*\n/).map((part) => part.trim()).filter(Boolean);
29175
+ const sentencesOf = (part) => part.split(/(?<=[.?!])\s+|\n+/).map((sentence) => sentence.trim()).filter(Boolean);
29176
+ const last = paragraphs[paragraphs.length - 1] ?? "";
29177
+ const sentences = sentencesOf(last);
29178
+ const first = sentences.findIndex((sentence) => sentence.endsWith("?"));
29179
+ if (first !== -1) {
29180
+ const run4 = sentences.slice(first).join(" ");
29181
+ const lastQuestion = [...sentences].reverse().find((sentence) => sentence.endsWith("?"));
29182
+ return { headline: oneLine(run4.length <= 160 ? run4 : lastQuestion), isQuestion: true };
29183
+ }
29184
+ const anyQuestion = [...paragraphs].reverse().flatMap((part) => sentencesOf(part).filter((sentence) => sentence.endsWith("?")).reverse())[0];
29185
+ if (anyQuestion) return { headline: oneLine(anyQuestion), isQuestion: true };
29186
+ return { headline: oneLine(last || "Claude finished its turn."), isQuestion: false };
29187
+ }
29188
+ function target(toolName2, input) {
29189
+ if (!input) return "";
29190
+ const pick = (key) => typeof input[key] === "string" ? input[key] : "";
29191
+ const file = pick("file_path") || pick("notebook_path") || pick("path");
29192
+ if (file) return file.split(/[\\/]/).slice(-2).join("/");
29193
+ const command = pick("command");
29194
+ if (command) return command.split("\n")[0];
29195
+ return pick("url") || pick("pattern") || pick("query") || pick("description") || (toolName2.startsWith("mcp__") ? toolName2.split("__").pop() ?? "" : "");
29196
+ }
29197
+ function present(interaction, sessionTitle2) {
29198
+ const data = interaction.data ?? {};
29199
+ const answerable = interaction.status === "open";
29200
+ const base = { kind: interaction.kind, sessionTitle: sessionTitle2, answerable, quickReplies: [] };
29201
+ switch (interaction.kind) {
29202
+ case "permission": {
29203
+ const tool = String(data.toolName ?? "a tool");
29204
+ const what = target(tool, data.toolInput);
29205
+ const shortTool = tool.startsWith("mcp__") ? tool.replace(/^mcp__/, "").split("__")[0] : tool;
29206
+ return {
29207
+ ...base,
29208
+ headline: oneLine(`${shortTool}${what ? ` \u2192 ${what}` : ""}`, 120),
29209
+ question: data.agent ? `The ${data.agent} agent asks to use ${tool}.` : `Claude asks to use ${tool}.`,
29210
+ choices: [
29211
+ { ref: "o:0", label: "Allow", tone: "primary" },
29212
+ { ref: "o:1", label: "Allow for this session" },
29213
+ { ref: "o:2", label: "Deny", tone: "danger" }
29214
+ ],
29215
+ freeText: "Deny with a reason for Claude...",
29216
+ details: { label: "Full request", text: interaction.body, format: "code" }
29217
+ };
29218
+ }
29219
+ case "question": {
29220
+ const questions = (Array.isArray(data.questions) ? data.questions : []).map((item) => ({
29221
+ header: item?.header ? String(item.header) : void 0,
29222
+ question: String(item?.question ?? ""),
29223
+ options: (Array.isArray(item?.options) ? item.options : []).map((option) => ({
29224
+ label: String(option?.label ?? option),
29225
+ description: option?.description ? String(option.description) : void 0
29226
+ })),
29227
+ multiSelect: Boolean(item?.multiSelect)
29228
+ }));
29229
+ const first = questions[0];
29230
+ const single = questions.length === 1;
29231
+ return {
29232
+ ...base,
29233
+ headline: oneLine(first?.question || interaction.body || interaction.title),
29234
+ question: first?.header,
29235
+ questions,
29236
+ choices: single ? first.options.map((option, index) => ({ ref: `o:${index}`, label: option.label, description: option.description, tone: index === 0 ? "primary" : void 0 })) : [],
29237
+ freeText: "Or answer in your own words..."
29238
+ };
29239
+ }
29240
+ case "turn": {
29241
+ const { headline, isQuestion } = mainQuestion(interaction.body);
29242
+ const replies = isQuestion ? ["Yes", "No", "Continue"] : ["Continue"];
29243
+ return {
29244
+ ...base,
29245
+ headline,
29246
+ choices: [],
29247
+ quickReplies: replies.map((label, index) => ({ ref: `q:${index}`, label })),
29248
+ freeText: "Reply to the session...",
29249
+ details: interaction.body && plain(interaction.body) !== headline ? { label: "Full message", text: interaction.body, format: "markdown" } : void 0,
29250
+ gist: interaction.body ? gistOf(interaction.body, headline) : void 0
29251
+ };
29252
+ }
29253
+ case "mcp":
29254
+ return {
29255
+ ...base,
29256
+ headline: oneLine(`Needs the MCP server '${data.name ?? ""}'`),
29257
+ question: data.reason ? oneLine(String(data.reason), 240) : void 0,
29258
+ choices: [
29259
+ { ref: "o:0", label: "Install & resume", tone: "primary" },
29260
+ { ref: "o:1", label: "Skip" }
29261
+ ],
29262
+ freeText: "Or tell Claude what to do instead...",
29263
+ details: data.command ? { label: "Install command", text: String(data.command), format: "code" } : void 0
29264
+ };
29265
+ case "done": {
29266
+ const deliverables = Object.entries(data.deliverables ?? {}).map(([key, value]) => `- **${key}**: ${typeof value === "string" ? value : JSON.stringify(value)}`).join("\n");
29267
+ return {
29268
+ ...base,
29269
+ answerable: false,
29270
+ headline: oneLine(String(data.summary ?? interaction.body ?? "Task done."), 200),
29271
+ question: data.category ? `Category: ${data.category}` : void 0,
29272
+ choices: [],
29273
+ freeText: null,
29274
+ details: deliverables ? { label: "Deliverables", text: deliverables, format: "markdown" } : void 0
29275
+ };
29276
+ }
29277
+ }
29278
+ }
29279
+ function resolveChoice(interaction, ref) {
29280
+ const [type, raw] = ref.split(":");
29281
+ const index = Number(raw);
29282
+ if (!Number.isInteger(index)) return null;
29283
+ if (type === "q") return present(interaction, "").quickReplies[index]?.label ?? null;
29284
+ if (type !== "o") return null;
29285
+ switch (interaction.kind) {
29286
+ case "permission":
29287
+ return ["1", "2", "3"][index] ?? null;
29288
+ case "question":
29289
+ return String(index + 1);
29290
+ case "mcp":
29291
+ return ["install", "skip"][index] ?? null;
29292
+ default:
29293
+ return null;
29294
+ }
29295
+ }
29296
+ var oneLine, plain;
29297
+ var init_presentation = __esm({
29298
+ "server/src/presentation.ts"() {
29299
+ "use strict";
29300
+ init_markdown();
29301
+ oneLine = (text, max = 160) => {
29302
+ const flat2 = text.replace(/\s+/g, " ").trim();
29303
+ return flat2.length > max ? `${flat2.slice(0, max - 1).trimEnd()}...` : flat2;
29304
+ };
29305
+ plain = (text) => text.replace(/`{3}[\s\S]*?`{3}/g, " ").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/^\s*(#+|>)\s?/gm, "").replace(/`+|\*\*|~~/g, "").replace(/(^|[\s(])(__|_|\*)([^_*\n]+?)\2(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1$3").trim();
29306
+ }
29307
+ });
29308
+
29309
+ // server/src/smallModel.ts
29310
+ import { spawn as spawn2 } from "node:child_process";
29311
+ import fs5 from "node:fs";
29312
+ import path6 from "node:path";
29313
+ function askSmallModel(prompt, timeoutMs = 45e3) {
29314
+ const claude2 = findClaudeCode();
29315
+ if (!claude2 || claudeStatus()?.problem) return Promise.resolve(null);
29316
+ return new Promise((resolve) => {
29317
+ const cwd = path6.join(hubHome, "global");
29318
+ fs5.mkdirSync(cwd, { recursive: true });
29319
+ const child = spawn2(claude2, ["-p", "--model", "haiku", "--tools", "", "--no-session-persistence", "--strict-mcp-config", "--output-format", "text"], {
29320
+ cwd,
29321
+ windowsHide: true,
29322
+ stdio: ["pipe", "pipe", "ignore"]
29323
+ });
29324
+ let out = "";
29325
+ const timer = setTimeout(() => child.kill(), timeoutMs);
29326
+ child.stdout.on("data", (chunk) => out += chunk);
29327
+ child.on("error", () => {
29328
+ clearTimeout(timer);
29329
+ resolve(null);
29330
+ });
29331
+ child.on("close", (code) => {
29332
+ clearTimeout(timer);
29333
+ resolve(code === 0 && out.trim() ? out : null);
29334
+ });
29335
+ child.stdin.end(prompt);
29336
+ });
29337
+ }
29338
+ function jsonIn(answer, open) {
29339
+ if (!answer) return null;
29340
+ const start = answer.indexOf(open);
29341
+ const end = answer.lastIndexOf(open === "[" ? "]" : "}");
29342
+ if (start === -1 || end <= start) return null;
29343
+ try {
29344
+ return JSON.parse(answer.slice(start, end + 1));
29345
+ } catch {
29346
+ return null;
29347
+ }
29348
+ }
29349
+ async function pickNumbers(prompt) {
29350
+ const picked = jsonIn(await askSmallModel(prompt), "[");
29351
+ return picked ? picked.map(Number).filter((number) => Number.isInteger(number) && number > 0) : null;
29352
+ }
29353
+ var init_smallModel = __esm({
29354
+ "server/src/smallModel.ts"() {
29355
+ "use strict";
29356
+ init_claudeCode();
29357
+ init_paths();
29358
+ }
29359
+ });
29360
+
29073
29361
  // server/src/terminals.ts
29074
29362
  import * as pty from "@lydell/node-pty";
29075
29363
  function onTerminalExit(listener) {
@@ -29240,232 +29528,6 @@ var init_terminals = __esm({
29240
29528
  }
29241
29529
  });
29242
29530
 
29243
- // server/src/inventory.ts
29244
- import fs5 from "node:fs";
29245
- import os2 from "node:os";
29246
- import path6 from "node:path";
29247
- function readJson(file) {
29248
- try {
29249
- return JSON.parse(fs5.readFileSync(file, "utf8"));
29250
- } catch {
29251
- return null;
29252
- }
29253
- }
29254
- function frontMatter(text) {
29255
- const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
29256
- if (!match) return {};
29257
- const fields = {};
29258
- let lastKey = "";
29259
- for (const line of match[1].split(/\r?\n/)) {
29260
- const pair = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
29261
- if (pair) {
29262
- lastKey = pair[1];
29263
- fields[lastKey] = pair[2].replace(/^["']|["']$/g, "").replace(/^[>|]-?$/, "");
29264
- } else if (lastKey && /^\s+\S/.test(line)) {
29265
- fields[lastKey] = `${fields[lastKey]} ${line.trim()}`.trim();
29266
- }
29267
- }
29268
- return fields;
29269
- }
29270
- function definition(file, fallbackName, scope, plugin) {
29271
- let text;
29272
- try {
29273
- text = fs5.readFileSync(file, "utf8");
29274
- } catch {
29275
- return null;
29276
- }
29277
- const meta = frontMatter(text);
29278
- const name = meta.name || fallbackName;
29279
- return {
29280
- name: plugin ? `${plugin.split("@")[0]}:${name}` : name,
29281
- description: meta.description ?? "",
29282
- scope,
29283
- plugin,
29284
- path: file,
29285
- model: meta.model || void 0
29286
- };
29287
- }
29288
- function markdownFiles(dir, depth = 3) {
29289
- const found = [];
29290
- const walk = (current, left) => {
29291
- let entries;
29292
- try {
29293
- entries = fs5.readdirSync(current, { withFileTypes: true });
29294
- } catch {
29295
- return;
29296
- }
29297
- for (const entry of entries) {
29298
- const full = path6.join(current, entry.name);
29299
- if (entry.isDirectory() && left > 0) walk(full, left - 1);
29300
- else if (entry.isFile() && entry.name.endsWith(".md")) found.push(full);
29301
- }
29302
- };
29303
- walk(dir, depth);
29304
- return found;
29305
- }
29306
- function agentsIn(dir, scope, plugin) {
29307
- return markdownFiles(dir, 1).map((file) => definition(file, path6.basename(file, ".md"), scope, plugin)).filter((item) => item !== null);
29308
- }
29309
- function skillsIn(dir, scope, plugin) {
29310
- let entries;
29311
- try {
29312
- entries = fs5.readdirSync(dir, { withFileTypes: true });
29313
- } catch {
29314
- return [];
29315
- }
29316
- return entries.filter((entry) => entry.isDirectory()).map((entry) => definition(path6.join(dir, entry.name, "SKILL.md"), entry.name, scope, plugin)).filter((item) => item !== null);
29317
- }
29318
- function commandsIn(dir, scope, plugin) {
29319
- return markdownFiles(dir, 2).map((file) => definition(file, path6.relative(dir, file).replace(/\.md$/, "").replace(/[\\/]/g, ":"), scope, plugin)).filter((item) => item !== null);
29320
- }
29321
- function mcpFrom(servers, scope, source, plugin) {
29322
- if (!servers || typeof servers !== "object") return [];
29323
- return Object.entries(servers).map(([name, config]) => ({
29324
- name: plugin ? `plugin:${plugin.split("@")[0]}:${name}` : name,
29325
- scope,
29326
- plugin,
29327
- transport: String(config?.type ?? (config?.url ? "http" : "stdio")),
29328
- target: config?.url ? String(config.url) : [config?.command, ...Array.isArray(config?.args) ? config.args : []].filter(Boolean).join(" "),
29329
- source
29330
- }));
29331
- }
29332
- function hooksFrom(settings, scope, source, plugin) {
29333
- const hooks = settings?.hooks;
29334
- if (!hooks || typeof hooks !== "object") return [];
29335
- const items = [];
29336
- for (const [event, groups] of Object.entries(hooks)) {
29337
- if (!Array.isArray(groups)) continue;
29338
- for (const group of groups) {
29339
- for (const hook of Array.isArray(group?.hooks) ? group.hooks : []) {
29340
- items.push({
29341
- event,
29342
- matcher: String(group?.matcher ?? ""),
29343
- type: String(hook?.type ?? "command"),
29344
- scope,
29345
- plugin,
29346
- source,
29347
- summary: String(hook?.command ?? hook?.url ?? hook?.prompt ?? hook?.tool ?? "").slice(0, 200)
29348
- });
29349
- }
29350
- }
29351
- }
29352
- return items;
29353
- }
29354
- function localProjectConfig(global3) {
29355
- const projects = global3?.projects ?? {};
29356
- const wanted = [projectRoot(), projectRoot().replace(/\\/g, "/")];
29357
- for (const [key, value] of Object.entries(projects)) {
29358
- if (wanted.some((candidate) => candidate.toLowerCase() === key.toLowerCase())) return value;
29359
- }
29360
- return null;
29361
- }
29362
- function readInventory() {
29363
- const userSettingsFile = path6.join(claudeHome, "settings.json");
29364
- const projectSettingsFile = path6.join(projectRoot(), ".claude", "settings.json");
29365
- const localSettingsFile = path6.join(projectRoot(), ".claude", "settings.local.json");
29366
- const userSettings = readJson(userSettingsFile);
29367
- const projectSettings = readJson(projectSettingsFile);
29368
- const localSettings = readJson(localSettingsFile);
29369
- const globalConfigFile = path6.join(os2.homedir(), ".claude.json");
29370
- const globalConfig = readJson(globalConfigFile);
29371
- const local = localProjectConfig(globalConfig);
29372
- const enabled = {
29373
- ...userSettings?.enabledPlugins ?? {},
29374
- ...projectSettings?.enabledPlugins ?? {},
29375
- ...localSettings?.enabledPlugins ?? {}
29376
- };
29377
- const plugins = [];
29378
- const installed = readJson(path6.join(claudeHome, "plugins", "installed_plugins.json"));
29379
- for (const [id, installs] of Object.entries(installed?.plugins ?? {})) {
29380
- const install = Array.isArray(installs) ? installs[installs.length - 1] : null;
29381
- if (!install?.installPath) continue;
29382
- plugins.push({
29383
- id,
29384
- version: String(install.version ?? ""),
29385
- scope: String(install.scope ?? "user"),
29386
- // Installed plugins are on unless a settings file turns them off.
29387
- enabled: enabled[id] !== false,
29388
- path: install.installPath
29389
- });
29390
- }
29391
- const agents = [
29392
- ...agentsIn(path6.join(claudeHome, "agents"), "user"),
29393
- ...agentsIn(path6.join(projectRoot(), ".claude", "agents"), "project"),
29394
- // No file behind these, so no path: they can be turned off, not edited.
29395
- ...BUILT_IN_AGENTS.map(([name, description]) => ({ name, description, scope: "built-in", path: "" }))
29396
- ];
29397
- const skills = [...skillsIn(path6.join(claudeHome, "skills"), "user"), ...skillsIn(path6.join(projectRoot(), ".claude", "skills"), "project")];
29398
- const commands = [
29399
- ...commandsIn(path6.join(claudeHome, "commands"), "user"),
29400
- ...commandsIn(path6.join(projectRoot(), ".claude", "commands"), "project")
29401
- ];
29402
- const disabledJson = new Set(local?.disabledMcpjsonServers ?? []);
29403
- const mcpServers = [
29404
- ...mcpFrom(globalConfig?.mcpServers, "user", globalConfigFile),
29405
- ...mcpFrom(local?.mcpServers, "local", globalConfigFile),
29406
- ...mcpFrom(readJson(path6.join(projectRoot(), ".mcp.json"))?.mcpServers, "project", path6.join(projectRoot(), ".mcp.json")).map(
29407
- (server2) => ({ ...server2, disabled: disabledJson.has(server2.name) })
29408
- )
29409
- ];
29410
- const hooks = [
29411
- ...hooksFrom(userSettings, "user", userSettingsFile),
29412
- ...hooksFrom(projectSettings, "project", projectSettingsFile),
29413
- ...hooksFrom(localSettings, "local", localSettingsFile)
29414
- ];
29415
- for (const plugin of plugins.filter((item) => item.enabled)) {
29416
- agents.push(...agentsIn(path6.join(plugin.path, "agents"), "plugin", plugin.id));
29417
- skills.push(...skillsIn(path6.join(plugin.path, "skills"), "plugin", plugin.id));
29418
- commands.push(...commandsIn(path6.join(plugin.path, "commands"), "plugin", plugin.id));
29419
- const pluginMcp = readJson(path6.join(plugin.path, ".mcp.json"));
29420
- mcpServers.push(...mcpFrom(pluginMcp?.mcpServers ?? pluginMcp, "plugin", path6.join(plugin.path, ".mcp.json"), plugin.id));
29421
- hooks.push(...hooksFrom(readJson(path6.join(plugin.path, "hooks", "hooks.json")), "plugin", path6.join(plugin.path, "hooks", "hooks.json"), plugin.id));
29422
- }
29423
- return { agents, skills, commands, mcpServers, hooks, plugins };
29424
- }
29425
- function memoryFiles() {
29426
- const files = [];
29427
- const add = (file, label, group, scope, always = false) => {
29428
- const exists = fs5.existsSync(file);
29429
- if (exists || always) files.push({ path: file, label, group, scope, exists });
29430
- };
29431
- add(path6.join(claudeHome, "CLAUDE.md"), "~/.claude/CLAUDE.md", "memory", "user", true);
29432
- add(path6.join(projectRoot(), "CLAUDE.md"), "CLAUDE.md", "memory", "project", true);
29433
- add(path6.join(projectRoot(), ".claude", "CLAUDE.md"), ".claude/CLAUDE.md", "memory", "project");
29434
- add(path6.join(projectRoot(), "CLAUDE.local.md"), "CLAUDE.local.md", "memory", "local");
29435
- for (const file of markdownFiles(path6.join(claudeHome, "rules"))) add(file, `~/.claude/rules/${path6.relative(path6.join(claudeHome, "rules"), file)}`, "rules", "user");
29436
- for (const file of markdownFiles(path6.join(projectRoot(), ".claude", "rules"))) add(file, `.claude/rules/${path6.relative(path6.join(projectRoot(), ".claude", "rules"), file)}`, "rules", "project");
29437
- for (const file of markdownFiles(path6.join(transcriptsDir(), "memory"), 1)) add(file, `memory/${path6.basename(file)}`, "auto-memory", "local");
29438
- const inventory = readInventory();
29439
- for (const agent of inventory.agents.filter((item) => item.scope !== "plugin" && item.path)) add(agent.path, `agent: ${agent.name}`, "agent", agent.scope);
29440
- for (const skill of inventory.skills.filter((item) => item.scope !== "plugin")) add(skill.path, `skill: ${skill.name}`, "skill", skill.scope);
29441
- for (const command of inventory.commands.filter((item) => item.scope !== "plugin")) add(command.path, `command: /${command.name}`, "command", command.scope);
29442
- return files.map((file) => ({ ...file, label: file.label.replace(/\\/g, "/") }));
29443
- }
29444
- function isMemoryFile(file) {
29445
- const wanted = path6.resolve(file).toLowerCase();
29446
- return memoryFiles().some((item) => path6.resolve(item.path).toLowerCase() === wanted);
29447
- }
29448
- function isDefinitionFile(file) {
29449
- const wanted = path6.resolve(file).toLowerCase();
29450
- const inventory = readInventory();
29451
- return [...inventory.agents, ...inventory.skills, ...inventory.commands].some((item) => item.path && path6.resolve(item.path).toLowerCase() === wanted);
29452
- }
29453
- var BUILT_IN_AGENTS;
29454
- var init_inventory = __esm({
29455
- "server/src/inventory.ts"() {
29456
- "use strict";
29457
- init_paths();
29458
- BUILT_IN_AGENTS = [
29459
- ["Explore", "Fast read-only search across the codebase."],
29460
- ["Plan", "Designs an implementation plan."],
29461
- ["general-purpose", "Multi-step research, code search and tasks."],
29462
- ["claude-code-guide", "Answers questions about Claude Code, the Agent SDK and the API."],
29463
- ["statusline-setup", "Configures the status line."],
29464
- ["web-fetch", "Fetches and reads web pages."]
29465
- ];
29466
- }
29467
- });
29468
-
29469
29531
  // server/src/transcripts.ts
29470
29532
  import fs6 from "node:fs";
29471
29533
  import path7 from "node:path";
@@ -29849,414 +29911,6 @@ var init_transcripts = __esm({
29849
29911
  }
29850
29912
  });
29851
29913
 
29852
- // server/src/toolset.ts
29853
- function normaliseToolset(input) {
29854
- const value = input ?? {};
29855
- const list = (items) => [...new Set((Array.isArray(items) ? items : []).map(String).filter(Boolean))].sort();
29856
- return { agents: list(value.agents), skills: list(value.skills), mcp: list(value.mcp), plugins: list(value.plugins) };
29857
- }
29858
- function isEmptyToolset(toolset) {
29859
- return !toolset.agents.length && !toolset.skills.length && !toolset.mcp.length && !toolset.plugins.length;
29860
- }
29861
- function mcpPrefix(server2) {
29862
- if (server2.scope !== "plugin") return `mcp__${toolName(server2.name)}`;
29863
- const [, plugin = "", name = ""] = server2.name.split(":");
29864
- return `mcp__plugin_${toolName(plugin)}_${toolName(name)}`;
29865
- }
29866
- function connectorsSeen() {
29867
- const prefixes = /* @__PURE__ */ new Set();
29868
- for (const summary of listTranscripts()) {
29869
- for (const name of Object.keys(transcriptDetail(summary.id)?.totals.tools ?? {})) {
29870
- const match = /^(mcp__claude_ai_[A-Za-z0-9_-]+?)__/.exec(name);
29871
- if (match) prefixes.add(match[1]);
29872
- }
29873
- }
29874
- return [...prefixes].sort();
29875
- }
29876
- function toolsetCatalog() {
29877
- const inventory = readInventory();
29878
- const items = [];
29879
- for (const plugin of inventory.plugins.filter((item) => item.enabled)) {
29880
- items.push({ kind: "plugins", id: plugin.id, label: plugin.id, description: `v${plugin.version}`, scope: plugin.scope === "user" ? "user" : "project", leavesContext: true });
29881
- }
29882
- for (const agent of inventory.agents) {
29883
- items.push({ kind: "agents", id: agent.name, label: agent.name, description: agent.description, scope: agent.scope, plugin: agent.plugin, leavesContext: true });
29884
- }
29885
- for (const skill of inventory.skills) {
29886
- items.push({ kind: "skills", id: skill.name, label: skill.name, description: skill.description, scope: skill.scope, plugin: skill.plugin, leavesContext: skill.scope !== "plugin" });
29887
- }
29888
- for (const server2 of inventory.mcpServers) {
29889
- items.push({ kind: "mcp", id: mcpPrefix(server2), label: server2.name, description: server2.target, scope: server2.scope, plugin: server2.plugin, leavesContext: false });
29890
- }
29891
- for (const prefix of connectorsSeen()) {
29892
- items.push({ kind: "mcp", id: prefix, label: prefix.replace(/^mcp__claude_ai_/, "claude.ai ").replace(/_/g, " "), description: "claude.ai connector", scope: "connector", leavesContext: false });
29893
- }
29894
- const seen = /* @__PURE__ */ new Set();
29895
- return items.filter((item) => {
29896
- const key = `${item.kind}:${item.id}`;
29897
- if (seen.has(key)) return false;
29898
- seen.add(key);
29899
- return true;
29900
- });
29901
- }
29902
- function toolsetSettings(toolset) {
29903
- if (isEmptyToolset(toolset)) return {};
29904
- const pluginSkills = new Set(readInventory().skills.filter((skill) => skill.scope === "plugin").map((skill) => skill.name));
29905
- const deny = [
29906
- ...toolset.agents.map((name) => `Agent(${name})`),
29907
- ...toolset.skills.filter((name) => pluginSkills.has(name)).map((name) => `Skill(${name})`),
29908
- ...toolset.mcp
29909
- ];
29910
- const overrides = Object.fromEntries(toolset.skills.filter((name) => !pluginSkills.has(name)).map((name) => [name, "off"]));
29911
- const settings = {};
29912
- if (deny.length) settings.permissions = { deny };
29913
- if (Object.keys(overrides).length) settings.skillOverrides = overrides;
29914
- if (toolset.plugins.length) settings.enabledPlugins = Object.fromEntries(toolset.plugins.map((id) => [id, false]));
29915
- return settings;
29916
- }
29917
- function listPresets() {
29918
- return db.prepare("SELECT * FROM presets ORDER BY name COLLATE NOCASE").all().map(toPreset);
29919
- }
29920
- function getPreset(id) {
29921
- const row = db.prepare("SELECT * FROM presets WHERE id = ?").get(id);
29922
- return row ? toPreset(row) : null;
29923
- }
29924
- function defaultToolset() {
29925
- const row = db.prepare("SELECT * FROM presets WHERE is_default = 1 LIMIT 1").get();
29926
- return row ? toPreset(row).toolset : EMPTY_TOOLSET;
29927
- }
29928
- function savePreset(input) {
29929
- const name = String(input.name ?? "").trim();
29930
- if (!name) throw new Error("A preset needs a name.");
29931
- const id = input.id ?? nanoid(10);
29932
- db.transaction(() => {
29933
- if (input.isDefault) db.prepare("UPDATE presets SET is_default = 0").run();
29934
- db.prepare(
29935
- `INSERT INTO presets (id, name, toolset, is_default, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)
29936
- ON CONFLICT(id) DO UPDATE SET name = excluded.name, toolset = excluded.toolset, is_default = excluded.is_default, updated_at = excluded.updated_at`
29937
- ).run(id, name, JSON.stringify(normaliseToolset(input.toolset)), input.isDefault ? 1 : 0, now(), now());
29938
- })();
29939
- broadcast("jobs", {});
29940
- return getPreset(id);
29941
- }
29942
- function setDefaultItem(input) {
29943
- const kind = String(input.kind ?? "");
29944
- const id = String(input.id ?? "").trim();
29945
- if (!(kind in EMPTY_TOOLSET) || !id) throw new Error("Send { kind, id, enabled }.");
29946
- const row = db.prepare("SELECT * FROM presets WHERE is_default = 1 LIMIT 1").get();
29947
- const preset = row ? toPreset(row) : { id: void 0, name: "Default", toolset: EMPTY_TOOLSET };
29948
- const off = preset.toolset[kind].filter((item) => item !== id);
29949
- if (input.enabled !== true) off.push(id);
29950
- return savePreset({ id: preset.id, name: preset.name, toolset: { ...preset.toolset, [kind]: off }, isDefault: true });
29951
- }
29952
- function deletePreset(id) {
29953
- db.prepare("DELETE FROM presets WHERE id = ?").run(id);
29954
- db.prepare("UPDATE jobs SET preset_id = NULL WHERE preset_id = ?").run(id);
29955
- broadcast("jobs", {});
29956
- }
29957
- var EMPTY_TOOLSET, toolName, toPreset;
29958
- var init_toolset = __esm({
29959
- "server/src/toolset.ts"() {
29960
- "use strict";
29961
- init_nanoid();
29962
- init_db();
29963
- init_events();
29964
- init_inventory();
29965
- init_transcripts();
29966
- EMPTY_TOOLSET = { agents: [], skills: [], mcp: [], plugins: [] };
29967
- toolName = (value) => value.replace(/[^A-Za-z0-9_-]/g, "_");
29968
- toPreset = (row) => ({ id: row.id, name: row.name, toolset: normaliseToolset(parseJson(row.toolset, {})), isDefault: Boolean(row.is_default) });
29969
- }
29970
- });
29971
-
29972
- // server/src/channels/markdown.ts
29973
- function pieces(markdown) {
29974
- const out = [];
29975
- let prose = [];
29976
- let code = null;
29977
- for (const line of markdown.split("\n")) {
29978
- if (code) {
29979
- if (/^\s*```/.test(line)) {
29980
- out.push({ code: true, text: code.join("\n") });
29981
- code = null;
29982
- } else code.push(line);
29983
- } else if (/^\s*```[^`]*$/.test(line)) {
29984
- if (prose.length) out.push({ code: false, text: prose.join("\n") });
29985
- prose = [];
29986
- code = [];
29987
- } else prose.push(line);
29988
- }
29989
- if (code) out.push({ code: true, text: code.join("\n") });
29990
- if (prose.length) out.push({ code: false, text: prose.join("\n") });
29991
- return out;
29992
- }
29993
- function holdLinks(text, render2, rewrite) {
29994
- const links = [];
29995
- const held = text.replace(/\[([^\]\n]+)\]\((https?:\/\/[^)\s]+)\)/g, (_whole, label, url) => `${links.push(render2(label, url)) - 1}`);
29996
- return rewrite(held).replace(/\u0002(\d+)\u0002/g, (_whole, index) => links[Number(index)]);
29997
- }
29998
- function lines(text, bold) {
29999
- return text.split("\n").map((line) => {
30000
- if (/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/.test(line)) return null;
30001
- if (/^\s*\|.*\|\s*$/.test(line))
30002
- return line.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim()).filter(Boolean).join(" \xB7 ");
30003
- if (/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(line)) return "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
30004
- const heading = /^\s*#{1,6}\s+(.*)$/.exec(line);
30005
- if (heading) return bold(heading[1].replace(/\*\*/g, ""));
30006
- const bullet = /^(\s*)[-*+]\s+(.*)$/.exec(line);
30007
- if (bullet) return `${bullet[1].length >= 2 ? " \u25E6 " : "\u2022 "}${bullet[2]}`;
30008
- return line.replace(/^\s*>\s?/, "");
30009
- }).filter((line) => line !== null).join("\n").replace(/\n{3,}/g, "\n\n");
30010
- }
30011
- function inline(text, codeOf, rest) {
30012
- const codes = [];
30013
- const held = text.replace(/`{1,3}([^`\n]+)`{1,3}/g, (_whole, code) => `\0${codes.push(code) - 1}\0`);
30014
- return rest(held).replace(/\u0000(\d+)\u0000/g, (_whole, index) => codeOf(codes[Number(index)]));
30015
- }
30016
- function toTelegramHtml(markdown, { inQuote = false } = {}) {
30017
- return pieces(markdown).map((piece) => {
30018
- if (piece.code) return inQuote ? `<code>${escapeHtml(piece.text)}</code>` : `<pre>${escapeHtml(piece.text)}</pre>`;
30019
- return inline(
30020
- lines(piece.text, (heading) => `**${heading}**`),
30021
- (code) => `<code>${escapeHtml(code)}</code>`,
30022
- (text) => holdLinks(
30023
- escapeHtml(text),
30024
- (label, url) => `<a href="${url.replace(/"/g, "&quot;")}">${label}</a>`,
30025
- (prose) => prose.replace(/\*\*([^*\n]+)\*\*/g, "<b>$1</b>").replace(/(^|[\s(])__([^_\n]+)__(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1<b>$2</b>").replace(/~~([^~\n]+)~~/g, "<s>$1</s>").replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1<i>$2</i>").replace(/(^|[\s(])_([^_\s][^_\n]*?)_(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1<i>$2</i>")
30026
- )
30027
- );
30028
- }).join("\n").replace(/\n{3,}/g, "\n\n").trim();
30029
- }
30030
- function toSlackMrkdwn(markdown) {
30031
- return pieces(markdown).map((piece) => {
30032
- if (piece.code) return `\`\`\`
30033
- ${escapeHtml(piece.text)}
30034
- \`\`\``;
30035
- return inline(
30036
- lines(piece.text, (heading) => `**${heading}**`),
30037
- // Escaped like the rest: "<https://x>" or "<!here>" in code would otherwise become a link or a mention.
30038
- (code) => `\`${escapeHtml(code)}\``,
30039
- (text) => holdLinks(
30040
- escapeHtml(text),
30041
- (label, url) => `<${url}|${label}>`,
30042
- (prose) => prose.replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1$2").replace(/\*\*([^*\n]+)\*\*/g, "*$1*").replace(/(^|[\s(])__([^_\n]+)__(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1*$2*").replace(/~~([^~\n]+)~~/g, "~$1~").replace(/\u0001/g, "_")
30043
- )
30044
- );
30045
- }).join("\n").replace(/\n{3,}/g, "\n\n").trim();
30046
- }
30047
- function gistOf(markdown, skip = "") {
30048
- const prose = pieces(markdown).filter((piece) => !piece.code).map((piece) => piece.text).join("\n");
30049
- const strip = (text) => text.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/^\s*#+\s+/, "").replace(/`+|\*\*|~~/g, "").replace(/(^|[\s(])(__|_|\*)([^_*\n]+?)\2(?=[\s),:;!?]|\.(?!\w)|$)/g, "$1$3").replace(/\s+/g, " ").trim();
30050
- const short2 = (text, max) => text.length > max ? `${text.slice(0, max - 1).trimEnd()}\u2026` : text;
30051
- const items = prose.split("\n").map((line) => /^\s{0,1}(?:[-*+]|\d+[.)])\s+(.*)$/.exec(line)?.[1]).filter((item) => Boolean(item)).map(strip).filter(Boolean);
30052
- if (items.length >= 2) {
30053
- const shown = items.slice(0, 4).map((item) => `\u2022 ${short2(item, 110)}`);
30054
- return items.length > 4 ? [...shown, `\u2026and ${items.length - 4} more`] : shown;
30055
- }
30056
- const opening = strip(
30057
- prose.split(/\n\s*\n/).map((part) => part.trim()).find((part) => part && !/^\s*(#|\|)/.test(part)) ?? ""
30058
- );
30059
- const sentences = opening.split(/(?<=[.?!])\s+/).slice(0, 2).join(" ");
30060
- const gist = short2(sentences, 260);
30061
- return gist && strip(skip) !== gist ? [gist] : [];
30062
- }
30063
- var escapeHtml;
30064
- var init_markdown = __esm({
30065
- "server/src/channels/markdown.ts"() {
30066
- "use strict";
30067
- escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
30068
- }
30069
- });
30070
-
30071
- // server/src/presentation.ts
30072
- function mainQuestion(message) {
30073
- const paragraphs = plain(message).split(/\n\s*\n/).map((part) => part.trim()).filter(Boolean);
30074
- const sentencesOf = (part) => part.split(/(?<=[.?!])\s+|\n+/).map((sentence) => sentence.trim()).filter(Boolean);
30075
- const last = paragraphs[paragraphs.length - 1] ?? "";
30076
- const sentences = sentencesOf(last);
30077
- const first = sentences.findIndex((sentence) => sentence.endsWith("?"));
30078
- if (first !== -1) {
30079
- const run4 = sentences.slice(first).join(" ");
30080
- const lastQuestion = [...sentences].reverse().find((sentence) => sentence.endsWith("?"));
30081
- return { headline: oneLine(run4.length <= 160 ? run4 : lastQuestion), isQuestion: true };
30082
- }
30083
- const anyQuestion = [...paragraphs].reverse().flatMap((part) => sentencesOf(part).filter((sentence) => sentence.endsWith("?")).reverse())[0];
30084
- if (anyQuestion) return { headline: oneLine(anyQuestion), isQuestion: true };
30085
- return { headline: oneLine(last || "Claude finished its turn."), isQuestion: false };
30086
- }
30087
- function target(toolName2, input) {
30088
- if (!input) return "";
30089
- const pick = (key) => typeof input[key] === "string" ? input[key] : "";
30090
- const file = pick("file_path") || pick("notebook_path") || pick("path");
30091
- if (file) return file.split(/[\\/]/).slice(-2).join("/");
30092
- const command = pick("command");
30093
- if (command) return command.split("\n")[0];
30094
- return pick("url") || pick("pattern") || pick("query") || pick("description") || (toolName2.startsWith("mcp__") ? toolName2.split("__").pop() ?? "" : "");
30095
- }
30096
- function present(interaction, sessionTitle2) {
30097
- const data = interaction.data ?? {};
30098
- const answerable = interaction.status === "open";
30099
- const base = { kind: interaction.kind, sessionTitle: sessionTitle2, answerable, quickReplies: [] };
30100
- switch (interaction.kind) {
30101
- case "permission": {
30102
- const tool = String(data.toolName ?? "a tool");
30103
- const what = target(tool, data.toolInput);
30104
- const shortTool = tool.startsWith("mcp__") ? tool.replace(/^mcp__/, "").split("__")[0] : tool;
30105
- return {
30106
- ...base,
30107
- headline: oneLine(`${shortTool}${what ? ` \u2192 ${what}` : ""}`, 120),
30108
- question: data.agent ? `The ${data.agent} agent asks to use ${tool}.` : `Claude asks to use ${tool}.`,
30109
- choices: [
30110
- { ref: "o:0", label: "Allow", tone: "primary" },
30111
- { ref: "o:1", label: "Allow for this session" },
30112
- { ref: "o:2", label: "Deny", tone: "danger" }
30113
- ],
30114
- freeText: "Deny with a reason for Claude...",
30115
- details: { label: "Full request", text: interaction.body, format: "code" }
30116
- };
30117
- }
30118
- case "question": {
30119
- const questions = (Array.isArray(data.questions) ? data.questions : []).map((item) => ({
30120
- header: item?.header ? String(item.header) : void 0,
30121
- question: String(item?.question ?? ""),
30122
- options: (Array.isArray(item?.options) ? item.options : []).map((option) => ({
30123
- label: String(option?.label ?? option),
30124
- description: option?.description ? String(option.description) : void 0
30125
- })),
30126
- multiSelect: Boolean(item?.multiSelect)
30127
- }));
30128
- const first = questions[0];
30129
- const single = questions.length === 1;
30130
- return {
30131
- ...base,
30132
- headline: oneLine(first?.question || interaction.body || interaction.title),
30133
- question: first?.header,
30134
- questions,
30135
- choices: single ? first.options.map((option, index) => ({ ref: `o:${index}`, label: option.label, description: option.description, tone: index === 0 ? "primary" : void 0 })) : [],
30136
- freeText: "Or answer in your own words..."
30137
- };
30138
- }
30139
- case "turn": {
30140
- const { headline, isQuestion } = mainQuestion(interaction.body);
30141
- const replies = isQuestion ? ["Yes", "No", "Continue"] : ["Continue"];
30142
- return {
30143
- ...base,
30144
- headline,
30145
- choices: [],
30146
- quickReplies: replies.map((label, index) => ({ ref: `q:${index}`, label })),
30147
- freeText: "Reply to the session...",
30148
- details: interaction.body && plain(interaction.body) !== headline ? { label: "Full message", text: interaction.body, format: "markdown" } : void 0,
30149
- gist: interaction.body ? gistOf(interaction.body, headline) : void 0
30150
- };
30151
- }
30152
- case "mcp":
30153
- return {
30154
- ...base,
30155
- headline: oneLine(`Needs the MCP server '${data.name ?? ""}'`),
30156
- question: data.reason ? oneLine(String(data.reason), 240) : void 0,
30157
- choices: [
30158
- { ref: "o:0", label: "Install & resume", tone: "primary" },
30159
- { ref: "o:1", label: "Skip" }
30160
- ],
30161
- freeText: "Or tell Claude what to do instead...",
30162
- details: data.command ? { label: "Install command", text: String(data.command), format: "code" } : void 0
30163
- };
30164
- case "done": {
30165
- const deliverables = Object.entries(data.deliverables ?? {}).map(([key, value]) => `- **${key}**: ${typeof value === "string" ? value : JSON.stringify(value)}`).join("\n");
30166
- return {
30167
- ...base,
30168
- answerable: false,
30169
- headline: oneLine(String(data.summary ?? interaction.body ?? "Task done."), 200),
30170
- question: data.category ? `Category: ${data.category}` : void 0,
30171
- choices: [],
30172
- freeText: null,
30173
- details: deliverables ? { label: "Deliverables", text: deliverables, format: "markdown" } : void 0
30174
- };
30175
- }
30176
- }
30177
- }
30178
- function resolveChoice(interaction, ref) {
30179
- const [type, raw] = ref.split(":");
30180
- const index = Number(raw);
30181
- if (!Number.isInteger(index)) return null;
30182
- if (type === "q") return present(interaction, "").quickReplies[index]?.label ?? null;
30183
- if (type !== "o") return null;
30184
- switch (interaction.kind) {
30185
- case "permission":
30186
- return ["1", "2", "3"][index] ?? null;
30187
- case "question":
30188
- return String(index + 1);
30189
- case "mcp":
30190
- return ["install", "skip"][index] ?? null;
30191
- default:
30192
- return null;
30193
- }
30194
- }
30195
- var oneLine, plain;
30196
- var init_presentation = __esm({
30197
- "server/src/presentation.ts"() {
30198
- "use strict";
30199
- init_markdown();
30200
- oneLine = (text, max = 160) => {
30201
- const flat2 = text.replace(/\s+/g, " ").trim();
30202
- return flat2.length > max ? `${flat2.slice(0, max - 1).trimEnd()}...` : flat2;
30203
- };
30204
- plain = (text) => text.replace(/`{3}[\s\S]*?`{3}/g, " ").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/^\s*(#+|>)\s?/gm, "").replace(/`+|\*\*|~~/g, "").replace(/(^|[\s(])(__|_|\*)([^_*\n]+?)\2(?=[\s),:;!?]|\.(?!\w)|$)/gm, "$1$3").trim();
30205
- }
30206
- });
30207
-
30208
- // server/src/smallModel.ts
30209
- import { spawn as spawn3 } from "node:child_process";
30210
- import fs7 from "node:fs";
30211
- import path8 from "node:path";
30212
- function askSmallModel(prompt, timeoutMs = 45e3) {
30213
- const claude2 = findClaudeCode();
30214
- if (!claude2 || claudeStatus()?.problem) return Promise.resolve(null);
30215
- return new Promise((resolve) => {
30216
- const cwd = path8.join(hubHome, "global");
30217
- fs7.mkdirSync(cwd, { recursive: true });
30218
- const child = spawn3(claude2, ["-p", "--model", "haiku", "--tools", "", "--no-session-persistence", "--strict-mcp-config", "--output-format", "text"], {
30219
- cwd,
30220
- windowsHide: true,
30221
- stdio: ["pipe", "pipe", "ignore"]
30222
- });
30223
- let out = "";
30224
- const timer = setTimeout(() => child.kill(), timeoutMs);
30225
- child.stdout.on("data", (chunk) => out += chunk);
30226
- child.on("error", () => {
30227
- clearTimeout(timer);
30228
- resolve(null);
30229
- });
30230
- child.on("close", (code) => {
30231
- clearTimeout(timer);
30232
- resolve(code === 0 && out.trim() ? out : null);
30233
- });
30234
- child.stdin.end(prompt);
30235
- });
30236
- }
30237
- function jsonIn(answer, open) {
30238
- if (!answer) return null;
30239
- const start = answer.indexOf(open);
30240
- const end = answer.lastIndexOf(open === "[" ? "]" : "}");
30241
- if (start === -1 || end <= start) return null;
30242
- try {
30243
- return JSON.parse(answer.slice(start, end + 1));
30244
- } catch {
30245
- return null;
30246
- }
30247
- }
30248
- async function pickNumbers(prompt) {
30249
- const picked = jsonIn(await askSmallModel(prompt), "[");
30250
- return picked ? picked.map(Number).filter((number) => Number.isInteger(number) && number > 0) : null;
30251
- }
30252
- var init_smallModel = __esm({
30253
- "server/src/smallModel.ts"() {
30254
- "use strict";
30255
- init_claudeCode();
30256
- init_paths();
30257
- }
30258
- });
30259
-
30260
29914
  // server/src/channels/commands.ts
30261
29915
  var commands_exports = {};
30262
29916
  __export(commands_exports, {
@@ -31539,6 +31193,7 @@ __export(interactions_exports, {
31539
31193
  chooseInteraction: () => chooseInteraction,
31540
31194
  closeOpen: () => closeOpen,
31541
31195
  createInteraction: () => createInteraction,
31196
+ dismissInteraction: () => dismissInteraction,
31542
31197
  getInteraction: () => getInteraction,
31543
31198
  listInteractions: () => listInteractions,
31544
31199
  routeReply: () => routeReply,
@@ -31607,6 +31262,15 @@ function closeOpen(sessionId, by, kinds) {
31607
31262
  }
31608
31263
  broadcast("interactions", { sessionId });
31609
31264
  }
31265
+ function dismissInteraction(id) {
31266
+ const interaction = getInteraction(id);
31267
+ if (!interaction) throw new AnswerError("No such interaction.");
31268
+ if (interaction.status !== "open") return interaction;
31269
+ db.prepare("UPDATE interactions SET status = 'closed', answered_by = 'dismissed', updated_at = ? WHERE id = ?").run(now(), id);
31270
+ void acknowledgeOnChannels(interaction, "Dismissed on the dashboard.");
31271
+ broadcast("interactions", { sessionId: interaction.sessionId });
31272
+ return getInteraction(id);
31273
+ }
31610
31274
  async function answerQuestion(interaction, answer) {
31611
31275
  const terminal = terminalForSession(interaction.sessionId);
31612
31276
  if (interaction.data.trust) {
@@ -31785,8 +31449,8 @@ __export(projects_exports, {
31785
31449
  touchProject: () => touchProject
31786
31450
  });
31787
31451
  import Database2 from "better-sqlite3";
31788
- import fs8 from "node:fs";
31789
- import path9 from "node:path";
31452
+ import fs7 from "node:fs";
31453
+ import path8 from "node:path";
31790
31454
  function listProjects() {
31791
31455
  return globalDb.prepare("SELECT * FROM projects ORDER BY opened_at DESC").all().map(toInfo);
31792
31456
  }
@@ -31803,15 +31467,15 @@ function globalProject() {
31803
31467
  }
31804
31468
  function bootGlobal() {
31805
31469
  if (global2) return global2.project;
31806
- const root2 = path9.join(hubHome, GLOBAL_ID);
31807
- fs8.mkdirSync(root2, { recursive: true });
31470
+ const root2 = path8.join(hubHome, GLOBAL_ID);
31471
+ fs7.mkdirSync(root2, { recursive: true });
31808
31472
  const project = {
31809
31473
  id: GLOBAL_ID,
31810
31474
  name: "Global",
31811
31475
  root: root2,
31812
- transcriptsDir: path9.join(claudeHome, "projects", projectSlug(root2)),
31476
+ transcriptsDir: path8.join(claudeHome, "projects", projectSlug(root2)),
31813
31477
  dataDir: root2,
31814
- db: openProjectDb(path9.join(root2, "hub.db"))
31478
+ db: openProjectDb(path8.join(root2, "hub.db"))
31815
31479
  };
31816
31480
  const stops = withProject(project, () => {
31817
31481
  recoverRuns();
@@ -31828,7 +31492,7 @@ function freeId(name, root2) {
31828
31492
  const taken = new Set(globalDb.prepare("SELECT id FROM projects").all().map((row) => row.id));
31829
31493
  const free = (id) => {
31830
31494
  if (taken.has(id) || RESERVED.has(id)) return false;
31831
- if (!fs8.existsSync(path9.join(projectsDir, id))) return true;
31495
+ if (!fs7.existsSync(path8.join(projectsDir, id))) return true;
31832
31496
  const owner = ownerOf(id);
31833
31497
  return owner !== null && samePath(owner, root2);
31834
31498
  };
@@ -31836,8 +31500,8 @@ function freeId(name, root2) {
31836
31500
  for (let n2 = 2; ; n2++) if (free(`${base}-${n2}`)) return `${base}-${n2}`;
31837
31501
  }
31838
31502
  function importOldDatabase(root2, file) {
31839
- const old = path9.join(root2, ".clauder-hub", "data", "hub.db");
31840
- if (!fs8.existsSync(old) || fs8.existsSync(file)) return;
31503
+ const old = path8.join(root2, ".clauder-hub", "data", "hub.db");
31504
+ if (!fs7.existsSync(old) || fs7.existsSync(file)) return;
31841
31505
  const source = new Database2(old, { readonly: true, fileMustExist: true });
31842
31506
  try {
31843
31507
  source.prepare("VACUUM INTO ?").run(file);
@@ -31846,7 +31510,7 @@ function importOldDatabase(root2, file) {
31846
31510
  for (const row of overrides) insert.run(row.key, row.text, row.updated_at);
31847
31511
  console.log(` imported : ${old}`);
31848
31512
  } catch (error) {
31849
- fs8.rmSync(file, { force: true });
31513
+ fs7.rmSync(file, { force: true });
31850
31514
  console.error(`[projects] could not import ${old}:`, error.message);
31851
31515
  } finally {
31852
31516
  source.close();
@@ -31855,16 +31519,16 @@ function importOldDatabase(root2, file) {
31855
31519
  function boot(row) {
31856
31520
  const running = live.get(row.id);
31857
31521
  if (running) return running.project;
31858
- const dataDir = path9.join(projectsDir, row.id);
31859
- fs8.mkdirSync(dataDir, { recursive: true });
31860
- if (ownerOf(row.id) === null) fs8.writeFileSync(path9.join(dataDir, OWNER_FILE), row.root, "utf8");
31861
- const file = path9.join(dataDir, "hub.db");
31522
+ const dataDir = path8.join(projectsDir, row.id);
31523
+ fs7.mkdirSync(dataDir, { recursive: true });
31524
+ if (ownerOf(row.id) === null) fs7.writeFileSync(path8.join(dataDir, OWNER_FILE), row.root, "utf8");
31525
+ const file = path8.join(dataDir, "hub.db");
31862
31526
  importOldDatabase(row.root, file);
31863
31527
  const project = {
31864
31528
  id: row.id,
31865
31529
  name: row.name,
31866
31530
  root: row.root,
31867
- transcriptsDir: path9.join(claudeHome, "projects", projectSlug(row.root)),
31531
+ transcriptsDir: path8.join(claudeHome, "projects", projectSlug(row.root)),
31868
31532
  dataDir,
31869
31533
  db: openProjectDb(file)
31870
31534
  };
@@ -31892,7 +31556,7 @@ function boot(row) {
31892
31556
  }
31893
31557
  function bootProjects() {
31894
31558
  for (const row of globalDb.prepare("SELECT * FROM projects").all()) {
31895
- if (!fs8.existsSync(row.root)) continue;
31559
+ if (!fs7.existsSync(row.root)) continue;
31896
31560
  try {
31897
31561
  boot(row);
31898
31562
  } catch (error) {
@@ -31903,13 +31567,13 @@ function bootProjects() {
31903
31567
  }
31904
31568
  function addProject(input) {
31905
31569
  if (typeof input !== "string" || !input.trim()) throw new Error("Send the folder's full path.");
31906
- const typed = path9.resolve(input.trim());
31907
- if (!fs8.existsSync(typed) || !fs8.statSync(typed).isDirectory()) throw new Error(`${typed} is not a folder.`);
31908
- const root2 = fs8.realpathSync.native(typed);
31570
+ const typed = path8.resolve(input.trim());
31571
+ if (!fs7.existsSync(typed) || !fs7.statSync(typed).isDirectory()) throw new Error(`${typed} is not a folder.`);
31572
+ const root2 = fs7.realpathSync.native(typed);
31909
31573
  const rows = globalDb.prepare("SELECT * FROM projects").all();
31910
31574
  let row = rows.find((item) => samePath(item.root, root2));
31911
31575
  if (!row) {
31912
- const name = path9.basename(root2) || root2;
31576
+ const name = path8.basename(root2) || root2;
31913
31577
  row = { id: freeId(name, root2), root: root2, name, added_at: now(), opened_at: now() };
31914
31578
  boot(row);
31915
31579
  globalDb.prepare("INSERT INTO projects (id, root, name, added_at, opened_at) VALUES (?, ?, ?, ?, ?)").run(row.id, row.root, row.name, row.added_at, row.opened_at);
@@ -31960,13 +31624,13 @@ var init_projects = __esm({
31960
31624
  init_terminals();
31961
31625
  init_transcripts();
31962
31626
  live = /* @__PURE__ */ new Map();
31963
- toInfo = (row) => ({ id: row.id, name: row.name, root: row.root, addedAt: row.added_at, openedAt: row.opened_at, exists: fs8.existsSync(row.root) });
31627
+ toInfo = (row) => ({ id: row.id, name: row.name, root: row.root, addedAt: row.added_at, openedAt: row.opened_at, exists: fs7.existsSync(row.root) });
31964
31628
  global2 = null;
31965
31629
  samePath = (a, b2) => process.platform === "linux" ? a === b2 : a.toLowerCase() === b2.toLowerCase();
31966
31630
  OWNER_FILE = "root.txt";
31967
31631
  ownerOf = (id) => {
31968
31632
  try {
31969
- return fs8.readFileSync(path9.join(projectsDir, id, OWNER_FILE), "utf8").trim();
31633
+ return fs7.readFileSync(path8.join(projectsDir, id, OWNER_FILE), "utf8").trim();
31970
31634
  } catch {
31971
31635
  return null;
31972
31636
  }
@@ -31980,29 +31644,29 @@ var folderFinder_exports = {};
31980
31644
  __export(folderFinder_exports, {
31981
31645
  findFolders: () => findFolders
31982
31646
  });
31983
- import fs9 from "node:fs";
31984
- import os3 from "node:os";
31985
- import path10 from "node:path";
31647
+ import fs8 from "node:fs";
31648
+ import os2 from "node:os";
31649
+ import path9 from "node:path";
31986
31650
  function isProject(dir, entries) {
31987
31651
  return entries.some((entry) => MARKERS.includes(entry.name) || entry.isFile() && PROJECT_FILE.test(entry.name));
31988
31652
  }
31989
31653
  function roots() {
31990
- const home = os3.homedir();
31654
+ const home = os2.homedir();
31991
31655
  const found = /* @__PURE__ */ new Set();
31992
31656
  for (const project of allContexts()) {
31993
31657
  if (isGlobal(project)) continue;
31994
- found.add(path10.dirname(project.root));
31995
- found.add(path10.dirname(path10.dirname(project.root)));
31658
+ found.add(path9.dirname(project.root));
31659
+ found.add(path9.dirname(path9.dirname(project.root)));
31996
31660
  }
31997
- for (const dir of CODE_DIRS) found.add(path10.join(home, dir));
31661
+ for (const dir of CODE_DIRS) found.add(path9.join(home, dir));
31998
31662
  if (process.platform === "win32") {
31999
31663
  for (const letter of "CDEFG") {
32000
31664
  const drive = `${letter}:\\`;
32001
- if (!fs9.existsSync(drive)) continue;
32002
- for (const dir of CODE_DIRS) found.add(path10.join(drive, dir));
31665
+ if (!fs8.existsSync(drive)) continue;
31666
+ for (const dir of CODE_DIRS) found.add(path9.join(drive, dir));
32003
31667
  }
32004
31668
  }
32005
- const real = [...found].filter((dir) => dir !== path10.parse(dir).root && fs9.existsSync(dir)).map((dir) => fs9.realpathSync.native(dir));
31669
+ const real = [...found].filter((dir) => dir !== path9.parse(dir).root && fs8.existsSync(dir)).map((dir) => fs8.realpathSync.native(dir));
32006
31670
  return [...new Set(real)];
32007
31671
  }
32008
31672
  function scan() {
@@ -32014,22 +31678,22 @@ function scan() {
32014
31678
  visited += 1;
32015
31679
  let entries;
32016
31680
  try {
32017
- entries = fs9.readdirSync(dir, { withFileTypes: true });
31681
+ entries = fs8.readdirSync(dir, { withFileTypes: true });
32018
31682
  } catch {
32019
31683
  return;
32020
31684
  }
32021
31685
  if (depth > 0 && isProject(dir, entries)) {
32022
31686
  let mtimeMs = 0;
32023
31687
  try {
32024
- mtimeMs = fs9.statSync(dir).mtimeMs;
31688
+ mtimeMs = fs8.statSync(dir).mtimeMs;
32025
31689
  } catch {
32026
31690
  }
32027
- folders.set(dir.toLowerCase(), { path: dir, name: path10.basename(dir), mtimeMs });
31691
+ folders.set(dir.toLowerCase(), { path: dir, name: path9.basename(dir), mtimeMs });
32028
31692
  return;
32029
31693
  }
32030
31694
  for (const entry of entries) {
32031
31695
  if (!entry.isDirectory() || entry.name.startsWith(".") || SKIP.has(entry.name.toLowerCase())) continue;
32032
- walk(path10.join(dir, entry.name), depth + 1);
31696
+ walk(path9.join(dir, entry.name), depth + 1);
32033
31697
  }
32034
31698
  };
32035
31699
  for (const root2 of roots()) walk(root2, 0);
@@ -32079,7 +31743,7 @@ var init_folderFinder = __esm({
32079
31743
  MARKERS = [".git", "package.json", "pyproject.toml", "requirements.txt", "go.mod", "Cargo.toml", "pom.xml", "build.gradle", "composer.json", "Gemfile", "CLAUDE.md", ".claude"];
32080
31744
  PROJECT_FILE = /\.(sln|csproj)$/i;
32081
31745
  SKIP = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "out", "bin", "obj", "target", "vendor", "venv", ".venv", "__pycache__", "appdata", "library", "application data", "$recycle.bin", "program files", "program files (x86)", "windows", "programdata"]);
32082
- CODE_DIRS = ["source", "src", "repos", "projects", "code", "dev", "work", "git", "github", "workspace", "documents", "desktop", path10.join("source", "repos"), "source code"];
31746
+ CODE_DIRS = ["source", "src", "repos", "projects", "code", "dev", "work", "git", "github", "workspace", "documents", "desktop", path9.join("source", "repos"), "source code"];
32083
31747
  cache2 = null;
32084
31748
  CACHE_MS = 5 * 6e4;
32085
31749
  }
@@ -32170,6 +31834,47 @@ function stopChannels() {
32170
31834
  adapters.delete(key);
32171
31835
  }
32172
31836
  }
31837
+ function readSetting(key, fallback) {
31838
+ const row = db.prepare("SELECT value FROM settings WHERE key = ?").get(key);
31839
+ return parseJson(row?.value, fallback);
31840
+ }
31841
+ function writeSetting(key, value) {
31842
+ db.prepare("INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at").run(
31843
+ key,
31844
+ JSON.stringify(value),
31845
+ now()
31846
+ );
31847
+ }
31848
+ function notificationsPaused() {
31849
+ return readSetting("notificationsPaused", false) === true;
31850
+ }
31851
+ function setNotificationsPaused(paused) {
31852
+ writeSetting("notificationsPaused", paused);
31853
+ broadcast("channels", {});
31854
+ return { paused };
31855
+ }
31856
+ function notifyKinds() {
31857
+ const saved = readSetting("notifyKinds", null);
31858
+ if (saved) return saved.filter((kind) => INTERACTION_KINDS.includes(kind));
31859
+ const channels = allChannels();
31860
+ return channels.length ? INTERACTION_KINDS.filter((kind) => channels.some((channel) => channel.kinds.includes(kind))) : [...INTERACTION_KINDS];
31861
+ }
31862
+ function setNotifyKinds(kinds) {
31863
+ writeSetting("notifyKinds", kinds.filter((kind) => INTERACTION_KINDS.includes(kind)));
31864
+ broadcast("channels", {});
31865
+ return notifyKinds();
31866
+ }
31867
+ function quietSessions() {
31868
+ return readSetting("quietSessions", []);
31869
+ }
31870
+ function setSessionQuiet(sessionId, quiet) {
31871
+ const next = new Set(quietSessions());
31872
+ if (quiet) next.add(sessionId);
31873
+ else next.delete(sessionId);
31874
+ writeSetting("quietSessions", [...next]);
31875
+ broadcast("sessions", { sessionId });
31876
+ return { quiet };
31877
+ }
32173
31878
  function mutedProjects() {
32174
31879
  const global3 = globalContext();
32175
31880
  if (!global3) return [];
@@ -32222,8 +31927,9 @@ function messageText(interaction, session) {
32222
31927
  async function deliver(interaction, sessionTitle2, projectId) {
32223
31928
  const text = messageText(interaction, sessionTitle2);
32224
31929
  const presented = present(interaction, sessionTitle2);
31930
+ if (!notifyKinds().includes(interaction.kind)) return;
32225
31931
  for (const channel of allChannels()) {
32226
- if (!channel.enabled || !channel.kinds.includes(interaction.kind)) continue;
31932
+ if (!channel.enabled) continue;
32227
31933
  const adapter = adapters.get(adapterKey(channel.id));
32228
31934
  if (!adapter) continue;
32229
31935
  const thread = db.prepare("SELECT thread FROM channel_threads WHERE channel_id = ? AND session_id = ?").get(channel.id, interaction.sessionId)?.thread ?? null;
@@ -32264,12 +31970,14 @@ async function deliver(interaction, sessionTitle2, projectId) {
32264
31970
  }
32265
31971
  }
32266
31972
  async function notifyChannels(interaction, sessionTitle2) {
31973
+ if (notificationsPaused() || quietSessions().includes(interaction.sessionId)) return;
32267
31974
  await deliver(interaction, sessionTitle2, null);
32268
31975
  broadcast("channels", {});
32269
31976
  const project = currentProject();
32270
31977
  const global3 = globalContext();
32271
31978
  if (!global3 || isGlobal(project) || mutedProjects().includes(project.id)) return;
32272
31979
  await withProject(global3, async () => {
31980
+ if (notificationsPaused()) return;
32273
31981
  await deliver(interaction, `${project.name} \xB7 ${sessionTitle2}`, project.id);
32274
31982
  broadcast("channels", {});
32275
31983
  });
@@ -32579,6 +32287,461 @@ var init_channels = __esm({
32579
32287
  }
32580
32288
  });
32581
32289
 
32290
+ // server/src/sessionFiles.ts
32291
+ import fs9 from "node:fs";
32292
+ import os3 from "node:os";
32293
+ import path10 from "node:path";
32294
+ function checkId(id) {
32295
+ if (!UUID.test(id)) throw new Error("Not a session id.");
32296
+ }
32297
+ function transcriptFile(id) {
32298
+ return path10.join(transcriptsDir(), `${id}.jsonl`);
32299
+ }
32300
+ function setSessionTitle(id, title) {
32301
+ checkId(id);
32302
+ const name = title.replace(/\s+/g, " ").trim();
32303
+ if (!name) throw new Error("The name is empty.");
32304
+ if (name.length > 200) throw new Error("Keep the name under 200 characters.");
32305
+ const file = transcriptFile(id);
32306
+ if (!fs9.existsSync(file)) throw new Error("This session has no transcript yet; give it a moment to start.");
32307
+ const size = fs9.statSync(file).size;
32308
+ let lead = "";
32309
+ if (size > 0) {
32310
+ const fd = fs9.openSync(file, "r");
32311
+ const last = Buffer.alloc(1);
32312
+ fs9.readSync(fd, last, 0, 1, size - 1);
32313
+ fs9.closeSync(fd);
32314
+ if (last.toString() !== "\n") lead = "\n";
32315
+ }
32316
+ fs9.appendFileSync(file, `${lead}${JSON.stringify({ type: "custom-title", customTitle: name, sessionId: id })}
32317
+ `, "utf8");
32318
+ broadcast("sessions", { sessionId: id });
32319
+ }
32320
+ function sizeOf(target2) {
32321
+ const stat = fs9.statSync(target2);
32322
+ if (!stat.isDirectory()) return stat.size;
32323
+ return fs9.readdirSync(target2).reduce((total, name) => total + sizeOf(path10.join(target2, name)), 0);
32324
+ }
32325
+ function tempDirOf(id) {
32326
+ const base = process.env.CLAUDE_CODE_TMPDIR ?? os3.tmpdir();
32327
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
32328
+ const roots2 = [path10.join(base, "claude"), ...uid !== null ? [path10.join(base, `claude-${uid}`)] : []];
32329
+ const candidates2 = roots2.map((root2) => path10.join(root2, projectSlug(projectRoot()), id));
32330
+ return candidates2.find((candidate) => fs9.existsSync(candidate)) ?? candidates2[0];
32331
+ }
32332
+ function sessionDiskBytes(id) {
32333
+ if (!UUID.test(id)) return null;
32334
+ const key = `${projectRoot()}\0${id}`;
32335
+ const hit = diskCache.get(key);
32336
+ if (hit && Date.now() - hit.at < 6e4) return hit.bytes;
32337
+ let bytes = null;
32338
+ try {
32339
+ const plan = deletionPlan(id);
32340
+ bytes = plan.totalBytes + (plan.temp?.bytes ?? 0);
32341
+ } catch {
32342
+ }
32343
+ if (bytes !== null) diskCache.set(key, { bytes, at: Date.now() });
32344
+ return bytes ?? hit?.bytes ?? null;
32345
+ }
32346
+ function deletionPlan(id) {
32347
+ checkId(id);
32348
+ const candidates2 = [
32349
+ [transcriptFile(id), "transcript"],
32350
+ [path10.join(transcriptsDir(), id), "subagent transcripts and tool output"],
32351
+ [path10.join(claudeHome, "file-history", id), "file snapshots used to rewind"],
32352
+ [path10.join(claudeHome, "session-env", id), "session environment"]
32353
+ ];
32354
+ const files = candidates2.filter(([target2]) => fs9.existsSync(target2)).map(([target2, what]) => ({ path: target2, bytes: sizeOf(target2), what }));
32355
+ const temp = tempDirOf(id);
32356
+ return {
32357
+ sessionId: id,
32358
+ files,
32359
+ totalBytes: files.reduce((total, item) => total + item.bytes, 0),
32360
+ temp: fs9.existsSync(temp) ? { path: temp, bytes: sizeOf(temp) } : null
32361
+ };
32362
+ }
32363
+ async function deleteSession(id, options = {}) {
32364
+ checkId(id);
32365
+ const terminal = terminalForSession(id);
32366
+ if (terminal) {
32367
+ killTerminal(terminal);
32368
+ await waitForExit(terminal);
32369
+ if (terminalForSession(id)) throw new Error("The session did not stop in time; nothing was deleted. Try again.");
32370
+ }
32371
+ const plan = deletionPlan(id);
32372
+ for (const item of plan.files) fs9.rmSync(item.path, { recursive: true, force: true });
32373
+ if (options.clearTemp !== false && plan.temp) fs9.rmSync(plan.temp.path, { recursive: true, force: true });
32374
+ db.transaction(() => {
32375
+ for (const table of ["interactions", "mcp_suggestions", "channel_refs", "channel_threads", "sessions"]) {
32376
+ db.prepare(`DELETE FROM ${table} WHERE ${table === "sessions" ? "id" : "session_id"} = ?`).run(id);
32377
+ }
32378
+ })();
32379
+ forgetTranscript(id);
32380
+ broadcast("sessions", {});
32381
+ broadcast("interactions", {});
32382
+ broadcast("mcp", {});
32383
+ return plan;
32384
+ }
32385
+ var UUID, diskCache;
32386
+ var init_sessionFiles = __esm({
32387
+ "server/src/sessionFiles.ts"() {
32388
+ "use strict";
32389
+ init_db();
32390
+ init_events();
32391
+ init_paths();
32392
+ init_terminals();
32393
+ init_transcripts();
32394
+ UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
32395
+ diskCache = /* @__PURE__ */ new Map();
32396
+ }
32397
+ });
32398
+
32399
+ // server/src/inventory.ts
32400
+ import fs10 from "node:fs";
32401
+ import os4 from "node:os";
32402
+ import path11 from "node:path";
32403
+ function readJson(file) {
32404
+ try {
32405
+ return JSON.parse(fs10.readFileSync(file, "utf8"));
32406
+ } catch {
32407
+ return null;
32408
+ }
32409
+ }
32410
+ function frontMatter(text) {
32411
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
32412
+ if (!match) return {};
32413
+ const fields = {};
32414
+ let lastKey = "";
32415
+ for (const line of match[1].split(/\r?\n/)) {
32416
+ const pair = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
32417
+ if (pair) {
32418
+ lastKey = pair[1];
32419
+ fields[lastKey] = pair[2].replace(/^["']|["']$/g, "").replace(/^[>|]-?$/, "");
32420
+ } else if (lastKey && /^\s+\S/.test(line)) {
32421
+ fields[lastKey] = `${fields[lastKey]} ${line.trim()}`.trim();
32422
+ }
32423
+ }
32424
+ return fields;
32425
+ }
32426
+ function definition(file, fallbackName, scope, plugin) {
32427
+ let text;
32428
+ try {
32429
+ text = fs10.readFileSync(file, "utf8");
32430
+ } catch {
32431
+ return null;
32432
+ }
32433
+ const meta = frontMatter(text);
32434
+ const name = meta.name || fallbackName;
32435
+ return {
32436
+ name: plugin ? `${plugin.split("@")[0]}:${name}` : name,
32437
+ description: meta.description ?? "",
32438
+ scope,
32439
+ plugin,
32440
+ path: file,
32441
+ model: meta.model || void 0
32442
+ };
32443
+ }
32444
+ function markdownFiles(dir, depth = 3) {
32445
+ const found = [];
32446
+ const walk = (current, left) => {
32447
+ let entries;
32448
+ try {
32449
+ entries = fs10.readdirSync(current, { withFileTypes: true });
32450
+ } catch {
32451
+ return;
32452
+ }
32453
+ for (const entry of entries) {
32454
+ const full = path11.join(current, entry.name);
32455
+ if (entry.isDirectory() && left > 0) walk(full, left - 1);
32456
+ else if (entry.isFile() && entry.name.endsWith(".md")) found.push(full);
32457
+ }
32458
+ };
32459
+ walk(dir, depth);
32460
+ return found;
32461
+ }
32462
+ function agentsIn(dir, scope, plugin) {
32463
+ return markdownFiles(dir, 1).map((file) => definition(file, path11.basename(file, ".md"), scope, plugin)).filter((item) => item !== null);
32464
+ }
32465
+ function skillsIn(dir, scope, plugin) {
32466
+ let entries;
32467
+ try {
32468
+ entries = fs10.readdirSync(dir, { withFileTypes: true });
32469
+ } catch {
32470
+ return [];
32471
+ }
32472
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => definition(path11.join(dir, entry.name, "SKILL.md"), entry.name, scope, plugin)).filter((item) => item !== null);
32473
+ }
32474
+ function commandsIn(dir, scope, plugin) {
32475
+ return markdownFiles(dir, 2).map((file) => definition(file, path11.relative(dir, file).replace(/\.md$/, "").replace(/[\\/]/g, ":"), scope, plugin)).filter((item) => item !== null);
32476
+ }
32477
+ function mcpFrom(servers, scope, source, plugin) {
32478
+ if (!servers || typeof servers !== "object") return [];
32479
+ return Object.entries(servers).map(([name, config]) => ({
32480
+ name: plugin ? `plugin:${plugin.split("@")[0]}:${name}` : name,
32481
+ scope,
32482
+ plugin,
32483
+ transport: String(config?.type ?? (config?.url ? "http" : "stdio")),
32484
+ target: config?.url ? String(config.url) : [config?.command, ...Array.isArray(config?.args) ? config.args : []].filter(Boolean).join(" "),
32485
+ source
32486
+ }));
32487
+ }
32488
+ function hooksFrom(settings, scope, source, plugin) {
32489
+ const hooks = settings?.hooks;
32490
+ if (!hooks || typeof hooks !== "object") return [];
32491
+ const items = [];
32492
+ for (const [event, groups] of Object.entries(hooks)) {
32493
+ if (!Array.isArray(groups)) continue;
32494
+ for (const group of groups) {
32495
+ for (const hook of Array.isArray(group?.hooks) ? group.hooks : []) {
32496
+ items.push({
32497
+ event,
32498
+ matcher: String(group?.matcher ?? ""),
32499
+ type: String(hook?.type ?? "command"),
32500
+ scope,
32501
+ plugin,
32502
+ source,
32503
+ summary: String(hook?.command ?? hook?.url ?? hook?.prompt ?? hook?.tool ?? "").slice(0, 200)
32504
+ });
32505
+ }
32506
+ }
32507
+ }
32508
+ return items;
32509
+ }
32510
+ function localProjectConfig(global3) {
32511
+ const projects = global3?.projects ?? {};
32512
+ const wanted = [projectRoot(), projectRoot().replace(/\\/g, "/")];
32513
+ for (const [key, value] of Object.entries(projects)) {
32514
+ if (wanted.some((candidate) => candidate.toLowerCase() === key.toLowerCase())) return value;
32515
+ }
32516
+ return null;
32517
+ }
32518
+ function readInventory() {
32519
+ const userSettingsFile = path11.join(claudeHome, "settings.json");
32520
+ const projectSettingsFile = path11.join(projectRoot(), ".claude", "settings.json");
32521
+ const localSettingsFile = path11.join(projectRoot(), ".claude", "settings.local.json");
32522
+ const userSettings = readJson(userSettingsFile);
32523
+ const projectSettings = readJson(projectSettingsFile);
32524
+ const localSettings = readJson(localSettingsFile);
32525
+ const globalConfigFile = path11.join(os4.homedir(), ".claude.json");
32526
+ const globalConfig = readJson(globalConfigFile);
32527
+ const local = localProjectConfig(globalConfig);
32528
+ const enabled = {
32529
+ ...userSettings?.enabledPlugins ?? {},
32530
+ ...projectSettings?.enabledPlugins ?? {},
32531
+ ...localSettings?.enabledPlugins ?? {}
32532
+ };
32533
+ const plugins = [];
32534
+ const installed = readJson(path11.join(claudeHome, "plugins", "installed_plugins.json"));
32535
+ for (const [id, installs] of Object.entries(installed?.plugins ?? {})) {
32536
+ const install = Array.isArray(installs) ? installs[installs.length - 1] : null;
32537
+ if (!install?.installPath) continue;
32538
+ plugins.push({
32539
+ id,
32540
+ version: String(install.version ?? ""),
32541
+ scope: String(install.scope ?? "user"),
32542
+ // Installed plugins are on unless a settings file turns them off.
32543
+ enabled: enabled[id] !== false,
32544
+ path: install.installPath
32545
+ });
32546
+ }
32547
+ const agents = [
32548
+ ...agentsIn(path11.join(claudeHome, "agents"), "user"),
32549
+ ...agentsIn(path11.join(projectRoot(), ".claude", "agents"), "project"),
32550
+ // No file behind these, so no path: they can be turned off, not edited.
32551
+ ...BUILT_IN_AGENTS.map(([name, description]) => ({ name, description, scope: "built-in", path: "" }))
32552
+ ];
32553
+ const skills = [...skillsIn(path11.join(claudeHome, "skills"), "user"), ...skillsIn(path11.join(projectRoot(), ".claude", "skills"), "project")];
32554
+ const commands = [
32555
+ ...commandsIn(path11.join(claudeHome, "commands"), "user"),
32556
+ ...commandsIn(path11.join(projectRoot(), ".claude", "commands"), "project")
32557
+ ];
32558
+ const disabledJson = new Set(local?.disabledMcpjsonServers ?? []);
32559
+ const mcpServers = [
32560
+ ...mcpFrom(globalConfig?.mcpServers, "user", globalConfigFile),
32561
+ ...mcpFrom(local?.mcpServers, "local", globalConfigFile),
32562
+ ...mcpFrom(readJson(path11.join(projectRoot(), ".mcp.json"))?.mcpServers, "project", path11.join(projectRoot(), ".mcp.json")).map(
32563
+ (server2) => ({ ...server2, disabled: disabledJson.has(server2.name) })
32564
+ )
32565
+ ];
32566
+ const hooks = [
32567
+ ...hooksFrom(userSettings, "user", userSettingsFile),
32568
+ ...hooksFrom(projectSettings, "project", projectSettingsFile),
32569
+ ...hooksFrom(localSettings, "local", localSettingsFile)
32570
+ ];
32571
+ for (const plugin of plugins.filter((item) => item.enabled)) {
32572
+ agents.push(...agentsIn(path11.join(plugin.path, "agents"), "plugin", plugin.id));
32573
+ skills.push(...skillsIn(path11.join(plugin.path, "skills"), "plugin", plugin.id));
32574
+ commands.push(...commandsIn(path11.join(plugin.path, "commands"), "plugin", plugin.id));
32575
+ const pluginMcp = readJson(path11.join(plugin.path, ".mcp.json"));
32576
+ mcpServers.push(...mcpFrom(pluginMcp?.mcpServers ?? pluginMcp, "plugin", path11.join(plugin.path, ".mcp.json"), plugin.id));
32577
+ hooks.push(...hooksFrom(readJson(path11.join(plugin.path, "hooks", "hooks.json")), "plugin", path11.join(plugin.path, "hooks", "hooks.json"), plugin.id));
32578
+ }
32579
+ return { agents, skills, commands, mcpServers, hooks, plugins };
32580
+ }
32581
+ function memoryFiles() {
32582
+ const files = [];
32583
+ const add = (file, label, group, scope, always = false) => {
32584
+ const exists = fs10.existsSync(file);
32585
+ if (exists || always) files.push({ path: file, label, group, scope, exists });
32586
+ };
32587
+ add(path11.join(claudeHome, "CLAUDE.md"), "~/.claude/CLAUDE.md", "memory", "user", true);
32588
+ add(path11.join(projectRoot(), "CLAUDE.md"), "CLAUDE.md", "memory", "project", true);
32589
+ add(path11.join(projectRoot(), ".claude", "CLAUDE.md"), ".claude/CLAUDE.md", "memory", "project");
32590
+ add(path11.join(projectRoot(), "CLAUDE.local.md"), "CLAUDE.local.md", "memory", "local");
32591
+ for (const file of markdownFiles(path11.join(claudeHome, "rules"))) add(file, `~/.claude/rules/${path11.relative(path11.join(claudeHome, "rules"), file)}`, "rules", "user");
32592
+ for (const file of markdownFiles(path11.join(projectRoot(), ".claude", "rules"))) add(file, `.claude/rules/${path11.relative(path11.join(projectRoot(), ".claude", "rules"), file)}`, "rules", "project");
32593
+ for (const file of markdownFiles(path11.join(transcriptsDir(), "memory"), 1)) add(file, `memory/${path11.basename(file)}`, "auto-memory", "local");
32594
+ const inventory = readInventory();
32595
+ for (const agent of inventory.agents.filter((item) => item.scope !== "plugin" && item.path)) add(agent.path, `agent: ${agent.name}`, "agent", agent.scope);
32596
+ for (const skill of inventory.skills.filter((item) => item.scope !== "plugin")) add(skill.path, `skill: ${skill.name}`, "skill", skill.scope);
32597
+ for (const command of inventory.commands.filter((item) => item.scope !== "plugin")) add(command.path, `command: /${command.name}`, "command", command.scope);
32598
+ return files.map((file) => ({ ...file, label: file.label.replace(/\\/g, "/") }));
32599
+ }
32600
+ function isMemoryFile(file) {
32601
+ const wanted = path11.resolve(file).toLowerCase();
32602
+ return memoryFiles().some((item) => path11.resolve(item.path).toLowerCase() === wanted);
32603
+ }
32604
+ function isDefinitionFile(file) {
32605
+ const wanted = path11.resolve(file).toLowerCase();
32606
+ const inventory = readInventory();
32607
+ return [...inventory.agents, ...inventory.skills, ...inventory.commands].some((item) => item.path && path11.resolve(item.path).toLowerCase() === wanted);
32608
+ }
32609
+ var BUILT_IN_AGENTS;
32610
+ var init_inventory = __esm({
32611
+ "server/src/inventory.ts"() {
32612
+ "use strict";
32613
+ init_paths();
32614
+ BUILT_IN_AGENTS = [
32615
+ ["Explore", "Fast read-only search across the codebase."],
32616
+ ["Plan", "Designs an implementation plan."],
32617
+ ["general-purpose", "Multi-step research, code search and tasks."],
32618
+ ["claude-code-guide", "Answers questions about Claude Code, the Agent SDK and the API."],
32619
+ ["statusline-setup", "Configures the status line."],
32620
+ ["web-fetch", "Fetches and reads web pages."]
32621
+ ];
32622
+ }
32623
+ });
32624
+
32625
+ // server/src/toolset.ts
32626
+ function normaliseToolset(input) {
32627
+ const value = input ?? {};
32628
+ const list = (items) => [...new Set((Array.isArray(items) ? items : []).map(String).filter(Boolean))].sort();
32629
+ return { agents: list(value.agents), skills: list(value.skills), mcp: list(value.mcp), plugins: list(value.plugins) };
32630
+ }
32631
+ function isEmptyToolset(toolset) {
32632
+ return !toolset.agents.length && !toolset.skills.length && !toolset.mcp.length && !toolset.plugins.length;
32633
+ }
32634
+ function mcpPrefix(server2) {
32635
+ if (server2.scope !== "plugin") return `mcp__${toolName(server2.name)}`;
32636
+ const [, plugin = "", name = ""] = server2.name.split(":");
32637
+ return `mcp__plugin_${toolName(plugin)}_${toolName(name)}`;
32638
+ }
32639
+ function connectorsSeen() {
32640
+ const prefixes = /* @__PURE__ */ new Set();
32641
+ for (const summary of listTranscripts()) {
32642
+ for (const name of Object.keys(transcriptDetail(summary.id)?.totals.tools ?? {})) {
32643
+ const match = /^(mcp__claude_ai_[A-Za-z0-9_-]+?)__/.exec(name);
32644
+ if (match) prefixes.add(match[1]);
32645
+ }
32646
+ }
32647
+ return [...prefixes].sort();
32648
+ }
32649
+ function toolsetCatalog() {
32650
+ const inventory = readInventory();
32651
+ const items = [];
32652
+ for (const plugin of inventory.plugins.filter((item) => item.enabled)) {
32653
+ items.push({ kind: "plugins", id: plugin.id, label: plugin.id, description: `v${plugin.version}`, scope: plugin.scope === "user" ? "user" : "project", leavesContext: true });
32654
+ }
32655
+ for (const agent of inventory.agents) {
32656
+ items.push({ kind: "agents", id: agent.name, label: agent.name, description: agent.description, scope: agent.scope, plugin: agent.plugin, leavesContext: true });
32657
+ }
32658
+ for (const skill of inventory.skills) {
32659
+ items.push({ kind: "skills", id: skill.name, label: skill.name, description: skill.description, scope: skill.scope, plugin: skill.plugin, leavesContext: skill.scope !== "plugin" });
32660
+ }
32661
+ for (const server2 of inventory.mcpServers) {
32662
+ items.push({ kind: "mcp", id: mcpPrefix(server2), label: server2.name, description: server2.target, scope: server2.scope, plugin: server2.plugin, leavesContext: false });
32663
+ }
32664
+ for (const prefix of connectorsSeen()) {
32665
+ items.push({ kind: "mcp", id: prefix, label: prefix.replace(/^mcp__claude_ai_/, "claude.ai ").replace(/_/g, " "), description: "claude.ai connector", scope: "connector", leavesContext: false });
32666
+ }
32667
+ const seen = /* @__PURE__ */ new Set();
32668
+ return items.filter((item) => {
32669
+ const key = `${item.kind}:${item.id}`;
32670
+ if (seen.has(key)) return false;
32671
+ seen.add(key);
32672
+ return true;
32673
+ });
32674
+ }
32675
+ function toolsetSettings(toolset) {
32676
+ if (isEmptyToolset(toolset)) return {};
32677
+ const pluginSkills = new Set(readInventory().skills.filter((skill) => skill.scope === "plugin").map((skill) => skill.name));
32678
+ const deny = [
32679
+ ...toolset.agents.map((name) => `Agent(${name})`),
32680
+ ...toolset.skills.filter((name) => pluginSkills.has(name)).map((name) => `Skill(${name})`),
32681
+ ...toolset.mcp
32682
+ ];
32683
+ const overrides = Object.fromEntries(toolset.skills.filter((name) => !pluginSkills.has(name)).map((name) => [name, "off"]));
32684
+ const settings = {};
32685
+ if (deny.length) settings.permissions = { deny };
32686
+ if (Object.keys(overrides).length) settings.skillOverrides = overrides;
32687
+ if (toolset.plugins.length) settings.enabledPlugins = Object.fromEntries(toolset.plugins.map((id) => [id, false]));
32688
+ return settings;
32689
+ }
32690
+ function listPresets() {
32691
+ return db.prepare("SELECT * FROM presets ORDER BY name COLLATE NOCASE").all().map(toPreset);
32692
+ }
32693
+ function getPreset(id) {
32694
+ const row = db.prepare("SELECT * FROM presets WHERE id = ?").get(id);
32695
+ return row ? toPreset(row) : null;
32696
+ }
32697
+ function defaultToolset() {
32698
+ const row = db.prepare("SELECT * FROM presets WHERE is_default = 1 LIMIT 1").get();
32699
+ return row ? toPreset(row).toolset : EMPTY_TOOLSET;
32700
+ }
32701
+ function savePreset(input) {
32702
+ const name = String(input.name ?? "").trim();
32703
+ if (!name) throw new Error("A preset needs a name.");
32704
+ const id = input.id ?? nanoid(10);
32705
+ db.transaction(() => {
32706
+ if (input.isDefault) db.prepare("UPDATE presets SET is_default = 0").run();
32707
+ db.prepare(
32708
+ `INSERT INTO presets (id, name, toolset, is_default, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)
32709
+ ON CONFLICT(id) DO UPDATE SET name = excluded.name, toolset = excluded.toolset, is_default = excluded.is_default, updated_at = excluded.updated_at`
32710
+ ).run(id, name, JSON.stringify(normaliseToolset(input.toolset)), input.isDefault ? 1 : 0, now(), now());
32711
+ })();
32712
+ broadcast("jobs", {});
32713
+ return getPreset(id);
32714
+ }
32715
+ function setDefaultItem(input) {
32716
+ const kind = String(input.kind ?? "");
32717
+ const id = String(input.id ?? "").trim();
32718
+ if (!(kind in EMPTY_TOOLSET) || !id) throw new Error("Send { kind, id, enabled }.");
32719
+ const row = db.prepare("SELECT * FROM presets WHERE is_default = 1 LIMIT 1").get();
32720
+ const preset = row ? toPreset(row) : { id: void 0, name: "Default", toolset: EMPTY_TOOLSET };
32721
+ const off = preset.toolset[kind].filter((item) => item !== id);
32722
+ if (input.enabled !== true) off.push(id);
32723
+ return savePreset({ id: preset.id, name: preset.name, toolset: { ...preset.toolset, [kind]: off }, isDefault: true });
32724
+ }
32725
+ function deletePreset(id) {
32726
+ db.prepare("DELETE FROM presets WHERE id = ?").run(id);
32727
+ db.prepare("UPDATE jobs SET preset_id = NULL WHERE preset_id = ?").run(id);
32728
+ broadcast("jobs", {});
32729
+ }
32730
+ var EMPTY_TOOLSET, toolName, toPreset;
32731
+ var init_toolset = __esm({
32732
+ "server/src/toolset.ts"() {
32733
+ "use strict";
32734
+ init_nanoid();
32735
+ init_db();
32736
+ init_events();
32737
+ init_inventory();
32738
+ init_transcripts();
32739
+ EMPTY_TOOLSET = { agents: [], skills: [], mcp: [], plugins: [] };
32740
+ toolName = (value) => value.replace(/[^A-Za-z0-9_-]/g, "_");
32741
+ toPreset = (row) => ({ id: row.id, name: row.name, toolset: normaliseToolset(parseJson(row.toolset, {})), isDefault: Boolean(row.is_default) });
32742
+ }
32743
+ });
32744
+
32582
32745
  // server/src/mcpCatalog.ts
32583
32746
  function catalogEntry(id) {
32584
32747
  return MCP_CATALOG.find((entry) => entry.id === id) ?? null;
@@ -32809,7 +32972,6 @@ function channelParams() {
32809
32972
  { name: "kind", type: `"${CHANNEL_KINDS.map((kind) => kind.kind).join('" | "')}"`, required: true, description: "The platform. Cannot change after creation.", example: "slack" },
32810
32973
  { name: "name", type: "string", required: true, description: "Shown in the dashboard.", example: "Team Slack" },
32811
32974
  { name: "enabled", type: "boolean", required: false, description: "Default true.", example: "true" },
32812
- { name: "kinds", type: "string[]", required: false, description: `What it is sent; any of ${INTERACTION_KINDS.join(", ")}. Default all.`, example: '["permission", "question", "done"]' },
32813
32975
  { name: "config", type: "object", required: true, description: `Per platform. ${fields}`, example: '{ "botToken": "xoxb-...", "appToken": "xapp-...", "channel": "C0123456789" }' }
32814
32976
  ];
32815
32977
  }
@@ -32893,8 +33055,8 @@ function definitionOf(purpose) {
32893
33055
  summary: isGlobal(currentProject()) ? "A global channel serves every project in the hub: their permission requests, questions, ends of turns, MCP suggestions and finished tasks all arrive on it, each named after its project, and replies go back into the right session. A bot used here cannot also be a project's own channel." : "A channel is where sessions reach the person: permission requests, questions, ends of turns, MCP suggestions and finished tasks. Replies there go back into the session.",
32894
33056
  params: channelParams(),
32895
33057
  samples: [
32896
- { kind: "slack", name: "Team Slack", enabled: true, kinds: ["permission", "question", "turn", "mcp", "done"], config: { botToken: "xoxb-...", appToken: "xapp-...", channel: "C0123456789" } },
32897
- { kind: "telegram", name: "My phone", enabled: true, kinds: ["permission", "question", "done"], config: { botToken: "123456:ABC-...", chatId: "123456789" } }
33058
+ { kind: "slack", name: "Team Slack", enabled: true, config: { botToken: "xoxb-...", appToken: "xapp-...", channel: "C0123456789" } },
33059
+ { kind: "telegram", name: "My phone", enabled: true, config: { botToken: "123456:ABC-...", chatId: "123456789" } }
32898
33060
  ],
32899
33061
  api: [
32900
33062
  "GET /api/channels (kinds and fields, existing channels with secrets masked as ********)",
@@ -32922,7 +33084,7 @@ function currentValue(purpose) {
32922
33084
  }
32923
33085
  case "edit-channel": {
32924
33086
  const channel = listChannels().find((item) => item.id === purpose.targetId);
32925
- return channel && { kind: channel.kind, name: channel.name, enabled: channel.enabled, kinds: channel.kinds, config: channel.config };
33087
+ return channel && { kind: channel.kind, name: channel.name, enabled: channel.enabled, config: channel.config };
32926
33088
  }
32927
33089
  default:
32928
33090
  return void 0;
@@ -33052,8 +33214,8 @@ JSON`;
33052
33214
 
33053
33215
  // server/src/sessions.ts
33054
33216
  import { randomUUID } from "node:crypto";
33055
- import fs10 from "node:fs";
33056
- import path11 from "node:path";
33217
+ import fs11 from "node:fs";
33218
+ import path12 from "node:path";
33057
33219
  function getSessionRow(id) {
33058
33220
  return db.prepare("SELECT * FROM sessions WHERE id = ?").get(id) ?? null;
33059
33221
  }
@@ -33149,11 +33311,11 @@ function startSession(options) {
33149
33311
  const category = options.category !== void 0 ? options.category || null : existing?.category ?? null;
33150
33312
  const token = nanoid(24);
33151
33313
  const toolset = options.toolset ? normaliseToolset(options.toolset) : existing?.toolset ? normaliseToolset(JSON.parse(existing.toolset)) : defaultToolset();
33152
- const settingsFile = path11.join(runDir, `${token}.settings.json`);
33153
- const promptFile = path11.join(runDir, `${token}.prompt.md`);
33154
- fs10.writeFileSync(settingsFile, JSON.stringify({ ...toolsetSettings(toolset), ...hookSettings(token) }, null, 2), "utf8");
33314
+ const settingsFile = path12.join(runDir, `${token}.settings.json`);
33315
+ const promptFile = path12.join(runDir, `${token}.prompt.md`);
33316
+ fs11.writeFileSync(settingsFile, JSON.stringify({ ...toolsetSettings(toolset), ...hookSettings(token) }, null, 2), "utf8");
33155
33317
  const purpose = options.purpose ?? (existing?.purpose ? JSON.parse(existing.purpose) : null);
33156
- fs10.writeFileSync(promptFile, systemPromptFor(category, purpose, existing ? sessionSetup(sessionId) : null), "utf8");
33318
+ fs11.writeFileSync(promptFile, systemPromptFor(category, purpose, existing ? sessionSetup(sessionId) : null), "utf8");
33157
33319
  const args = ["--settings", settingsFile, "--append-system-prompt-file", promptFile];
33158
33320
  args.push(...options.resumeId ? ["--resume", options.resumeId] : ["--session-id", sessionId]);
33159
33321
  if (options.name) args.push("--name", options.name);
@@ -33202,7 +33364,7 @@ function terminalByToken(token) {
33202
33364
  return allTerminals().find((terminal) => terminal.token === token);
33203
33365
  }
33204
33366
  function cleanRunFiles(token) {
33205
- for (const suffix of [".settings.json", ".prompt.md"]) fs10.rmSync(path11.join(runDir, `${token}${suffix}`), { force: true });
33367
+ for (const suffix of [".settings.json", ".prompt.md"]) fs11.rmSync(path12.join(runDir, `${token}${suffix}`), { force: true });
33206
33368
  }
33207
33369
  function purposeOf(row) {
33208
33370
  const purpose = parseJson(row?.purpose, null);
@@ -33216,6 +33378,7 @@ function listSessions() {
33216
33378
  )
33217
33379
  );
33218
33380
  const terminals2 = new Map(listTerminals().map((terminal) => [terminal.sessionId, terminal]));
33381
+ const quiet = new Set(quietSessions());
33219
33382
  const views = [];
33220
33383
  const seen = /* @__PURE__ */ new Set();
33221
33384
  const view = (id, summary) => {
@@ -33236,7 +33399,9 @@ function listSessions() {
33236
33399
  runId: row?.run_id ?? null,
33237
33400
  openInteractions: open.get(id) ?? 0,
33238
33401
  done: parseJson(row?.done_json, null),
33239
- purpose
33402
+ purpose,
33403
+ diskBytes: sessionDiskBytes(id),
33404
+ quiet: quiet.has(id)
33240
33405
  };
33241
33406
  };
33242
33407
  for (const summary of listTranscripts()) {
@@ -33259,7 +33424,9 @@ var init_sessions = __esm({
33259
33424
  init_db();
33260
33425
  init_events();
33261
33426
  init_paths();
33427
+ init_channels();
33262
33428
  init_prompts();
33429
+ init_sessionFiles();
33263
33430
  init_terminals();
33264
33431
  init_toolset();
33265
33432
  init_purposes();
@@ -33536,6 +33703,7 @@ init_claudeCode();
33536
33703
  init_context();
33537
33704
  init_db();
33538
33705
  import fs14 from "node:fs";
33706
+ import net from "node:net";
33539
33707
  import path15 from "node:path";
33540
33708
  import { fileURLToPath as fileURLToPath2 } from "node:url";
33541
33709
 
@@ -33830,6 +33998,40 @@ function revealPath(relInput) {
33830
33998
  });
33831
33999
  });
33832
34000
  }
34001
+ function copyFileToClipboard(relInput) {
34002
+ const absolute = resolvePath(relInput);
34003
+ if (!fs3.existsSync(absolute)) throw new FileError("No such file or folder.", 404);
34004
+ const run4 = (command, args, env = process.env) => new Promise((resolve, reject) => {
34005
+ const child = spawn(command, args, { windowsHide: true, env, stdio: ["ignore", "ignore", "pipe"] });
34006
+ let errorText = "";
34007
+ child.stderr.on("data", (chunk) => errorText += chunk);
34008
+ child.once("error", (error) => reject(new FileError(`Could not reach the clipboard: ${error.message}`, 409)));
34009
+ child.once("exit", (code) => code === 0 ? resolve({ path: toRel(absolute) }) : reject(new FileError(`Could not reach the clipboard: ${errorText.trim() || `exit ${code}`}`, 409)));
34010
+ });
34011
+ if (process.platform === "win32") {
34012
+ return run4("powershell.exe", ["-NoProfile", "-NonInteractive", "-STA", "-ExecutionPolicy", "Bypass", "-Command", "Set-Clipboard -LiteralPath $env:CLAUDER_COPY"], {
34013
+ ...process.env,
34014
+ CLAUDER_COPY: absolute
34015
+ });
34016
+ }
34017
+ if (process.platform === "darwin") {
34018
+ return run4("osascript", ["-e", "on run argv", "-e", "set the clipboard to (POSIX file (item 1 of argv))", "-e", "end run", absolute]);
34019
+ }
34020
+ if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
34021
+ throw new FileError("There is no desktop session on the machine running the hub, so no clipboard to put the file on.", 409);
34022
+ }
34023
+ const uri = `file://${absolute.split("/").map(encodeURIComponent).join("/")}`;
34024
+ return new Promise((resolve, reject) => {
34025
+ const child = spawn("xclip", ["-selection", "clipboard", "-t", "text/uri-list"], { stdio: ["pipe", "ignore", "ignore"], detached: true });
34026
+ child.once("error", (error) => reject(new FileError(`Could not reach the clipboard (is xclip installed?): ${error.message}`, 409)));
34027
+ child.once("spawn", () => {
34028
+ child.stdin.end(`${uri}
34029
+ `);
34030
+ child.unref();
34031
+ resolve({ path: toRel(absolute) });
34032
+ });
34033
+ });
34034
+ }
33833
34035
  function deletePath(relInput) {
33834
34036
  const absolute = resolvePath(relInput);
33835
34037
  refuseRoot(absolute);
@@ -33963,6 +34165,7 @@ fileRoutes.post("/mkdir", wrap((req) => createFolder(req.body?.path)));
33963
34165
  fileRoutes.post("/rename", wrap((req) => renamePath(req.body?.from, req.body?.to)));
33964
34166
  fileRoutes.post("/delete", wrap((req) => deletePath(req.body?.path)));
33965
34167
  fileRoutes.post("/reveal", wrapAsync((req) => revealPath(req.body?.path)));
34168
+ fileRoutes.post("/clipboard", wrapAsync((req) => copyFileToClipboard(req.body?.path)));
33966
34169
  fileRoutes.post("/copy", wrap((req) => copyPath(req.body?.from, req.body?.folder ?? "")));
33967
34170
 
33968
34171
  // server/src/index.ts
@@ -33980,16 +34183,16 @@ import os5 from "node:os";
33980
34183
  import path14 from "node:path";
33981
34184
 
33982
34185
  // server/src/fileIcons.ts
33983
- import fs11 from "node:fs";
34186
+ import fs12 from "node:fs";
33984
34187
  import nodeModule from "node:module";
33985
- import path12 from "node:path";
34188
+ import path13 from "node:path";
33986
34189
  var resolveFrom = nodeModule.createRequire(import.meta.url);
33987
- var root = path12.dirname(resolveFrom.resolve("material-icon-theme/package.json"));
33988
- var iconsDir = path12.join(root, "icons");
34190
+ var root = path13.dirname(resolveFrom.resolve("material-icon-theme/package.json"));
34191
+ var iconsDir = path13.join(root, "icons");
33989
34192
  var manifest = null;
33990
34193
  function iconManifest() {
33991
34194
  if (!manifest) {
33992
- const full = JSON.parse(fs11.readFileSync(path12.join(root, "dist", "material-icons.json"), "utf8"));
34195
+ const full = JSON.parse(fs12.readFileSync(path13.join(root, "dist", "material-icons.json"), "utf8"));
33993
34196
  manifest = {
33994
34197
  file: full.file,
33995
34198
  folder: full.folder,
@@ -34004,8 +34207,8 @@ function iconManifest() {
34004
34207
  }
34005
34208
  function iconFile(name) {
34006
34209
  if (!/^[\w.-]+$/.test(name)) return null;
34007
- const file = path12.join(iconsDir, `${name}.svg`);
34008
- return fs11.existsSync(file) ? file : null;
34210
+ const file = path13.join(iconsDir, `${name}.svg`);
34211
+ return fs12.existsSync(file) ? file : null;
34009
34212
  }
34010
34213
 
34011
34214
  // server/src/routes.ts
@@ -34154,96 +34357,7 @@ init_prompts();
34154
34357
  init_sessions();
34155
34358
  init_terminals();
34156
34359
  init_purposes();
34157
-
34158
- // server/src/sessionFiles.ts
34159
- init_db();
34160
- init_events();
34161
- init_paths();
34162
- init_terminals();
34163
- init_transcripts();
34164
- import fs12 from "node:fs";
34165
- import os4 from "node:os";
34166
- import path13 from "node:path";
34167
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
34168
- function checkId(id) {
34169
- if (!UUID.test(id)) throw new Error("Not a session id.");
34170
- }
34171
- function transcriptFile(id) {
34172
- return path13.join(transcriptsDir(), `${id}.jsonl`);
34173
- }
34174
- function setSessionTitle(id, title) {
34175
- checkId(id);
34176
- const name = title.replace(/\s+/g, " ").trim();
34177
- if (!name) throw new Error("The name is empty.");
34178
- if (name.length > 200) throw new Error("Keep the name under 200 characters.");
34179
- const file = transcriptFile(id);
34180
- if (!fs12.existsSync(file)) throw new Error("This session has no transcript yet; give it a moment to start.");
34181
- const size = fs12.statSync(file).size;
34182
- let lead = "";
34183
- if (size > 0) {
34184
- const fd = fs12.openSync(file, "r");
34185
- const last = Buffer.alloc(1);
34186
- fs12.readSync(fd, last, 0, 1, size - 1);
34187
- fs12.closeSync(fd);
34188
- if (last.toString() !== "\n") lead = "\n";
34189
- }
34190
- fs12.appendFileSync(file, `${lead}${JSON.stringify({ type: "custom-title", customTitle: name, sessionId: id })}
34191
- `, "utf8");
34192
- broadcast("sessions", { sessionId: id });
34193
- }
34194
- function sizeOf(target2) {
34195
- const stat = fs12.statSync(target2);
34196
- if (!stat.isDirectory()) return stat.size;
34197
- return fs12.readdirSync(target2).reduce((total, name) => total + sizeOf(path13.join(target2, name)), 0);
34198
- }
34199
- function tempDirOf(id) {
34200
- const base = process.env.CLAUDE_CODE_TMPDIR ?? os4.tmpdir();
34201
- const uid = typeof process.getuid === "function" ? process.getuid() : null;
34202
- const roots2 = [path13.join(base, "claude"), ...uid !== null ? [path13.join(base, `claude-${uid}`)] : []];
34203
- const candidates2 = roots2.map((root2) => path13.join(root2, projectSlug(projectRoot()), id));
34204
- return candidates2.find((candidate) => fs12.existsSync(candidate)) ?? candidates2[0];
34205
- }
34206
- function deletionPlan(id) {
34207
- checkId(id);
34208
- const candidates2 = [
34209
- [transcriptFile(id), "transcript"],
34210
- [path13.join(transcriptsDir(), id), "subagent transcripts and tool output"],
34211
- [path13.join(claudeHome, "file-history", id), "file snapshots used to rewind"],
34212
- [path13.join(claudeHome, "session-env", id), "session environment"]
34213
- ];
34214
- const files = candidates2.filter(([target2]) => fs12.existsSync(target2)).map(([target2, what]) => ({ path: target2, bytes: sizeOf(target2), what }));
34215
- const temp = tempDirOf(id);
34216
- return {
34217
- sessionId: id,
34218
- files,
34219
- totalBytes: files.reduce((total, item) => total + item.bytes, 0),
34220
- temp: fs12.existsSync(temp) ? { path: temp, bytes: sizeOf(temp) } : null
34221
- };
34222
- }
34223
- async function deleteSession(id, options = {}) {
34224
- checkId(id);
34225
- const terminal = terminalForSession(id);
34226
- if (terminal) {
34227
- killTerminal(terminal);
34228
- await waitForExit(terminal);
34229
- if (terminalForSession(id)) throw new Error("The session did not stop in time; nothing was deleted. Try again.");
34230
- }
34231
- const plan = deletionPlan(id);
34232
- for (const item of plan.files) fs12.rmSync(item.path, { recursive: true, force: true });
34233
- if (options.clearTemp !== false && plan.temp) fs12.rmSync(plan.temp.path, { recursive: true, force: true });
34234
- db.transaction(() => {
34235
- for (const table of ["interactions", "mcp_suggestions", "channel_refs", "channel_threads", "sessions"]) {
34236
- db.prepare(`DELETE FROM ${table} WHERE ${table === "sessions" ? "id" : "session_id"} = ?`).run(id);
34237
- }
34238
- })();
34239
- forgetTranscript(id);
34240
- broadcast("sessions", {});
34241
- broadcast("interactions", {});
34242
- broadcast("mcp", {});
34243
- return plan;
34244
- }
34245
-
34246
- // server/src/routes.ts
34360
+ init_sessionFiles();
34247
34361
  init_toolset();
34248
34362
  init_transcripts();
34249
34363
  var api = import_express2.default.Router();
@@ -34479,6 +34593,16 @@ api.post(
34479
34593
  "/interactions/:id/answer",
34480
34594
  wrap2((req) => answerInteraction(req.params.id, String(req.body?.answer ?? ""), "dashboard"))
34481
34595
  );
34596
+ api.post("/interactions/:id/dismiss", wrap2((req) => dismissInteraction(req.params.id)));
34597
+ api.post(
34598
+ "/sessions/:id/dismiss-waiting",
34599
+ wrap2((req) => {
34600
+ const open = listInteractions({ sessionId: req.params.id, status: "open" });
34601
+ for (const item of open) dismissInteraction(item.id);
34602
+ return { dismissed: open.length };
34603
+ })
34604
+ );
34605
+ api.put("/sessions/:id/quiet", wrap2((req) => setSessionQuiet(req.params.id, Boolean(req.body?.quiet))));
34482
34606
  api.get("/inventory", wrap2(() => readInventory()));
34483
34607
  api.get(
34484
34608
  "/stats",
@@ -34552,7 +34676,9 @@ api.put(
34552
34676
  return { path: file, content };
34553
34677
  })
34554
34678
  );
34555
- api.get("/channels", wrap2(() => ({ kinds: CHANNEL_KINDS, interactionKinds: INTERACTION_KINDS, channels: listChannels() })));
34679
+ api.get("/channels", wrap2(() => ({ kinds: CHANNEL_KINDS, interactionKinds: INTERACTION_KINDS, channels: listChannels(), paused: notificationsPaused(), notifyKinds: notifyKinds() })));
34680
+ api.put("/notifications/kinds", wrap2((req) => ({ notifyKinds: setNotifyKinds(Array.isArray(req.body?.kinds) ? req.body.kinds.map(String) : []) })));
34681
+ api.put("/notifications/paused", wrap2((req) => setNotificationsPaused(Boolean(req.body?.paused))));
34556
34682
  api.post("/channels", wrap2((req) => saveChannel(req.body ?? {})));
34557
34683
  api.put("/channels/:id", wrap2((req) => saveChannel({ ...req.body ?? {}, id: req.params.id })));
34558
34684
  api.delete("/channels/:id", wrap2((req) => deleteChannel(req.params.id)));
@@ -34681,6 +34807,21 @@ async function otherHubPort() {
34681
34807
  }
34682
34808
  return null;
34683
34809
  }
34810
+ var listening = (port2) => new Promise((resolve) => {
34811
+ const socket = net.connect(port2, "127.0.0.1");
34812
+ const done = (answer) => {
34813
+ socket.destroy();
34814
+ resolve(answer);
34815
+ };
34816
+ socket.setTimeout(2e3);
34817
+ socket.once("connect", () => done(true));
34818
+ socket.once("timeout", () => done(true));
34819
+ socket.once("error", () => done(false));
34820
+ });
34821
+ var leftover = readLock();
34822
+ if (leftover?.port && alive(leftover.pid) && !await listening(leftover.port) && readLock()?.pid === leftover.pid) {
34823
+ fs14.rmSync(lockFile, { force: true });
34824
+ }
34684
34825
  if (!takeLock() && !await otherHubPort().then((found) => found === null && takeLock())) {
34685
34826
  const otherPort = await otherHubPort();
34686
34827
  if (!otherPort) {