tring-chat 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tring.js CHANGED
@@ -5,7 +5,7 @@ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:f
5
5
  import { createServer } from "node:http";
6
6
  import { createServer as createSecureServer } from "node:https";
7
7
  import os9 from "node:os";
8
- import path14 from "node:path";
8
+ import path18 from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { WebSocketServer } from "ws";
11
11
 
@@ -203,14 +203,14 @@ function isNewer(latest, current) {
203
203
  var DAY_MS = 24 * 60 * 60 * 1e3;
204
204
  async function checkForUpdate(cachePath) {
205
205
  const current = currentVersion();
206
- let cache = null;
206
+ let cache2 = null;
207
207
  try {
208
- cache = JSON.parse(await readFile(cachePath, "utf8"));
208
+ cache2 = JSON.parse(await readFile(cachePath, "utf8"));
209
209
  } catch {
210
- cache = null;
210
+ cache2 = null;
211
211
  }
212
- if (cache && Date.now() - cache.checkedAt < DAY_MS) {
213
- return isNewer(cache.latest, current) ? cache.latest : null;
212
+ if (cache2 && Date.now() - cache2.checkedAt < DAY_MS) {
213
+ return isNewer(cache2.latest, current) ? cache2.latest : null;
214
214
  }
215
215
  let latest;
216
216
  try {
@@ -447,7 +447,7 @@ function snapshot(term) {
447
447
  const line = buf.getLine(buf.viewportY + y);
448
448
  const out = [];
449
449
  if (line) {
450
- let run2 = null;
450
+ let run3 = null;
451
451
  for (let x = 0; x < term.cols; x++) {
452
452
  const cell = line.getCell(x);
453
453
  if (!cell) break;
@@ -456,11 +456,11 @@ function snapshot(term) {
456
456
  const fg = cell.isFgDefault() ? -1 : cell.getFgColor();
457
457
  const bg = cell.isBgDefault() ? -1 : cell.getBgColor();
458
458
  const bold = cell.isBold() !== 0;
459
- if (run2 && run2.fg === fg && run2.bg === bg && run2.bold === bold) {
460
- run2.text += text2;
459
+ if (run3 && run3.fg === fg && run3.bg === bg && run3.bold === bold) {
460
+ run3.text += text2;
461
461
  } else {
462
- run2 = { text: text2, fg, bg, bold };
463
- out.push(run2);
462
+ run3 = { text: text2, fg, bg, bold };
463
+ out.push(run3);
464
464
  }
465
465
  }
466
466
  while (out.length > 0) {
@@ -564,6 +564,21 @@ var Session = class {
564
564
  title = null;
565
565
  /** The conversation running here, kept so a restart can reopen it. */
566
566
  claude = null;
567
+ /** What the agent said when it last stopped (Stop hook), for the orchestrator. */
568
+ lastMessage = null;
569
+ /** When the agent last stopped; 0 for never. */
570
+ stoppedAt = 0;
571
+ /** When it was last given a prompt, typed or sent by the orchestrator; 0 for never. */
572
+ promptedAt = 0;
573
+ /**
574
+ * Where the agent in this tile is working, from the `cwd` every Claude Code
575
+ * hook reports. Not the shell's directory: an agent that has moved into a
576
+ * git worktree (`claude --worktree`, or its own `cd`) is there, while the
577
+ * shell that started it never moved. Null when no agent has reported.
578
+ */
579
+ agentCwd = null;
580
+ /** The conversation's transcript (`transcript_path` in every hook); null until one reports. */
581
+ transcript = null;
567
582
  tracker;
568
583
  onData = null;
569
584
  onStatusChange = null;
@@ -720,6 +735,36 @@ var Session = class {
720
735
  snapshotNow() {
721
736
  return snapshot(this.term);
722
737
  }
738
+ /**
739
+ * The last `lines` lines of screen and scrollback as plain text, trailing
740
+ * blank lines dropped. What the orchestrator agent reads a tile through.
741
+ */
742
+ recentText(lines) {
743
+ const buf = this.term.buffer.active;
744
+ const line = (y) => buf.getLine(y)?.translateToString(true) ?? "";
745
+ let end = buf.length;
746
+ while (end > 0 && !line(end - 1).trim()) end--;
747
+ const out = [];
748
+ for (let y = Math.max(0, end - Math.max(1, lines)); y < end; y++) out.push(line(y));
749
+ return out.join("\n");
750
+ }
751
+ /** The agent stopped and said this; see `lastMessage`. */
752
+ said(text2) {
753
+ this.lastMessage = text2;
754
+ this.stoppedAt = Date.now();
755
+ }
756
+ /** A prompt went in; see `promptedAt`. */
757
+ prompted() {
758
+ this.promptedAt = Date.now();
759
+ }
760
+ /** The agent reported where it is; null when it has ended. See `agentCwd`. */
761
+ agentAt(dir) {
762
+ this.agentCwd = dir && path3.isAbsolute(dir) ? dir : null;
763
+ }
764
+ /** Where the running conversation is recorded. Only an absolute .jsonl is kept. */
765
+ transcriptAt(file) {
766
+ if (path3.isAbsolute(file) && file.endsWith(".jsonl")) this.transcript = file;
767
+ }
723
768
  /** Only when the screen actually changed, which is what keeps 16 tiles cheap. */
724
769
  takeSnapshot() {
725
770
  const shot = snapshot(this.term);
@@ -1048,9 +1093,19 @@ var ProjectManager = class _ProjectManager {
1048
1093
  this.changed();
1049
1094
  }
1050
1095
  activate(id) {
1096
+ if (!this.entries.has(id)) return null;
1097
+ this.activeId = id;
1098
+ return this.ensure(id);
1099
+ }
1100
+ /**
1101
+ * The project's sessions, spawning a restored project's if they are still
1102
+ * pending, without making it the active project. The orchestrator agent
1103
+ * starts tiles in projects you are not looking at, and doing so must not
1104
+ * pull the view out from under you.
1105
+ */
1106
+ ensure(id) {
1051
1107
  const e = this.entries.get(id);
1052
1108
  if (!e) return null;
1053
- this.activeId = id;
1054
1109
  if (!e.manager) {
1055
1110
  e.manager = this.spawnManager(e);
1056
1111
  for (const rec of e.pending) {
@@ -1070,9 +1125,15 @@ var ProjectManager = class _ProjectManager {
1070
1125
  create(projectId, spec) {
1071
1126
  const id = projectId ?? this.activeId;
1072
1127
  if (!id) return null;
1073
- const mgr = this.managerFor(id) ?? this.activate(id);
1128
+ const mgr = this.ensure(id);
1074
1129
  return mgr ? mgr.create(spec) : null;
1075
1130
  }
1131
+ /** A project by id, or by name ignoring case — names are what people say. */
1132
+ findProject(ref) {
1133
+ const all = this.list();
1134
+ const want = ref.trim().toLowerCase();
1135
+ return all.find((p) => p.id === ref) ?? all.find((p) => p.name.toLowerCase() === want);
1136
+ }
1076
1137
  /** Session lookup by globally unique id, across every live project. */
1077
1138
  findSession(sessionId) {
1078
1139
  for (const e of this.entries.values()) {
@@ -1175,9 +1236,9 @@ var ProjectManager = class _ProjectManager {
1175
1236
 
1176
1237
  // src/http.ts
1177
1238
  import { createReadStream } from "node:fs";
1178
- import { readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";
1239
+ import { readdir as readdir4, realpath, stat as stat5 } from "node:fs/promises";
1179
1240
  import os5 from "node:os";
1180
- import path9 from "node:path";
1241
+ import path12 from "node:path";
1181
1242
 
1182
1243
  // src/security.ts
1183
1244
  import { createHash, timingSafeEqual } from "node:crypto";
@@ -1399,7 +1460,7 @@ function parseLimits(text2) {
1399
1460
  }
1400
1461
  function readLimits(timeoutMs = 3e4) {
1401
1462
  const args = ["-p", "/usage", "--output-format", "json"];
1402
- const run2 = (cmd) => new Promise((resolve, reject) => {
1463
+ const run3 = (cmd) => new Promise((resolve, reject) => {
1403
1464
  const child = spawn2(cmd, args, { stdio: ["ignore", "pipe", "ignore"] });
1404
1465
  let out = "";
1405
1466
  let settled = false;
@@ -1429,8 +1490,8 @@ function readLimits(timeoutMs = 3e4) {
1429
1490
  }, 50);
1430
1491
  });
1431
1492
  });
1432
- return run2("claude").catch(
1433
- (err) => process.platform === "win32" && err.code === "ENOENT" ? run2("claude.cmd") : Promise.reject(err)
1493
+ return run3("claude").catch(
1494
+ (err) => process.platform === "win32" && err.code === "ENOENT" ? run3("claude.cmd") : Promise.reject(err)
1434
1495
  );
1435
1496
  }
1436
1497
  async function collectUsage(dir, now) {
@@ -1755,6 +1816,9 @@ function routeHook(req) {
1755
1816
  const { inbox, session, event, payload } = req;
1756
1817
  const tool = payload.tool_name;
1757
1818
  const input = payload.tool_input;
1819
+ if (event === "SessionEnd") session.agentAt?.(null);
1820
+ else if (typeof payload.cwd === "string" && payload.cwd) session.agentAt?.(payload.cwd);
1821
+ if (typeof payload.transcript_path === "string" && payload.transcript_path) session.transcriptAt?.(payload.transcript_path);
1758
1822
  switch (event) {
1759
1823
  case "PermissionRequest":
1760
1824
  if (!tool || tool === "AskUserQuestion") return Promise.resolve(null);
@@ -1768,6 +1832,7 @@ function routeHook(req) {
1768
1832
  case "Stop": {
1769
1833
  session.hook();
1770
1834
  const said = payload.last_assistant_message?.trim();
1835
+ session.said?.(said ?? "");
1771
1836
  if (said) inbox.reply(session.id, said);
1772
1837
  return Promise.resolve(null);
1773
1838
  }
@@ -1785,6 +1850,7 @@ function routeHook(req) {
1785
1850
  // The user typed into this session's own terminal: whatever its cards
1786
1851
  // were asking has been dealt with there.
1787
1852
  case "UserPromptSubmit":
1853
+ session.prompted?.();
1788
1854
  inbox.dropSession(session.id);
1789
1855
  return Promise.resolve(null);
1790
1856
  // The tool ran (or failed), so its permission prompt is over. Matched on
@@ -1915,6 +1981,913 @@ async function uninstallHooks(file = defaultClaudeSettingsPath()) {
1915
1981
  return true;
1916
1982
  }
1917
1983
 
1984
+ // src/orchestrator-tools.ts
1985
+ import { stat as stat4 } from "node:fs/promises";
1986
+ import path11 from "node:path";
1987
+
1988
+ // src/git-worktrees.ts
1989
+ import { execFile as execFile2 } from "node:child_process";
1990
+ import path9 from "node:path";
1991
+ import { promisify as promisify2 } from "node:util";
1992
+ var run2 = promisify2(execFile2);
1993
+ async function git2(cwd, args, timeout = 5e3) {
1994
+ try {
1995
+ const { stdout } = await run2("git", ["-c", "core.fsmonitor=false", ...args], { cwd, encoding: "utf8", timeout });
1996
+ return stdout;
1997
+ } catch {
1998
+ return null;
1999
+ }
2000
+ }
2001
+ function samePath(a, b) {
2002
+ return normal(a) === normal(b);
2003
+ }
2004
+ function normal(p) {
2005
+ const r = path9.resolve(p).replace(/[\\/]+$/, "");
2006
+ return process.platform === "win32" ? r.toLowerCase() : r;
2007
+ }
2008
+ function repoName(commonDir) {
2009
+ const base2 = path9.basename(commonDir);
2010
+ return base2 === ".git" ? path9.basename(path9.dirname(commonDir)) : base2.replace(/\.git$/, "");
2011
+ }
2012
+ function branchSlug(branch) {
2013
+ return branch.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "worktree";
2014
+ }
2015
+ function parseWorktreeList(text2) {
2016
+ const out = [];
2017
+ for (const block of text2.replace(/\r\n/g, "\n").split(/\n\n+/)) {
2018
+ const lines = block.split("\n").filter(Boolean);
2019
+ const first = lines[0];
2020
+ if (!first?.startsWith("worktree ")) continue;
2021
+ const w = {
2022
+ path: first.slice("worktree ".length),
2023
+ branch: null,
2024
+ head: null,
2025
+ bare: false,
2026
+ detached: false,
2027
+ locked: false,
2028
+ prunable: false
2029
+ };
2030
+ for (const l of lines.slice(1)) {
2031
+ if (l.startsWith("HEAD ")) w.head = l.slice(5);
2032
+ else if (l.startsWith("branch ")) w.branch = l.slice(7).replace(/^refs\/heads\//, "");
2033
+ else if (l === "bare") w.bare = true;
2034
+ else if (l === "detached") w.detached = true;
2035
+ else if (l === "locked" || l.startsWith("locked ")) w.locked = true;
2036
+ else if (l === "prunable" || l.startsWith("prunable ")) w.prunable = true;
2037
+ }
2038
+ out.push(w);
2039
+ }
2040
+ return out;
2041
+ }
2042
+ function defaultWorktreePath(commonDir, existing, branch) {
2043
+ const slug = branchSlug(branch);
2044
+ const linked = existing.filter((w, i) => i > 0 && !w.bare && !w.prunable);
2045
+ const parents = [...new Set(linked.map((w) => normal(path9.dirname(w.path))))];
2046
+ if (parents.length === 1) return path9.join(path9.dirname(linked[0].path), slug);
2047
+ const repoDir = path9.basename(commonDir) === ".git" ? path9.dirname(commonDir) : commonDir;
2048
+ return path9.join(path9.dirname(repoDir), `${repoName(commonDir)}.worktrees`, slug);
2049
+ }
2050
+ var realGit = {
2051
+ async place(dir) {
2052
+ const out = await git2(dir, ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-dir", "--git-common-dir"]);
2053
+ const [root, gitDir, commonDir] = out?.trim().split(/\r?\n/) ?? [];
2054
+ if (!root || !gitDir || !commonDir) return null;
2055
+ const branch = (await git2(dir, ["symbolic-ref", "--quiet", "--short", "HEAD"]))?.trim() || null;
2056
+ const detached = !branch && await git2(dir, ["rev-parse", "--verify", "--quiet", "HEAD"]) !== null;
2057
+ return { root: path9.resolve(root), commonDir: path9.resolve(commonDir), linked: !samePath(gitDir, commonDir), branch, detached };
2058
+ },
2059
+ async worktrees(dir) {
2060
+ const out = await git2(dir, ["worktree", "list", "--porcelain"]);
2061
+ return out ? parseWorktreeList(out).map((w) => ({ ...w, path: path9.resolve(w.path) })) : [];
2062
+ },
2063
+ async branchExists(dir, branch) {
2064
+ return await git2(dir, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]) !== null;
2065
+ },
2066
+ async checkBranch(dir, branch) {
2067
+ if (!branch || branch.startsWith("-")) return `"${branch}" is not a usable branch name`;
2068
+ return await git2(dir, ["check-ref-format", "--branch", branch]) === null ? `"${branch}" is not a valid branch name` : null;
2069
+ },
2070
+ async addWorktree(dir, spec) {
2071
+ const args = spec.create ? ["worktree", "add", "-b", spec.branch, spec.path, ...spec.base ? [spec.base] : []] : ["worktree", "add", spec.path, spec.branch];
2072
+ try {
2073
+ await run2("git", args, { cwd: dir, encoding: "utf8", timeout: 18e4 });
2074
+ return null;
2075
+ } catch (err) {
2076
+ const e = err;
2077
+ return (e.stderr || e.message).trim().split(/\r?\n/).slice(-3).join(" ");
2078
+ }
2079
+ }
2080
+ };
2081
+
2082
+ // src/type-prompt.ts
2083
+ var PASTE_SETTLE_MS = 60;
2084
+ function cleanPrompt(text2) {
2085
+ return String(text2 ?? "").replace(/\x1b\[20[01]~/g, "").replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "").trimEnd();
2086
+ }
2087
+ function typePrompt(target, text2) {
2088
+ target.write(`\x1B[200~${text2}\x1B[201~`);
2089
+ setTimeout(() => target.write("\r"), PASTE_SETTLE_MS).unref?.();
2090
+ }
2091
+
2092
+ // src/transcript.ts
2093
+ import { open, readdir as readdir3, stat as stat3 } from "node:fs/promises";
2094
+ import path10 from "node:path";
2095
+ var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
2096
+ var WHOLE_BYTES = 8 << 20;
2097
+ var HEAD_BYTES = 512 << 10;
2098
+ var TAIL_BYTES = 8 << 20;
2099
+ function humanPrompt(j) {
2100
+ const msg = j["message"];
2101
+ if (j["isMeta"] || j["isSidechain"]) return null;
2102
+ const origin = j["origin"];
2103
+ if (origin && origin.kind !== "human") return null;
2104
+ let text2 = null;
2105
+ if (typeof msg?.content === "string") text2 = msg.content;
2106
+ else if (Array.isArray(msg?.content)) {
2107
+ const blocks = msg.content;
2108
+ if (blocks.some((b) => b.type === "tool_result")) return null;
2109
+ text2 = blocks.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n") || null;
2110
+ }
2111
+ text2 = text2?.trim() ?? null;
2112
+ if (!text2 || text2.startsWith("<")) return null;
2113
+ return text2;
2114
+ }
2115
+ function parseTranscript(lines) {
2116
+ let title = null;
2117
+ const turns = [];
2118
+ for (const line of lines) {
2119
+ if (!line.trim()) continue;
2120
+ let j;
2121
+ try {
2122
+ j = JSON.parse(line);
2123
+ } catch {
2124
+ continue;
2125
+ }
2126
+ const at = typeof j["timestamp"] === "string" ? j["timestamp"] : null;
2127
+ if (j["type"] === "ai-title" && typeof j["aiTitle"] === "string") {
2128
+ title = j["aiTitle"];
2129
+ continue;
2130
+ }
2131
+ if (j["type"] === "user") {
2132
+ const text2 = humanPrompt(j);
2133
+ if (text2) turns.push({ role: "user", text: text2, at });
2134
+ continue;
2135
+ }
2136
+ if (j["type"] !== "assistant" || j["isSidechain"]) continue;
2137
+ const blocks = j["message"]?.content;
2138
+ if (!Array.isArray(blocks)) continue;
2139
+ const texts = [];
2140
+ const files = [];
2141
+ for (const b of blocks) {
2142
+ if (b.type === "text" && b.text?.trim()) texts.push(b.text.trim());
2143
+ if (b.type === "tool_use" && b.name && EDIT_TOOLS.has(b.name)) {
2144
+ const f = b.input?.["file_path"] ?? b.input?.["notebook_path"];
2145
+ if (typeof f === "string") files.push(f);
2146
+ }
2147
+ }
2148
+ if (!texts.length && !files.length) continue;
2149
+ const last = turns[turns.length - 1];
2150
+ if (last?.role === "assistant") {
2151
+ if (texts.length) last.text = [last.text, ...texts].filter(Boolean).join("\n\n");
2152
+ if (files.length) last.files = [.../* @__PURE__ */ new Set([...last.files ?? [], ...files])];
2153
+ } else {
2154
+ turns.push({ role: "assistant", text: texts.join("\n\n"), at, ...files.length ? { files: [...new Set(files)] } : {} });
2155
+ }
2156
+ }
2157
+ return { title, turns };
2158
+ }
2159
+ async function readRange(file, start, length) {
2160
+ const fh = await open(file, "r");
2161
+ try {
2162
+ const buf = Buffer.alloc(length);
2163
+ const { bytesRead } = await fh.read(buf, 0, length, start);
2164
+ return buf.subarray(0, bytesRead).toString("utf8");
2165
+ } finally {
2166
+ await fh.close();
2167
+ }
2168
+ }
2169
+ var cache = /* @__PURE__ */ new Map();
2170
+ var CACHE_LIMIT = 48;
2171
+ async function readTranscript(file) {
2172
+ let info;
2173
+ try {
2174
+ info = await stat3(file);
2175
+ } catch {
2176
+ return null;
2177
+ }
2178
+ const key = `${info.size}:${info.mtimeMs}`;
2179
+ const hit = cache.get(file);
2180
+ if (hit?.key === key) return hit.value;
2181
+ let lines;
2182
+ let partial = false;
2183
+ try {
2184
+ if (info.size <= WHOLE_BYTES) {
2185
+ lines = (await readRange(file, 0, info.size)).split("\n");
2186
+ } else {
2187
+ const head2 = (await readRange(file, 0, HEAD_BYTES)).split("\n").slice(0, -1);
2188
+ const tail = (await readRange(file, info.size - TAIL_BYTES, TAIL_BYTES)).split("\n").slice(1);
2189
+ lines = [...head2, ...tail];
2190
+ partial = true;
2191
+ }
2192
+ } catch {
2193
+ return null;
2194
+ }
2195
+ const value = { ...parseTranscript(lines), partial };
2196
+ cache.delete(file);
2197
+ cache.set(file, { key, value });
2198
+ if (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
2199
+ return value;
2200
+ }
2201
+ async function findTranscript(projectsDir, id) {
2202
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return null;
2203
+ let dirs;
2204
+ try {
2205
+ dirs = await readdir3(projectsDir);
2206
+ } catch {
2207
+ return null;
2208
+ }
2209
+ for (const d of dirs) {
2210
+ const f = path10.join(projectsDir, d, `${id}.jsonl`);
2211
+ try {
2212
+ if ((await stat3(f)).isFile()) return f;
2213
+ } catch {
2214
+ }
2215
+ }
2216
+ return null;
2217
+ }
2218
+
2219
+ // src/orchestrator-tools.ts
2220
+ var ToolError = class extends Error {
2221
+ };
2222
+ var SESSION_REF = {
2223
+ type: "string",
2224
+ description: 'A session id from list_sessions, or "<project>/<slot>" such as "tring.chat/3". A bare slot number means the project the user is viewing.'
2225
+ };
2226
+ var TOOLS = [
2227
+ {
2228
+ name: "list_sessions",
2229
+ description: "Every project and terminal tile in tring: slot, name, status (busy = working, done = finished and waiting for the user, idle, exited), the directory its agent is working in, its git repository, worktree and branch, whether it runs Claude Code, what it is waiting on, and the last thing its agent said. Flags tiles that share a worktree. Call this first to know what is going on.",
2230
+ inputSchema: {
2231
+ type: "object",
2232
+ properties: { project: { type: "string", description: "Only this project (name or id)." } },
2233
+ additionalProperties: false
2234
+ }
2235
+ },
2236
+ {
2237
+ name: "list_worktrees",
2238
+ description: "Every git worktree of each project's repository (and of any repository a tile is in): path, branch, whether it is the main checkout, and which tiles are working in it. Use it to find a free worktree for new work, or to see where a branch is checked out.",
2239
+ inputSchema: {
2240
+ type: "object",
2241
+ properties: { project: { type: "string", description: "Only this project's repository (name or id)." } },
2242
+ additionalProperties: false
2243
+ }
2244
+ },
2245
+ {
2246
+ name: "find_work",
2247
+ description: 'Which tiles have been working on something: ranks every tile by how well the request matches its name, branch, worktree, conversation title, the prompts it was given, what its agent said and the files it edited. Use it whenever the user refers to work by topic ("the reporting box", "the login bug") instead of by tile.',
2248
+ inputSchema: {
2249
+ type: "object",
2250
+ properties: { query: { type: "string", description: 'What the user is talking about, in their words, e.g. "reporting box colour".' } },
2251
+ required: ["query"],
2252
+ additionalProperties: false
2253
+ }
2254
+ },
2255
+ {
2256
+ name: "session_history",
2257
+ description: "A tile's Claude Code conversation: the prompts it was given, what its agent answered and the files it edited, newest last. With `search`, only the turns that mention it. Use it to confirm a tile is the one working on something before sending it work.",
2258
+ inputSchema: {
2259
+ type: "object",
2260
+ properties: {
2261
+ session: SESSION_REF,
2262
+ turns: { type: "integer", minimum: 1, maximum: 60, description: "How many recent turns, default 12." },
2263
+ search: { type: "string", description: "Only turns mentioning these words." }
2264
+ },
2265
+ required: ["session"],
2266
+ additionalProperties: false
2267
+ }
2268
+ },
2269
+ {
2270
+ name: "read_session",
2271
+ description: "The last lines of a tile's terminal (screen and scrollback) as plain text: what its agent or shell is showing right now.",
2272
+ inputSchema: {
2273
+ type: "object",
2274
+ properties: {
2275
+ session: SESSION_REF,
2276
+ lines: { type: "integer", minimum: 1, maximum: 400, description: "How many lines, default 80." }
2277
+ },
2278
+ required: ["session"],
2279
+ additionalProperties: false
2280
+ }
2281
+ },
2282
+ {
2283
+ name: "session_changes",
2284
+ description: "The uncommitted git changes in the worktree a tile's agent is working in: files with lines added and removed, and the patch (all files, trimmed, or one file in full).",
2285
+ inputSchema: {
2286
+ type: "object",
2287
+ properties: {
2288
+ session: SESSION_REF,
2289
+ file: { type: "string", description: "Only this file's patch (a path from the file list)." }
2290
+ },
2291
+ required: ["session"],
2292
+ additionalProperties: false
2293
+ }
2294
+ },
2295
+ {
2296
+ name: "send_prompt",
2297
+ description: "Send a prompt to the Claude Code agent in a tile, as if the user typed it there and pressed Enter. Only works on tiles running Claude Code that are not waiting on a permission prompt or question. A busy agent queues it. Use wait_for afterwards to get its answer.",
2298
+ inputSchema: {
2299
+ type: "object",
2300
+ properties: {
2301
+ session: SESSION_REF,
2302
+ text: { type: "string", description: "The prompt. Write it as a complete instruction; that agent cannot see this conversation." }
2303
+ },
2304
+ required: ["session", "text"],
2305
+ additionalProperties: false
2306
+ }
2307
+ },
2308
+ {
2309
+ name: "create_session",
2310
+ description: "Start a new tile running Claude Code in the first empty slot of a project, optionally with a first prompt. Give `branch` to run it in a git worktree for that branch: an existing worktree that has the branch checked out is reused; otherwise a new worktree is added (checking out the branch if it exists, or creating it from `base`). One agent per worktree: parallel work gets its own branch. The user sees the new tile in the ring.",
2311
+ inputSchema: {
2312
+ type: "object",
2313
+ properties: {
2314
+ project: { type: "string", description: "Project name or id; default the project the user is viewing." },
2315
+ cwd: { type: "string", description: "Working directory, or with `branch` the repository to add the worktree to; default the project root. A relative path is resolved against the root." },
2316
+ branch: { type: "string", description: 'Run in a worktree for this branch, e.g. "feature/CHV-3193-login".' },
2317
+ base: { type: "string", description: "With a new `branch`: what to branch from (branch, tag or commit); default the repository's current HEAD." },
2318
+ worktree_path: { type: "string", description: "With `branch`: where to put a new worktree. Default: beside the existing worktrees, or <parent>/<repo>.worktrees/<branch>." },
2319
+ name: { type: "string", description: 'A short tile name, e.g. "api tests"; defaults to the branch.' },
2320
+ prompt: { type: "string", description: "First prompt, sent once Claude Code is ready." }
2321
+ },
2322
+ additionalProperties: false
2323
+ }
2324
+ },
2325
+ {
2326
+ name: "wait_for",
2327
+ description: "Wait until the given tiles finish their current work (or need the user, or exit), then return each one's status and last message. Use after send_prompt or create_session.",
2328
+ inputSchema: {
2329
+ type: "object",
2330
+ properties: {
2331
+ sessions: { type: "array", items: SESSION_REF, minItems: 1 },
2332
+ timeout_seconds: { type: "integer", minimum: 5, maximum: 900, description: "Default 300." }
2333
+ },
2334
+ required: ["sessions"],
2335
+ additionalProperties: false
2336
+ }
2337
+ }
2338
+ ];
2339
+ var MAX_LAST_MESSAGE = 600;
2340
+ var MAX_PATCH_CHARS = 16e3;
2341
+ var READY_TIMEOUT_MS = 3e4;
2342
+ var READY_SETTLE_MS = 1500;
2343
+ var PROMPT_GRACE_MS = 15e3;
2344
+ var clip = (s, n) => s.length > n ? `${s.slice(0, n)}\u2026 (${s.length - n} more characters)` : s;
2345
+ async function isDirectory(p) {
2346
+ try {
2347
+ return (await stat4(p)).isDirectory();
2348
+ } catch {
2349
+ return false;
2350
+ }
2351
+ }
2352
+ var workdir = (s) => s.agentCwd ?? s.cwd;
2353
+ var OrchestratorTools = class {
2354
+ constructor(d) {
2355
+ this.d = d;
2356
+ }
2357
+ get now() {
2358
+ return (this.d.now ?? Date.now)();
2359
+ }
2360
+ get git() {
2361
+ return this.d.git ?? realGit;
2362
+ }
2363
+ sleep(ms) {
2364
+ return (this.d.sleep ?? ((t) => new Promise((r) => setTimeout(r, t))))(ms);
2365
+ }
2366
+ async call(name, args, signal) {
2367
+ switch (name) {
2368
+ case "list_sessions":
2369
+ return this.listSessions(str(args["project"]));
2370
+ case "list_worktrees":
2371
+ return this.listWorktrees(str(args["project"]));
2372
+ case "find_work":
2373
+ return this.findWork(String(args["query"] ?? ""));
2374
+ case "session_history":
2375
+ return this.sessionHistory(this.resolve(args["session"]), num(args["turns"]) ?? 12, str(args["search"]));
2376
+ case "read_session":
2377
+ return this.readSession(this.resolve(args["session"]), num(args["lines"]) ?? 80);
2378
+ case "session_changes":
2379
+ return this.changes(this.resolve(args["session"]), str(args["file"]));
2380
+ case "send_prompt":
2381
+ return this.sendPrompt(this.resolve(args["session"]), String(args["text"] ?? ""));
2382
+ case "create_session":
2383
+ return this.createSession(args, signal);
2384
+ case "wait_for":
2385
+ return this.waitFor(args, signal);
2386
+ }
2387
+ throw new ToolError(`unknown tool ${name}`);
2388
+ }
2389
+ /** "<project>/<slot>", a session id, or a slot in the viewed project. */
2390
+ resolve(ref) {
2391
+ const r = String(ref ?? "").trim();
2392
+ if (!r) throw new ToolError("session is required");
2393
+ const byId = this.d.pm.findSession(r);
2394
+ if (byId) return byId;
2395
+ const at = r.lastIndexOf("/");
2396
+ const projectRef = at >= 0 ? r.slice(0, at) : null;
2397
+ const slot = Number(at >= 0 ? r.slice(at + 1) : r);
2398
+ const project = projectRef !== null ? this.d.pm.findProject(projectRef) : this.d.pm.list().find((p) => p.id === this.d.pm.activeProjectId);
2399
+ if (!project) throw new ToolError(`no project ${projectRef ?? "(none is being viewed)"}; see list_sessions`);
2400
+ if (!Number.isInteger(slot)) throw new ToolError(`cannot read "${r}" as a session; use an id or "<project>/<slot>"`);
2401
+ const info = project.sessions.find((s2) => s2.slot === slot);
2402
+ const s = info && this.d.pm.findSession(info.id);
2403
+ if (!s) throw new ToolError(`slot ${slot} in ${project.name} is empty`);
2404
+ return s;
2405
+ }
2406
+ ref(s) {
2407
+ const project = this.d.pm.list().find((p) => p.id === s.projectId);
2408
+ return `${project?.name ?? "project"}/${s.slot}`;
2409
+ }
2410
+ label(s) {
2411
+ return `${this.ref(s)}${s.name ? ` (${s.name})` : ""}`;
2412
+ }
2413
+ waiting(s) {
2414
+ return this.d.inbox.list().filter((i) => i.sessionId === s.id && i.kind !== "reply");
2415
+ }
2416
+ allSessions() {
2417
+ return this.d.pm.list().flatMap((p) => p.sessions).map((i) => this.d.pm.findSession(i.id)).filter((s) => !!s);
2418
+ }
2419
+ /** Every tile with its repository and worktree, in one pass of git calls. */
2420
+ async placeAll(sessions = this.allSessions()) {
2421
+ const memo = /* @__PURE__ */ new Map();
2422
+ const place = (dir) => {
2423
+ const k = normal(dir);
2424
+ if (!memo.has(k)) memo.set(k, this.git.place(dir));
2425
+ return memo.get(k);
2426
+ };
2427
+ return Promise.all(sessions.map(async (s) => ({ s, ref: this.ref(s), place: await place(workdir(s)) })));
2428
+ }
2429
+ /** Other live tiles whose agents are in the same worktree as `p`. */
2430
+ sharing(p, all) {
2431
+ if (!p.place) return [];
2432
+ return all.filter((o) => o.s.id !== p.s.id && o.place && o.s.tracker.status !== "exited" && samePath(o.place.root, p.place.root));
2433
+ }
2434
+ async listSessions(only) {
2435
+ let projects = this.d.pm.list();
2436
+ if (only) {
2437
+ const p = this.d.pm.findProject(only);
2438
+ if (!p) throw new ToolError(`no project ${only}; projects: ${projects.map((x) => x.name).join(", ")}`);
2439
+ projects = [p];
2440
+ }
2441
+ const placed = await this.placeAll();
2442
+ const byId = new Map(placed.map((p) => [p.s.id, p]));
2443
+ const talks = new Map(await Promise.all(placed.map(async (p) => [p.s.id, await this.history(p.s)])));
2444
+ const out = projects.map((p) => ({
2445
+ project: p.name,
2446
+ id: p.id,
2447
+ root: p.root,
2448
+ viewing: p.id === this.d.pm.activeProjectId,
2449
+ sessions: p.sessions.map((info) => {
2450
+ const pl = byId.get(info.id);
2451
+ const s = pl?.s;
2452
+ const waiting = s ? this.waiting(s) : [];
2453
+ const shared = pl ? this.sharing(pl, placed).map((o) => o.ref) : [];
2454
+ const agentDir = s?.agentCwd && !samePath(s.agentCwd, info.cwd) ? s.agentCwd : null;
2455
+ return {
2456
+ ref: `${p.name}/${info.slot}`,
2457
+ id: info.id,
2458
+ slot: info.slot,
2459
+ name: info.name ?? info.title ?? null,
2460
+ status: info.status,
2461
+ cwd: info.cwd,
2462
+ ...agentDir ? { agentCwd: agentDir } : {},
2463
+ git: pl?.place ? gitSummary(pl.place) : null,
2464
+ ...shared.length ? { sameWorktreeAs: shared } : {},
2465
+ agent: s?.claude ? "claude" : null,
2466
+ ...conversationSummary(talks.get(info.id) ?? null),
2467
+ ...waiting.length ? { waitingOnUser: waiting.map(summary) } : {},
2468
+ ...s?.lastMessage ? { lastMessage: clip(s.lastMessage, MAX_LAST_MESSAGE) } : {}
2469
+ };
2470
+ })
2471
+ }));
2472
+ return JSON.stringify({ projects: out }, null, 2);
2473
+ }
2474
+ async listWorktrees(only) {
2475
+ let projects = this.d.pm.list();
2476
+ if (only) {
2477
+ const p = this.d.pm.findProject(only);
2478
+ if (!p) throw new ToolError(`no project ${only}; projects: ${projects.map((x) => x.name).join(", ")}`);
2479
+ projects = [p];
2480
+ }
2481
+ const placed = await this.placeAll();
2482
+ const repos = /* @__PURE__ */ new Map();
2483
+ const add2 = (place, dir, project) => {
2484
+ if (!place) return;
2485
+ const k = normal(place.commonDir);
2486
+ const r = repos.get(k) ?? { dir, projects: /* @__PURE__ */ new Set() };
2487
+ if (project) r.projects.add(project);
2488
+ repos.set(k, r);
2489
+ };
2490
+ const roots = await Promise.all(projects.map(async (p) => ({ p, place: await this.git.place(p.root) })));
2491
+ for (const { p, place } of roots) add2(place, p.root, p.name);
2492
+ const wanted = new Set(projects.map((p) => p.id));
2493
+ for (const pl of placed) if (wanted.has(pl.s.projectId)) add2(pl.place, workdir(pl.s));
2494
+ if (repos.size === 0) return "No git repositories: none of these projects or tiles is inside one.";
2495
+ const out = await Promise.all([...repos.entries()].map(async ([commonDir, r]) => {
2496
+ const trees = await this.git.worktrees(r.dir);
2497
+ return {
2498
+ repo: repoName(commonDir),
2499
+ ...r.projects.size ? { projects: [...r.projects] } : {},
2500
+ // git lists the main worktree first; in a bare-repo layout that entry
2501
+ // is the bare repository itself, and every checkout is a linked one.
2502
+ worktrees: trees.map((w, i) => ({ w, main: i === 0 && !w.bare })).filter(({ w }) => !w.bare).map(({ w, main: main2 }) => {
2503
+ const tiles = placed.filter((pl) => pl.place && samePath(pl.place.root, w.path));
2504
+ return {
2505
+ path: w.path,
2506
+ branch: w.branch ?? (w.detached ? "(detached)" : null),
2507
+ main: main2,
2508
+ tiles: tiles.map((t) => `${t.ref} ${t.s.tracker.status}${t.s.claude ? " claude" : ""}`),
2509
+ ...w.locked ? { locked: true } : {},
2510
+ ...w.prunable ? { prunable: true } : {}
2511
+ };
2512
+ })
2513
+ };
2514
+ }));
2515
+ return JSON.stringify({ repos: out }, null, 2);
2516
+ }
2517
+ /** The tile's conversation, from the transcript its hooks named, or found by id. */
2518
+ async history(s) {
2519
+ const t = this.d.transcripts ?? {
2520
+ read: readTranscript,
2521
+ find: (id) => findTranscript(defaultTranscriptDir(), id)
2522
+ };
2523
+ const file = s.transcript ?? (s.claude ? await t.find(s.claude.id) : null);
2524
+ return file ? t.read(file) : null;
2525
+ }
2526
+ async sessionHistory(s, count, search) {
2527
+ const talk = await this.history(s);
2528
+ if (!talk) {
2529
+ return `${this.label(s)}: no conversation to read${s.claude ? " (its transcript was not found)" : " \u2014 it is not running Claude Code"}.`;
2530
+ }
2531
+ const n = Math.max(1, Math.min(60, Math.floor(count)));
2532
+ let turns = talk.turns;
2533
+ if (search) {
2534
+ const ws = words(search);
2535
+ turns = turns.filter((t) => ws.some((w) => turnText(t).toLowerCase().includes(w)));
2536
+ if (!turns.length) return `${this.label(s)}: nothing in its conversation mentions "${search}".`;
2537
+ }
2538
+ const shown = turns.slice(-n);
2539
+ const head2 = `${this.label(s)}${talk.title ? ` \u2014 "${talk.title}"` : ""}: ${shown.length} of ${turns.length} ${search ? "matching " : ""}turn(s)${talk.partial ? " (a very long conversation: only its start and end were read)" : ""}`;
2540
+ const body = shown.map((t) => {
2541
+ const who = t.role === "user" ? "PROMPT" : "AGENT";
2542
+ const files = t.files?.length ? `
2543
+ (edited: ${t.files.join(", ")})` : "";
2544
+ return `[${who}${t.at ? ` ${t.at.slice(0, 16).replace("T", " ")}` : ""}]
2545
+ ${clip(t.text, t.role === "user" ? 800 : 1500)}${files}`;
2546
+ });
2547
+ return `${head2}
2548
+
2549
+ ${body.join("\n\n")}`;
2550
+ }
2551
+ /**
2552
+ * Ranks tiles against what the user said. Each word counts for more the
2553
+ * fewer tiles mention it — "change" is everywhere, "reporting" is not — and
2554
+ * what a tile was asked, titled or edited counts for more than what its
2555
+ * agent happened to say, as do its recent turns over its old ones.
2556
+ */
2557
+ async findWork(query) {
2558
+ const ws = words(query);
2559
+ if (!ws.length) throw new ToolError('say what the work is about, e.g. "reporting box"');
2560
+ const placed = await this.placeAll();
2561
+ const docs = await Promise.all(placed.map(async (p) => {
2562
+ const talk = await this.history(p.s);
2563
+ const fields = [
2564
+ { why: "name", text: [p.s.name, p.s.title].filter(Boolean).join(" "), weight: 4 },
2565
+ { why: "branch", text: [p.place?.branch, p.place?.root].filter(Boolean).join(" "), weight: 4 },
2566
+ { why: "title", text: talk?.title ?? "", weight: 4 },
2567
+ { why: "last message", text: p.s.lastMessage ?? "", weight: 1 }
2568
+ ];
2569
+ const turns = talk?.turns ?? [];
2570
+ turns.forEach((t, i) => {
2571
+ const recent = i >= turns.length - 10 ? 2 : 1;
2572
+ if (t.role === "user") fields.push({ why: "prompt", text: t.text, weight: 3 * recent });
2573
+ else fields.push({ why: "agent said", text: t.text, weight: recent });
2574
+ if (t.files?.length) fields.push({ why: "edited", text: t.files.join(" "), weight: 3 * recent });
2575
+ });
2576
+ return { p, fields };
2577
+ }));
2578
+ const df = new Map(ws.map((w) => [w, docs.filter((d) => d.fields.some((f) => f.text.toLowerCase().includes(w))).length]));
2579
+ const ranked = docs.map(({ p, fields }) => {
2580
+ let score = 0;
2581
+ const why = /* @__PURE__ */ new Set();
2582
+ let best = null;
2583
+ let confident = false;
2584
+ for (const f of fields) {
2585
+ const low = f.text.toLowerCase();
2586
+ const hit = ws.filter((w) => low.includes(w));
2587
+ if (!hit.length) continue;
2588
+ const s = f.weight * hit.reduce((n, w) => n + 1 / df.get(w), 0) * (hit.length === ws.length ? 2 : 1);
2589
+ score += s;
2590
+ why.add(f.why);
2591
+ if (!best || s > best.score) best = { score: s, text: snippet(f.text, hit[0]) };
2592
+ if (hit.length === ws.length || STRONG.has(f.why) && hit.length >= ws.length / 2) confident = true;
2593
+ }
2594
+ return { p, score, confident, why: [...why], snippet: best?.text ?? "" };
2595
+ }).filter((r) => r.score > 0).sort((a, b) => b.score - a.score);
2596
+ const top = ranked.slice(0, 5);
2597
+ const lines = top.map((r) => `- ${this.label(r.p.s)} \u2014 ${r.p.s.tracker.status}${r.p.place?.branch ? `, on ${r.p.place.branch}` : ""} (score ${r.score.toFixed(1)}; matched ${r.why.join(", ")})
2598
+ "${r.snippet}"`);
2599
+ const sure = top.filter((r) => r.confident);
2600
+ if (!sure.length) {
2601
+ return `No tile clearly matches "${query}". Ask the user which tile, or offer a new one in its own worktree.` + (lines.length ? `
2602
+
2603
+ Only passing mentions:
2604
+ ${lines.join("\n")}` : "");
2605
+ }
2606
+ const close = sure.length > 1 && sure[1].score >= sure[0].score * 0.75;
2607
+ const verdict = close ? "Two or more tiles match about equally: ask the user which one before sending anything." : `Best match: ${this.label(sure[0].p.s)}. Confirm with session_history if unsure.`;
2608
+ return `${verdict}
2609
+
2610
+ ${lines.join("\n")}`;
2611
+ }
2612
+ readSession(s, lines) {
2613
+ const n = Math.max(1, Math.min(400, Math.floor(lines)));
2614
+ return `${this.label(s)} \u2014 ${s.tracker.status}, ${workdir(s)}
2615
+
2616
+ ${s.recentText(n) || "(nothing on screen)"}`;
2617
+ }
2618
+ async changes(s, file) {
2619
+ const r = await (this.d.diff ?? gitDiff)(workdir(s));
2620
+ if ("error" in r) return `${this.label(s)}: ${r.error}`;
2621
+ if (r.files.length === 0) return `${this.label(s)}: no uncommitted changes in ${r.cwd}`;
2622
+ const list = r.files.map((f) => `${f.path} +${f.added} -${f.removed}${f.note ? ` (${f.note})` : ""}`);
2623
+ const head2 = `${this.label(s)}: ${r.files.length} changed file(s) in ${r.cwd}${r.truncated ? " (patch truncated)" : ""}
2624
+ ${list.join("\n")}`;
2625
+ if (file) {
2626
+ const f = r.files.find((x) => x.path === file || x.path.endsWith(`/${file}`));
2627
+ if (!f) throw new ToolError(`${file} has no changes; changed: ${r.files.map((x) => x.path).join(", ")}`);
2628
+ return `${head2}
2629
+
2630
+ --- ${f.path}
2631
+ ${clip(f.patch || f.note || "", MAX_PATCH_CHARS * 2)}`;
2632
+ }
2633
+ let budget = MAX_PATCH_CHARS;
2634
+ const patches = [];
2635
+ for (const f of r.files) {
2636
+ if (!f.patch || budget <= 0) continue;
2637
+ const p = clip(f.patch, budget);
2638
+ budget -= p.length;
2639
+ patches.push(`--- ${f.path}
2640
+ ${p}`);
2641
+ }
2642
+ const rest = budget <= 0 ? "\n\n(more patches left out; ask for one file with `file`)" : "";
2643
+ return `${head2}
2644
+
2645
+ ${patches.join("\n\n")}${rest}`;
2646
+ }
2647
+ /** Why this tile cannot take a prompt now, or null when it can. */
2648
+ refusal(s) {
2649
+ if (s.tracker.status === "exited") return `${this.label(s)} has exited`;
2650
+ if (!s.claude) {
2651
+ return `${this.label(s)} is not running Claude Code (or tring's hooks are not installed, so it cannot tell). send_prompt only talks to agents; use create_session to start one.`;
2652
+ }
2653
+ const waiting = this.waiting(s);
2654
+ if (waiting.length) {
2655
+ return `${this.label(s)} is waiting on the user (${waiting.map(summary).join("; ")}). Ask the user to answer it in the inbox first; typing now would land in that dialog.`;
2656
+ }
2657
+ return null;
2658
+ }
2659
+ deliver(s, text2) {
2660
+ s.prompted();
2661
+ (this.d.type ?? typePrompt)(s, text2);
2662
+ }
2663
+ /** A warning for the agent when another agent is busy in the same worktree. */
2664
+ async crowding(s) {
2665
+ const placed = await this.placeAll();
2666
+ const me = placed.find((p) => p.s.id === s.id);
2667
+ const busy = me ? this.sharing(me, placed).filter((o) => o.s.claude && o.s.tracker.status === "busy") : [];
2668
+ if (!busy.length || !me?.place) return "";
2669
+ return ` Warning: ${busy.map((o) => o.ref).join(", ")} ${busy.length === 1 ? "is" : "are"} also working in ${me.place.root}; two agents in one worktree edit the same files. Prefer a worktree per task.`;
2670
+ }
2671
+ async sendPrompt(s, raw) {
2672
+ const text2 = cleanPrompt(raw);
2673
+ if (!text2) throw new ToolError("text is empty");
2674
+ const why = this.refusal(s);
2675
+ if (why) throw new ToolError(why);
2676
+ const busy = s.tracker.status === "busy";
2677
+ const warning = await this.crowding(s);
2678
+ this.deliver(s, text2);
2679
+ return `Sent to ${this.label(s)}${busy ? " (it was busy, so Claude Code queues it)" : ""}.${warning} Use wait_for with "${s.id}" for the answer.`;
2680
+ }
2681
+ /**
2682
+ * The worktree for `branch`: the one it is already checked out in, or a new
2683
+ * one. Returns the directory to start in, and what was done, in words.
2684
+ */
2685
+ async worktreeFor(repoDir, args) {
2686
+ const branch = str(args["branch"]);
2687
+ const git3 = this.git;
2688
+ const place = await git3.place(repoDir);
2689
+ if (!place) throw new ToolError(`${repoDir} is not inside a git repository, so there is no worktree to make`);
2690
+ const bad = await git3.checkBranch(repoDir, branch);
2691
+ if (bad) throw new ToolError(bad);
2692
+ const trees = await git3.worktrees(repoDir);
2693
+ const there = trees.find((w) => w.branch === branch && !w.prunable);
2694
+ if (there) {
2695
+ const inside2 = (await this.placeAll()).filter((p) => p.place && samePath(p.place.root, there.path) && p.s.tracker.status !== "exited");
2696
+ const crowd = inside2.length ? ` Warning: ${inside2.map((p) => p.ref).join(", ")} ${inside2.length === 1 ? "is" : "are"} already in that worktree; one agent per worktree, so make sure they are not both working, or use a new branch.` : "";
2697
+ return { dir: there.path, note: `Reused the existing worktree ${there.path}, which has ${branch} checked out.${crowd}` };
2698
+ }
2699
+ const base2 = str(args["base"]);
2700
+ if (base2?.startsWith("-")) throw new ToolError(`"${base2}" is not a usable base`);
2701
+ const exists = await git3.branchExists(repoDir, branch);
2702
+ const wanted = str(args["worktree_path"]);
2703
+ const dir = wanted ? path11.resolve(repoDir, wanted) : defaultWorktreePath(place.commonDir, trees, branch);
2704
+ if (await (this.d.isDir ?? isDirectory)(dir)) throw new ToolError(`${dir} already exists; pick another worktree_path`);
2705
+ const err = await git3.addWorktree(repoDir, { path: dir, branch, create: !exists, ...base2 && !exists ? { base: base2 } : {} });
2706
+ if (err) throw new ToolError(`git worktree add failed: ${err}`);
2707
+ const what = exists ? `checked out the existing branch ${branch}` : `created ${branch} from ${base2 ?? "the current HEAD"}`;
2708
+ return { dir, note: `Added the worktree ${dir} and ${what}.` };
2709
+ }
2710
+ async createSession(args, signal) {
2711
+ const projectRef = str(args["project"]);
2712
+ const project = projectRef ? this.d.pm.findProject(projectRef) : this.d.pm.list().find((p) => p.id === this.d.pm.activeProjectId) ?? this.d.pm.list()[0];
2713
+ if (!project) throw new ToolError(projectRef ? `no project ${projectRef}; see list_sessions` : "there are no projects yet");
2714
+ const cwdArg = str(args["cwd"]);
2715
+ let cwd = cwdArg ? path11.resolve(project.root, cwdArg) : project.root;
2716
+ if (!await (this.d.isDir ?? isDirectory)(cwd)) throw new ToolError(`${cwd} is not a directory`);
2717
+ const branch = str(args["branch"]);
2718
+ let note = "";
2719
+ if (branch) {
2720
+ const wt = await this.worktreeFor(cwd, args);
2721
+ cwd = wt.dir;
2722
+ note = ` ${wt.note}`;
2723
+ }
2724
+ let s;
2725
+ try {
2726
+ s = this.d.pm.create(project.id, { cwd, command: "claude", name: str(args["name"]) ?? branch ?? null });
2727
+ } catch (err) {
2728
+ throw new ToolError(`${err.message}.${note}`);
2729
+ }
2730
+ if (!s) throw new ToolError(`could not start a session.${note}`);
2731
+ const started = `Started ${this.label(s)} (id ${s.id}) running claude in ${cwd}.${note}`;
2732
+ const prompt = cleanPrompt(String(args["prompt"] ?? ""));
2733
+ if (!prompt) return started;
2734
+ const ready = await this.ready(s, signal);
2735
+ if (!ready) {
2736
+ return `${started} The first prompt was NOT sent: Claude Code did not report it was ready within ${READY_TIMEOUT_MS / 1e3}s (are tring's hooks installed? is the folder trusted?). Check with read_session, then use send_prompt.`;
2737
+ }
2738
+ this.deliver(s, prompt);
2739
+ return `${started} First prompt sent. Use wait_for with "${s.id}" for the answer.`;
2740
+ }
2741
+ /** Claude has started (SessionStart hook) and drawn its prompt. */
2742
+ async ready(s, signal) {
2743
+ const until = this.now + READY_TIMEOUT_MS;
2744
+ let since = null;
2745
+ while (this.now < until && !signal?.aborted) {
2746
+ if (s.tracker.status === "exited") return false;
2747
+ if (s.claude && s.tracker.status !== "busy") {
2748
+ since ??= this.now;
2749
+ if (this.now - since >= READY_SETTLE_MS) return true;
2750
+ } else {
2751
+ since = null;
2752
+ }
2753
+ await this.sleep(250);
2754
+ }
2755
+ return false;
2756
+ }
2757
+ async waitFor(args, signal) {
2758
+ const refs = Array.isArray(args["sessions"]) ? args["sessions"] : [args["sessions"]];
2759
+ const sessions = refs.map((r) => this.resolve(r));
2760
+ const timeout = Math.max(5, Math.min(900, num(args["timeout_seconds"]) ?? 300)) * 1e3;
2761
+ const until = this.now + timeout;
2762
+ while (!signal?.aborted) {
2763
+ if (sessions.every((s) => this.state(s) !== "working") || this.now >= until) break;
2764
+ await this.sleep(1e3);
2765
+ }
2766
+ const timedOut = sessions.some((s) => this.state(s) === "working");
2767
+ const lines = sessions.map((s) => {
2768
+ const st = this.state(s);
2769
+ const waiting = this.waiting(s);
2770
+ const said = s.lastMessage && s.stoppedAt >= s.promptedAt ? `
2771
+ ${clip(s.lastMessage, 4e3)}` : "";
2772
+ const why = st === "needs-user" ? ` \u2014 waiting on the user: ${waiting.map(summary).join("; ")}` : "";
2773
+ return `## ${this.label(s)} \u2014 ${st === "working" ? "still working" : st}${why}${said}`;
2774
+ });
2775
+ return (timedOut ? `Timed out after ${timeout / 1e3}s.
2776
+
2777
+ ` : "") + lines.join("\n\n");
2778
+ }
2779
+ state(s) {
2780
+ if (s.tracker.status === "exited") return "exited";
2781
+ if (this.waiting(s).length) return "needs-user";
2782
+ if (s.tracker.status === "busy") return "working";
2783
+ if (s.promptedAt > s.stoppedAt && this.now - s.promptedAt < PROMPT_GRACE_MS) return "working";
2784
+ return "finished";
2785
+ }
2786
+ };
2787
+ function conversationSummary(t) {
2788
+ if (!t) return {};
2789
+ const prompts = t.turns.filter((x) => x.role === "user").map((x) => clip(x.text.replace(/\s+/g, " "), 200));
2790
+ if (!t.title && !prompts.length) return {};
2791
+ return {
2792
+ conversation: {
2793
+ ...t.title ? { title: t.title } : {},
2794
+ ...prompts.length ? { firstPrompt: prompts[0] } : {},
2795
+ ...prompts.length > 1 ? { recentPrompts: prompts.slice(-3) } : {}
2796
+ }
2797
+ };
2798
+ }
2799
+ var STRONG = /* @__PURE__ */ new Set(["name", "branch", "title", "prompt", "edited"]);
2800
+ var STOP = /* @__PURE__ */ new Set([
2801
+ "the",
2802
+ "and",
2803
+ "for",
2804
+ "with",
2805
+ "that",
2806
+ "this",
2807
+ "from",
2808
+ "into",
2809
+ "onto",
2810
+ "then",
2811
+ "than",
2812
+ "please",
2813
+ "can",
2814
+ "could",
2815
+ "would",
2816
+ "should",
2817
+ "you",
2818
+ "your",
2819
+ "our",
2820
+ "its",
2821
+ "are",
2822
+ "was",
2823
+ "were",
2824
+ "has",
2825
+ "have",
2826
+ "had",
2827
+ "not",
2828
+ "but",
2829
+ "all",
2830
+ "any",
2831
+ "some",
2832
+ "one",
2833
+ "out",
2834
+ "make",
2835
+ "change",
2836
+ "update",
2837
+ "fix",
2838
+ "add",
2839
+ "set",
2840
+ "get",
2841
+ "put",
2842
+ "use",
2843
+ "now",
2844
+ "also",
2845
+ "just",
2846
+ "like",
2847
+ "want",
2848
+ "need",
2849
+ "tile",
2850
+ "terminal",
2851
+ "session",
2852
+ "agent",
2853
+ "work",
2854
+ "working",
2855
+ "thing",
2856
+ "there"
2857
+ ]);
2858
+ function words(query) {
2859
+ const out = query.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 3 && !STOP.has(w)).map((w) => w.length > 5 ? w.replace(/(ing|ed|es|s)$/, "") : w);
2860
+ return [...new Set(out)];
2861
+ }
2862
+ function turnText(t) {
2863
+ return `${t.text} ${t.files?.join(" ") ?? ""}`;
2864
+ }
2865
+ function snippet(text2, word) {
2866
+ const flat = text2.replace(/\s+/g, " ");
2867
+ const i = flat.toLowerCase().indexOf(word);
2868
+ const from = Math.max(0, i - 60);
2869
+ return `${from > 0 ? "\u2026" : ""}${flat.slice(from, from + 160)}${from + 160 < flat.length ? "\u2026" : ""}`;
2870
+ }
2871
+ function gitSummary(p) {
2872
+ return {
2873
+ repo: repoName(p.commonDir),
2874
+ branch: p.branch ?? (p.detached ? "(detached)" : null),
2875
+ worktree: p.root,
2876
+ linkedWorktree: p.linked
2877
+ };
2878
+ }
2879
+ function summary(i) {
2880
+ if (i.kind === "question") return `question: ${clip(i.questions?.map((q) => q.question).join(" / ") ?? "", 200)}`;
2881
+ const input = i.input ?? {};
2882
+ const what = String(input["command"] ?? input["file_path"] ?? input["url"] ?? "");
2883
+ return `permission for ${i.tool ?? "a tool"}${what ? `: ${clip(what, 200)}` : ""}`;
2884
+ }
2885
+ var str = (v) => typeof v === "string" && v.trim() ? v.trim() : void 0;
2886
+ var num = (v) => {
2887
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
2888
+ return Number.isFinite(n) ? n : void 0;
2889
+ };
2890
+
1918
2891
  // src/http.ts
1919
2892
  var MIME = {
1920
2893
  ".html": "text/html; charset=utf-8",
@@ -1987,14 +2960,14 @@ function createHandler(opts) {
1987
2960
  let usage = null;
1988
2961
  const homeDir = () => process.env["HOME"] ?? os5.homedir();
1989
2962
  const within = (root, dir) => {
1990
- const rel = path9.relative(path9.resolve(root), dir);
1991
- return rel === "" || !rel.startsWith("..") && !path9.isAbsolute(rel);
2963
+ const rel = path12.relative(path12.resolve(root), dir);
2964
+ return rel === "" || !rel.startsWith("..") && !path12.isAbsolute(rel);
1992
2965
  };
1993
2966
  const real = async (p) => {
1994
2967
  try {
1995
2968
  return await realpath(p);
1996
2969
  } catch {
1997
- return path9.resolve(p);
2970
+ return path12.resolve(p);
1998
2971
  }
1999
2972
  };
2000
2973
  const browsable = async (dir) => {
@@ -2023,8 +2996,10 @@ function createHandler(opts) {
2023
2996
  }
2024
2997
  const hook = url.pathname.match(/^\/api\/sessions\/([^/]+)\/hook$/);
2025
2998
  if (hook && req.method === "POST") {
2026
- const s = pm.findSession(decodeURIComponent(hook[1]));
2027
- if (!s) return json(res, 404, { error: "no such session" });
2999
+ const id = decodeURIComponent(hook[1]);
3000
+ const agent = opts.agentSession?.(id);
3001
+ const s = pm.findSession(id);
3002
+ if (!s && !agent) return json(res, 404, { error: "no such session" });
2028
3003
  const raw = await readBody(req);
2029
3004
  if (raw === null) return tooLarge(req, res, "body too large");
2030
3005
  let body;
@@ -2035,6 +3010,12 @@ function createHandler(opts) {
2035
3010
  }
2036
3011
  if (typeof body.event !== "string") return json(res, 400, { error: "event is required" });
2037
3012
  const payload = body.payload && typeof body.payload === "object" ? body.payload : {};
3013
+ if (agent) {
3014
+ const conv = body.event === "SessionStart" ? claudeConversation({ id: payload.session_id, cwd: payload.cwd }) : null;
3015
+ if (conv) agent.setClaude(conv);
3016
+ return json(res, 200, { output: null });
3017
+ }
3018
+ if (!s) return json(res, 404, { error: "no such session" });
2038
3019
  if (!opts.inbox) {
2039
3020
  if (body.event === "Stop" || body.event === "Notification") s.hook();
2040
3021
  return json(res, 200, { output: null });
@@ -2054,6 +3035,36 @@ function createHandler(opts) {
2054
3035
  if (gone.signal.aborted) return;
2055
3036
  return json(res, 200, { output });
2056
3037
  }
3038
+ if (url.pathname === "/api/orchestrator/tools" && req.method === "GET") {
3039
+ return json(res, 200, { tools: TOOLS });
3040
+ }
3041
+ if (url.pathname === "/api/orchestrator/call" && req.method === "POST") {
3042
+ const tools = opts.tools;
3043
+ if (!tools) return json(res, 503, { error: "the orchestrator agent is not available" });
3044
+ const raw = await readBody(req);
3045
+ if (raw === null) return tooLarge(req, res, "body too large");
3046
+ let body;
3047
+ try {
3048
+ body = JSON.parse(raw || "{}");
3049
+ } catch {
3050
+ return json(res, 400, { error: "malformed body" });
3051
+ }
3052
+ if (typeof body.name !== "string") return json(res, 400, { error: "name is required" });
3053
+ const args = body.arguments && typeof body.arguments === "object" ? body.arguments : {};
3054
+ const gone = new AbortController();
3055
+ res.on("close", () => {
3056
+ if (!res.writableFinished) gone.abort();
3057
+ });
3058
+ try {
3059
+ const text2 = await tools.call(body.name, args, gone.signal);
3060
+ if (gone.signal.aborted) return;
3061
+ return json(res, 200, { text: text2, isError: false });
3062
+ } catch (err) {
3063
+ if (gone.signal.aborted) return;
3064
+ if (err instanceof ToolError) return json(res, 200, { text: err.message, isError: true });
3065
+ return json(res, 200, { text: `tring could not do that: ${err.message}`, isError: true });
3066
+ }
3067
+ }
2057
3068
  if (url.pathname === "/api/hooks" && req.method === "GET") {
2058
3069
  return json(res, 200, await hooksStatus(opts.claudeSettingsPath));
2059
3070
  }
@@ -2090,12 +3101,12 @@ function createHandler(opts) {
2090
3101
  }
2091
3102
  if (url.pathname === "/api/fs" && req.method === "GET") {
2092
3103
  const raw = url.searchParams.get("path")?.trim();
2093
- const dir = raw ? path9.resolve(raw) : homeDir();
3104
+ const dir = raw ? path12.resolve(raw) : homeDir();
2094
3105
  if (!await browsable(dir)) return json(res, 403, { error: "outside the browsable roots" });
2095
3106
  try {
2096
- const found = await readdir3(dir, { withFileTypes: true });
2097
- const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path9.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
2098
- const parent = path9.dirname(dir);
3107
+ const found = await readdir4(dir, { withFileTypes: true });
3108
+ const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path12.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
3109
+ const parent = path12.dirname(dir);
2099
3110
  const up = parent !== dir && await browsable(parent) ? parent : null;
2100
3111
  return json(res, 200, { path: dir, parent: up, entries });
2101
3112
  } catch {
@@ -2142,15 +3153,15 @@ function createHandler(opts) {
2142
3153
  }
2143
3154
  async function serveStatic(res, pathname) {
2144
3155
  const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
2145
- const file = path9.resolve(webRoot, rel);
2146
- if (file !== webRoot && !file.startsWith(webRoot + path9.sep)) {
3156
+ const file = path12.resolve(webRoot, rel);
3157
+ if (file !== webRoot && !file.startsWith(webRoot + path12.sep)) {
2147
3158
  text(res, 403, "forbidden");
2148
3159
  return;
2149
3160
  }
2150
3161
  try {
2151
- const info = await stat3(file);
3162
+ const info = await stat5(file);
2152
3163
  if (!info.isFile()) throw new Error("not a file");
2153
- head(res, 200, MIME[path9.extname(file)] ?? "application/octet-stream");
3164
+ head(res, 200, MIME[path12.extname(file)] ?? "application/octet-stream");
2154
3165
  createReadStream(file).pipe(res);
2155
3166
  } catch {
2156
3167
  if (rel === "index.html") {
@@ -2164,7 +3175,6 @@ function createHandler(opts) {
2164
3175
  }
2165
3176
 
2166
3177
  // src/ws.ts
2167
- var PASTE_SETTLE_MS = 60;
2168
3178
  var Hub = class {
2169
3179
  constructor(opts) {
2170
3180
  this.opts = opts;
@@ -2183,12 +3193,17 @@ var Hub = class {
2183
3193
  };
2184
3194
  if (opts.inbox) opts.inbox.onChange = () => this.broadcastInbox();
2185
3195
  if (opts.auto) opts.auto.onChange = () => this.broadcastAuto();
2186
- pm.onSessionData = (s, data) => {
3196
+ const output = (s, data) => {
2187
3197
  const frame = encodeOutput(s.id, Buffer.from(data, "utf8"));
2188
3198
  for (const c of this.clients) {
2189
3199
  if (c.authed && c.focusedId === s.id) c.ws.send(frame, { binary: true });
2190
3200
  }
2191
3201
  };
3202
+ pm.onSessionData = output;
3203
+ if (opts.agent) {
3204
+ opts.agent.onData = output;
3205
+ opts.agent.onChange = () => this.broadcastAgent();
3206
+ }
2192
3207
  this.timer = setInterval(() => this.pumpSnapshots(), opts.snapshotMs ?? 250);
2193
3208
  this.timer.unref?.();
2194
3209
  }
@@ -2240,6 +3255,7 @@ var Hub = class {
2240
3255
  this.sendSnapshots(c);
2241
3256
  if (this.opts.inbox) this.send(c, { type: "inbox", items: this.opts.inbox.list() });
2242
3257
  if (this.opts.auto) this.send(c, this.autoMessage(this.opts.auto));
3258
+ if (this.opts.agent) this.send(c, { type: "agent", agent: this.opts.agent.info() });
2243
3259
  return;
2244
3260
  }
2245
3261
  if (!c.authed) return this.send(c, { type: "error", message: "expected hello" });
@@ -2278,18 +3294,25 @@ var Hub = class {
2278
3294
  case "focus": {
2279
3295
  c.focusedId = msg.id;
2280
3296
  if (!msg.id) break;
2281
- const s = pm.findSession(msg.id);
3297
+ const s = this.find(msg.id);
2282
3298
  if (!s) break;
2283
3299
  s.resize(msg.cols, msg.rows);
2284
3300
  this.send(c, { type: "screen", id: s.id, ansi: s.serialize() });
2285
3301
  break;
2286
3302
  }
2287
3303
  case "input": {
2288
- pm.findSession(msg.id)?.write(msg.data);
3304
+ this.find(msg.id)?.write(msg.data);
2289
3305
  break;
2290
3306
  }
2291
3307
  case "resize": {
2292
- if (c.focusedId) pm.findSession(c.focusedId)?.resize(msg.cols, msg.rows);
3308
+ if (c.focusedId) this.find(c.focusedId)?.resize(msg.cols, msg.rows);
3309
+ break;
3310
+ }
3311
+ case "agent": {
3312
+ const agent = this.opts.agent;
3313
+ if (!agent) break;
3314
+ if (typeof msg.enabled === "boolean") void agent.setEnabled(msg.enabled);
3315
+ else if (msg.restart === "resume" || msg.restart === "fresh") void agent.restart(msg.restart === "fresh");
2293
3316
  break;
2294
3317
  }
2295
3318
  case "kill":
@@ -2331,11 +3354,10 @@ var Hub = class {
2331
3354
  const item = inbox?.get(msg.itemId);
2332
3355
  if (!inbox || !item || item.kind !== "reply") break;
2333
3356
  const s = pm.findSession(item.sessionId);
2334
- const text2 = String(msg.text ?? "").replace(/\x1b\[20[01]~/g, "").trimEnd();
3357
+ const text2 = cleanPrompt(msg.text);
2335
3358
  if (!s || s.tracker.status === "busy" || s.tracker.status === "exited" || !text2) break;
2336
3359
  inbox.answer(item.id, { decision: "allow" });
2337
- s.write(`\x1B[200~${text2}\x1B[201~`);
2338
- setTimeout(() => s.write("\r"), PASTE_SETTLE_MS).unref?.();
3360
+ typePrompt(s, text2);
2339
3361
  break;
2340
3362
  }
2341
3363
  }
@@ -2395,6 +3417,13 @@ var Hub = class {
2395
3417
  broadcastAuto() {
2396
3418
  if (this.opts.auto) this.broadcast(this.autoMessage(this.opts.auto));
2397
3419
  }
3420
+ /** A tile, or the orchestrator agent's own terminal. */
3421
+ find(id) {
3422
+ return this.opts.pm.findSession(id) ?? this.opts.agent?.find(id);
3423
+ }
3424
+ broadcastAgent() {
3425
+ if (this.opts.agent) this.broadcast({ type: "agent", agent: this.opts.agent.info() });
3426
+ }
2398
3427
  broadcastInbox() {
2399
3428
  if (this.opts.inbox) this.broadcast({ type: "inbox", items: this.opts.inbox.list() });
2400
3429
  }
@@ -2544,25 +3573,25 @@ import {
2544
3573
  readdirSync
2545
3574
  } from "node:fs";
2546
3575
  import { createRequire as createRequire4 } from "node:module";
2547
- import path10 from "node:path";
3576
+ import path13 from "node:path";
2548
3577
  var EXEC = 73;
2549
3578
  function nodePtyRoot() {
2550
3579
  try {
2551
- return path10.dirname(createRequire4(import.meta.url).resolve("node-pty/package.json"));
3580
+ return path13.dirname(createRequire4(import.meta.url).resolve("node-pty/package.json"));
2552
3581
  } catch {
2553
3582
  return null;
2554
3583
  }
2555
3584
  }
2556
3585
  function spawnHelperPaths(root) {
2557
- const found = [path10.join(root, "build", "Release", "spawn-helper")];
3586
+ const found = [path13.join(root, "build", "Release", "spawn-helper")];
2558
3587
  let prebuilds;
2559
3588
  try {
2560
- prebuilds = readdirSync(path10.join(root, "prebuilds"), { withFileTypes: true });
3589
+ prebuilds = readdirSync(path13.join(root, "prebuilds"), { withFileTypes: true });
2561
3590
  } catch {
2562
3591
  return found;
2563
3592
  }
2564
3593
  for (const entry of prebuilds) {
2565
- if (entry.isDirectory()) found.push(path10.join(root, "prebuilds", entry.name, "spawn-helper"));
3594
+ if (entry.isDirectory()) found.push(path13.join(root, "prebuilds", entry.name, "spawn-helper"));
2566
3595
  }
2567
3596
  return found;
2568
3597
  }
@@ -2591,7 +3620,7 @@ function fixSpawnHelper(root = nodePtyRoot()) {
2591
3620
  import { spawn as spawn4 } from "node:child_process";
2592
3621
  import { mkdir as mkdir5, readFile as readFile6, writeFile as writeFile5 } from "node:fs/promises";
2593
3622
  import os7 from "node:os";
2594
- import path11 from "node:path";
3623
+ import path14 from "node:path";
2595
3624
  var BASH_ALWAYS_ASK = [
2596
3625
  /\brm\s+(-[a-zA-Z]*[rRf]|--recursive|--force)/,
2597
3626
  /\bsudo\b|\bdoas\b|\bsu\s/,
@@ -2615,8 +3644,8 @@ var BASH_ALWAYS_ASK = [
2615
3644
  var PATH_ALWAYS_ASK = /(^|\/)(\.env[^/]*|\.git\/|\.ssh\/|\.aws\/|id_rsa|id_ed25519|credentials[^/]*|\.npmrc|\.netrc|secrets?\.[a-z]+)$|(^|\/)\.git\//;
2616
3645
  var FILE_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
2617
3646
  var inside = (cwd, p) => {
2618
- const rel = path11.relative(path11.resolve(cwd), path11.resolve(cwd, p));
2619
- return rel === "" || !rel.startsWith("..") && !path11.isAbsolute(rel);
3647
+ const rel = path14.relative(path14.resolve(cwd), path14.resolve(cwd, p));
3648
+ return rel === "" || !rel.startsWith("..") && !path14.isAbsolute(rel);
2620
3649
  };
2621
3650
  function rule(item, cwd) {
2622
3651
  if (item.kind !== "permission") return { verdict: "ask", reason: "only permission prompts are auto-answered" };
@@ -2629,7 +3658,7 @@ function rule(item, cwd) {
2629
3658
  const p = String(input["file_path"] ?? input["notebook_path"] ?? "");
2630
3659
  if (!p) return { verdict: "ask", reason: "no file path given" };
2631
3660
  if (!inside(cwd, p)) return { verdict: "ask", reason: "outside the session directory" };
2632
- if (PATH_ALWAYS_ASK.test(path11.resolve(cwd, p))) return { verdict: "ask", reason: "a secrets or git file" };
3661
+ if (PATH_ALWAYS_ASK.test(path14.resolve(cwd, p))) return { verdict: "ask", reason: "a secrets or git file" };
2633
3662
  return { verdict: "classify" };
2634
3663
  }
2635
3664
  if (tool === "Bash") {
@@ -2750,7 +3779,7 @@ var AutoAnswerer = class {
2750
3779
  this.on = on;
2751
3780
  this.onChange?.();
2752
3781
  if (!this.opts.statePath) return;
2753
- await mkdir5(path11.dirname(this.opts.statePath), { recursive: true });
3782
+ await mkdir5(path14.dirname(this.opts.statePath), { recursive: true });
2754
3783
  await writeFile5(this.opts.statePath, JSON.stringify({ autoAnswer: on }, null, 2) + "\n", "utf8");
2755
3784
  }
2756
3785
  /**
@@ -2796,37 +3825,37 @@ var AutoAnswerer = class {
2796
3825
 
2797
3826
  // src/hook-shim.ts
2798
3827
  import { chmod, mkdir as mkdir6, writeFile as writeFile6 } from "node:fs/promises";
2799
- import path12 from "node:path";
3828
+ import path15 from "node:path";
2800
3829
  async function writeHookShim(dir, node, script) {
2801
3830
  await mkdir6(dir, { recursive: true });
2802
3831
  const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
2803
- await writeFile6(path12.join(dir, "tring-hook"), `#!/bin/sh
3832
+ await writeFile6(path15.join(dir, "tring-hook"), `#!/bin/sh
2804
3833
  exec ${q(node)} ${q(script)} "$@"
2805
3834
  `, "utf8");
2806
- await chmod(path12.join(dir, "tring-hook"), 493);
2807
- await writeFile6(path12.join(dir, "tring-hook.cmd"), `@"${node}" "${script}" %*\r
3835
+ await chmod(path15.join(dir, "tring-hook"), 493);
3836
+ await writeFile6(path15.join(dir, "tring-hook.cmd"), `@"${node}" "${script}" %*\r
2808
3837
  `, "utf8");
2809
3838
  }
2810
3839
  function prependPath(current, dir) {
2811
- const parts = (current ?? "").split(path12.delimiter).filter((p) => p && p !== dir);
2812
- return [dir, ...parts].join(path12.delimiter);
3840
+ const parts = (current ?? "").split(path15.delimiter).filter((p) => p && p !== dir);
3841
+ return [dir, ...parts].join(path15.delimiter);
2813
3842
  }
2814
3843
 
2815
3844
  // src/autostart.ts
2816
- import { execFile as execFile2 } from "node:child_process";
3845
+ import { execFile as execFile3 } from "node:child_process";
2817
3846
  import { mkdir as mkdir7, readFile as readFile7, rename as rename2, rm as rm2, writeFile as writeFile7 } from "node:fs/promises";
2818
3847
  import os8 from "node:os";
2819
- import path13 from "node:path";
3848
+ import path16 from "node:path";
2820
3849
  var MARKER = "written by tring autostart";
2821
3850
  var LABEL = "chat.tring.daemon";
2822
3851
  function autostartFile(e) {
2823
- if (e.platform === "darwin") return path13.join(e.home, "Library", "LaunchAgents", `${LABEL}.plist`);
3852
+ if (e.platform === "darwin") return path16.join(e.home, "Library", "LaunchAgents", `${LABEL}.plist`);
2824
3853
  if (e.platform === "win32") {
2825
- const appData = e.env["APPDATA"] ?? path13.join(e.home, "AppData", "Roaming");
2826
- return path13.win32.join(appData, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "tring.cmd");
3854
+ const appData = e.env["APPDATA"] ?? path16.join(e.home, "AppData", "Roaming");
3855
+ return path16.win32.join(appData, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "tring.cmd");
2827
3856
  }
2828
- const config = e.env["XDG_CONFIG_HOME"] ?? path13.join(e.home, ".config");
2829
- return path13.join(config, "systemd", "user", "tring.service");
3857
+ const config = e.env["XDG_CONFIG_HOME"] ?? path16.join(e.home, ".config");
3858
+ return path16.join(config, "systemd", "user", "tring.service");
2830
3859
  }
2831
3860
  var sdQuote = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
2832
3861
  var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -2884,7 +3913,7 @@ RestartSec=2
2884
3913
  WantedBy=default.target
2885
3914
  `;
2886
3915
  }
2887
- var defaultRun = (cmd, args) => new Promise((resolve) => execFile2(cmd, args, (err) => resolve(!err)));
3916
+ var defaultRun = (cmd, args) => new Promise((resolve) => execFile3(cmd, args, (err) => resolve(!err)));
2888
3917
  async function autostartStatus(e) {
2889
3918
  const file = autostartFile(e);
2890
3919
  try {
@@ -2902,14 +3931,14 @@ async function autostartOn(e, flags = []) {
2902
3931
  throw new ForeignAutostart(`${st.file} already exists and tring did not write it, so it was left alone.
2903
3932
  If it already starts tring at login there is nothing to do; otherwise move it aside and run this again.`);
2904
3933
  }
2905
- await mkdir7(path13.dirname(st.file), { recursive: true });
3934
+ await mkdir7(path16.dirname(st.file), { recursive: true });
2906
3935
  const tmp = `${st.file}.tring-${process.pid}`;
2907
3936
  await writeFile7(tmp, autostartContent(e, flags), "utf8");
2908
3937
  await rename2(tmp, st.file);
2909
- const run2 = e.run ?? defaultRun;
3938
+ const run3 = e.run ?? defaultRun;
2910
3939
  if (e.platform === "linux") {
2911
- await run2("systemctl", ["--user", "daemon-reload"]);
2912
- if (!await run2("systemctl", ["--user", "enable", "tring.service"])) {
3940
+ await run3("systemctl", ["--user", "daemon-reload"]);
3941
+ if (!await run3("systemctl", ["--user", "enable", "tring.service"])) {
2913
3942
  throw new Error(`wrote ${st.file}, but systemctl --user enable tring.service failed`);
2914
3943
  }
2915
3944
  }
@@ -2919,14 +3948,268 @@ async function autostartOff(e) {
2919
3948
  const st = await autostartStatus(e);
2920
3949
  if (!st.present) return false;
2921
3950
  if (!st.ours) throw new ForeignAutostart(`${st.file} was not written by tring, so it was left alone.`);
2922
- const run2 = e.run ?? defaultRun;
2923
- if (e.platform === "linux") await run2("systemctl", ["--user", "disable", "tring.service"]);
2924
- if (e.platform === "darwin") await run2("launchctl", ["bootout", `gui/${os8.userInfo().uid}/${LABEL}`]);
3951
+ const run3 = e.run ?? defaultRun;
3952
+ if (e.platform === "linux") await run3("systemctl", ["--user", "disable", "tring.service"]);
3953
+ if (e.platform === "darwin") await run3("launchctl", ["bootout", `gui/${os8.userInfo().uid}/${LABEL}`]);
2925
3954
  await rm2(st.file, { force: true });
2926
- if (e.platform === "linux") await run2("systemctl", ["--user", "daemon-reload"]);
3955
+ if (e.platform === "linux") await run3("systemctl", ["--user", "daemon-reload"]);
2927
3956
  return true;
2928
3957
  }
2929
3958
 
3959
+ // src/orchestrator-agent.ts
3960
+ import { randomUUID as randomUUID4 } from "node:crypto";
3961
+ import { chmod as chmod2, mkdir as mkdir8, readFile as readFile8, writeFile as writeFile8, access } from "node:fs/promises";
3962
+ import path17 from "node:path";
3963
+ var PRE_ALLOWED = ["list_sessions", "list_worktrees", "find_work", "session_history", "read_session", "session_changes", "send_prompt", "wait_for"].map((t) => `mcp__tring__${t}`);
3964
+ var RESUME_FAIL_MS = 1e4;
3965
+ var OrchestratorAgent = class {
3966
+ constructor(opts) {
3967
+ this.opts = opts;
3968
+ }
3969
+ on = false;
3970
+ conversation = null;
3971
+ current = null;
3972
+ startedAt = 0;
3973
+ error = null;
3974
+ timer = null;
3975
+ onChange = null;
3976
+ onData = null;
3977
+ get enabled() {
3978
+ return this.on;
3979
+ }
3980
+ get session() {
3981
+ return this.current;
3982
+ }
3983
+ /** The agent's session, if `id` is it. */
3984
+ find(id) {
3985
+ return this.current && this.current.id === id ? this.current : void 0;
3986
+ }
3987
+ info() {
3988
+ return {
3989
+ enabled: this.on,
3990
+ id: this.current?.id ?? null,
3991
+ status: this.current?.tracker.status ?? null,
3992
+ error: this.error
3993
+ };
3994
+ }
3995
+ async load() {
3996
+ try {
3997
+ const raw = JSON.parse(await readFile8(this.opts.statePath, "utf8"));
3998
+ this.on = raw.enabled === true;
3999
+ this.conversation = claudeConversation(raw.claude);
4000
+ } catch {
4001
+ this.on = false;
4002
+ }
4003
+ if (this.on) await this.start();
4004
+ }
4005
+ async setEnabled(on) {
4006
+ if (on === this.on) return;
4007
+ this.on = on;
4008
+ if (on) await this.start();
4009
+ else this.stop();
4010
+ await this.save();
4011
+ this.onChange?.();
4012
+ }
4013
+ /** A fresh conversation, or the same one again after Claude was quit. */
4014
+ async restart(fresh) {
4015
+ if (!this.on) return;
4016
+ if (fresh) this.conversation = null;
4017
+ this.stop();
4018
+ await this.start();
4019
+ await this.save();
4020
+ this.onChange?.();
4021
+ }
4022
+ dispose() {
4023
+ this.stop();
4024
+ }
4025
+ stop() {
4026
+ if (this.timer) clearInterval(this.timer);
4027
+ this.timer = null;
4028
+ this.current?.dispose();
4029
+ this.current = null;
4030
+ }
4031
+ async start() {
4032
+ if (this.current) return;
4033
+ this.error = null;
4034
+ if (!this.opts.mcpScript) {
4035
+ this.error = "the tring MCP relay is missing from this install, so the agent would have no tools";
4036
+ this.onChange?.();
4037
+ return;
4038
+ }
4039
+ try {
4040
+ await this.writeWorkspace();
4041
+ } catch (err) {
4042
+ this.error = `cannot write ${this.opts.dir}: ${err.message}`;
4043
+ this.onChange?.();
4044
+ return;
4045
+ }
4046
+ const resume = this.conversation ? ` --resume ${this.conversation.id}` : "";
4047
+ const command = `claude --mcp-config tring-mcp.json${resume}`;
4048
+ const s = (this.opts.spawn ?? ((o) => new Session(o)))({
4049
+ id: randomUUID4(),
4050
+ projectId: "",
4051
+ projectName: "orchestrator",
4052
+ slot: 0,
4053
+ cwd: this.opts.dir,
4054
+ command,
4055
+ name: "Orchestrator",
4056
+ url: this.opts.url,
4057
+ token: this.opts.token,
4058
+ scrollback: this.opts.scrollback,
4059
+ idleMs: this.opts.idleMs,
4060
+ ...this.opts.shell ? { shell: this.opts.shell } : {},
4061
+ autorun: true
4062
+ });
4063
+ this.current = s;
4064
+ this.startedAt = Date.now();
4065
+ this.timer = setInterval(() => s.tick(Date.now()), 500);
4066
+ this.timer.unref?.();
4067
+ s.onData = (data) => this.onData?.(s, data);
4068
+ s.onStatusChange = () => this.onChange?.();
4069
+ s.onClaudeChange = () => {
4070
+ if (s.claude) this.conversation = s.claude;
4071
+ void this.save();
4072
+ };
4073
+ s.onExit = () => {
4074
+ if (resume && Date.now() - this.startedAt < RESUME_FAIL_MS && this.current === s) {
4075
+ this.conversation = null;
4076
+ this.stop();
4077
+ void this.start().then(() => this.save()).then(() => this.onChange?.());
4078
+ return;
4079
+ }
4080
+ this.onChange?.();
4081
+ };
4082
+ this.onChange?.();
4083
+ }
4084
+ async save() {
4085
+ try {
4086
+ await mkdir8(path17.dirname(this.opts.statePath), { recursive: true });
4087
+ const saved = { enabled: this.on, claude: this.conversation };
4088
+ await writeFile8(this.opts.statePath, JSON.stringify(saved, null, 2) + "\n", "utf8");
4089
+ } catch {
4090
+ }
4091
+ }
4092
+ /**
4093
+ * Rewritten on every start, so an upgrade brings new instructions and a
4094
+ * moved Node with it. CLAUDE.md is the user's: written once, and it only
4095
+ * imports TRING.md, so anything they add there survives.
4096
+ */
4097
+ async writeWorkspace() {
4098
+ const dir = this.opts.dir;
4099
+ await mkdir8(path17.join(dir, ".claude"), { recursive: true });
4100
+ const tokenFile = path17.join(dir, ".token");
4101
+ if (this.opts.token) {
4102
+ await writeFile8(tokenFile, `${this.opts.token}
4103
+ `, { mode: 384 });
4104
+ await chmod2(tokenFile, 384).catch(() => {
4105
+ });
4106
+ }
4107
+ const script = this.opts.mcpScript;
4108
+ const nodeArgs = script.endsWith(".ts") ? ["--experimental-strip-types", "--no-warnings"] : [];
4109
+ const mcp = {
4110
+ mcpServers: {
4111
+ tring: {
4112
+ type: "stdio",
4113
+ command: this.opts.node,
4114
+ args: [...nodeArgs, script, "--url", this.opts.url, ...this.opts.token ? ["--token-file", tokenFile] : []]
4115
+ }
4116
+ }
4117
+ };
4118
+ await writeFile8(path17.join(dir, "tring-mcp.json"), JSON.stringify(mcp, null, 2) + "\n", "utf8");
4119
+ await writeFile8(path17.join(dir, ".claude", "settings.json"), JSON.stringify({
4120
+ permissions: { allow: PRE_ALLOWED }
4121
+ }, null, 2) + "\n", "utf8");
4122
+ await writeFile8(path17.join(dir, "TRING.md"), INSTRUCTIONS, "utf8");
4123
+ const claudeMd = path17.join(dir, "CLAUDE.md");
4124
+ try {
4125
+ await access(claudeMd);
4126
+ } catch {
4127
+ await writeFile8(claudeMd, "@TRING.md\n\n# Your own instructions for the orchestrator go below.\n", "utf8");
4128
+ }
4129
+ }
4130
+ };
4131
+ var INSTRUCTIONS = `# You are the tring orchestrator
4132
+
4133
+ The user runs many terminal tiles in tring, most of them Claude Code agents,
4134
+ each in its own slot of a project. You sit in the centre of tring's
4135
+ orchestrator mode: the user talks to you instead of typing into each tile, and
4136
+ you get the work done through the agents in those tiles.
4137
+
4138
+ ## Your tools (the \`tring\` MCP server)
4139
+
4140
+ - \`list_sessions\` \u2014 every project and tile: status (busy = working, done =
4141
+ finished and waiting, idle, exited), the directory its agent works in, its
4142
+ repository, worktree and branch, whether it runs Claude Code, what it is
4143
+ waiting on, and what its agent last said. \`sameWorktreeAs\` marks tiles
4144
+ sharing a worktree. Start here whenever you need to know what is going on.
4145
+ - \`list_worktrees\` \u2014 every worktree of each repository, its branch, and
4146
+ which tiles are in it. Free worktrees are the ones with no tiles.
4147
+ - \`find_work\` \u2014 which tiles have been working on a topic, ranked: by name,
4148
+ branch, conversation title, the prompts they were given, what their agent
4149
+ said and the files they edited.
4150
+ - \`session_history\` \u2014 a tile's conversation: prompts, answers, edited files.
4151
+ - \`read_session\` \u2014 the last lines of a tile's terminal.
4152
+ - \`session_changes\` \u2014 the uncommitted git changes in a tile's worktree.
4153
+ - \`send_prompt\` \u2014 give an agent an instruction, as if the user typed it.
4154
+ - \`create_session\` \u2014 start a new Claude Code tile, optionally with a first
4155
+ prompt, and with \`branch\` in its own git worktree. The user approves each one.
4156
+ - \`wait_for\` \u2014 wait until tiles finish, then read what they said.
4157
+
4158
+ Refer to tiles the way the user does: by project and slot (\`tring.chat/3\`),
4159
+ or by name. A bare slot number means the project the user is looking at.
4160
+
4161
+ ## How to work
4162
+
4163
+ - Delegate. You coordinate; the agents in the tiles do the coding, in their
4164
+ own repositories. Do not edit project files yourself unless the user asks.
4165
+ - The agents cannot see this conversation. Every prompt you send must stand
4166
+ on its own: the goal, the context they need, and what "done" looks like.
4167
+ - Pick the tile whose directory and branch fit the task. If none fits, or the
4168
+ work should run in parallel, offer to start a new tile.
4169
+ - After sending work, use \`wait_for\` and report back what each agent did, in
4170
+ a few lines. Quote them when it matters; never claim work an agent has not
4171
+ reported.
4172
+ - Permission prompts and questions from the agents are the user's to answer
4173
+ in tring's inbox, beside you. If a tile is waiting on one, say so; do not
4174
+ try to answer it by typing into that tile (send_prompt refuses anyway).
4175
+ - Keep replies short and scannable. The user is juggling many sessions.
4176
+
4177
+ ## Which tile? Route by what each one has been doing
4178
+
4179
+ The user talks about work, not slots: "make the reporting box green". Send it
4180
+ to the agent that has been working on that, which already has the context.
4181
+
4182
+ 1. Call \`find_work\` with the user's words. \`list_sessions\` also shows each
4183
+ tile's conversation title and recent prompts.
4184
+ 2. One clear best match: confirm with \`session_history\` (\`search\` for the
4185
+ topic) when the match is thin, then send it there and tell the user which
4186
+ tile you chose and why, in one line.
4187
+ 3. Several match about equally, or none does: do not guess. Ask the user,
4188
+ naming the candidates (slot, name, branch), or offer to start a new tile
4189
+ in its own worktree for it.
4190
+ 4. A clear match that is busy, waiting on the user, or exited: say so, and ask
4191
+ whether to queue it there or start a new tile.
4192
+
4193
+ ## Git worktrees
4194
+
4195
+ The user works in git worktrees: one branch, one worktree, one agent. Treat
4196
+ that as a rule, not a preference.
4197
+
4198
+ - Know where each agent is before you give it work: its \`git.branch\` and
4199
+ \`git.worktree\` in \`list_sessions\`, not just the tile's name. An agent can
4200
+ move into a worktree after its tile started; the tools follow it there.
4201
+ - Never give two agents work in the same worktree at once; they would edit the
4202
+ same files. If \`sameWorktreeAs\` shows a clash, tell the user.
4203
+ - New parallel work gets its own worktree: \`create_session\` with a
4204
+ \`branch\` (and \`base\` when it should not start from the current HEAD).
4205
+ If a worktree already has that branch, it is reused, not duplicated.
4206
+ - Name branches the way the user's existing branches are named (look at
4207
+ \`list_worktrees\`), e.g. with their ticket number when they use one.
4208
+ - Say which branch and worktree each piece of work is on when you report back.
4209
+ - Do not remove worktrees, delete branches, merge or push unless the user asks;
4210
+ when they do, have the agent in that worktree do it.
4211
+ `;
4212
+
2930
4213
  // src/index.ts
2931
4214
  function resolveAuth(args) {
2932
4215
  if (args.insecureNoToken) return { token: null, persisted: false };
@@ -3015,15 +4298,15 @@ async function main() {
3015
4298
  const tls = args.tlsCert && args.tlsKey ? loadTls(args.tlsCert, args.tlsKey) : null;
3016
4299
  const url = `${tls ? "https" : "http"}://${args.host}:${args.port}`;
3017
4300
  const cleartextOffBox = !tls && !isLoopbackBind(args.host);
3018
- const here = path14.dirname(fileURLToPath(import.meta.url));
4301
+ const here = path18.dirname(fileURLToPath(import.meta.url));
3019
4302
  const webRoot = [
3020
- path14.resolve(here, "web"),
3021
- path14.resolve(here, "../../web/dist")
3022
- ].find((p) => existsSync2(p)) ?? path14.resolve(here, "web");
4303
+ path18.resolve(here, "web"),
4304
+ path18.resolve(here, "../../web/dist")
4305
+ ].find((p) => existsSync2(p)) ?? path18.resolve(here, "web");
3023
4306
  for (const file of fixSpawnHelper()) console.log(`made ${file} executable`);
3024
- const hookScript = [path14.resolve(here, "tring-hook.js"), path14.resolve(here, "hook-cli.ts")].find((p) => existsSync2(p));
4307
+ const hookScript = [path18.resolve(here, "tring-hook.js"), path18.resolve(here, "hook-cli.ts")].find((p) => existsSync2(p));
3025
4308
  if (hookScript) {
3026
- const binDir = path14.join(path14.dirname(defaultTokenPath()), "bin");
4309
+ const binDir = path18.join(path18.dirname(defaultTokenPath()), "bin");
3027
4310
  try {
3028
4311
  await writeHookShim(binDir, process.execPath, hookScript);
3029
4312
  process.env["PATH"] = prependPath(process.env["PATH"], binDir);
@@ -3041,11 +4324,11 @@ async function main() {
3041
4324
  ...args.shell ? { shell: args.shell } : {}
3042
4325
  });
3043
4326
  const sameOrigin = createOriginCheck({ host: args.host, allow: args.allowOrigin });
3044
- const uploads = new UploadStore(path14.join(path14.dirname(pm.statePath), "uploads"));
4327
+ const uploads = new UploadStore(path18.join(path18.dirname(pm.statePath), "uploads"));
3045
4328
  const inbox = new Inbox();
3046
4329
  const auto = new AutoAnswerer({
3047
4330
  inbox,
3048
- statePath: path14.join(path14.dirname(pm.statePath), "orchestrator.json"),
4331
+ statePath: path18.join(path18.dirname(pm.statePath), "orchestrator.json"),
3049
4332
  context: (id) => {
3050
4333
  const s = pm.findSession(id);
3051
4334
  if (!s) return null;
@@ -3054,6 +4337,19 @@ async function main() {
3054
4337
  }
3055
4338
  });
3056
4339
  await auto.load();
4340
+ const configDir = path18.dirname(pm.statePath);
4341
+ const agent = new OrchestratorAgent({
4342
+ dir: path18.join(configDir, "orchestrator"),
4343
+ statePath: path18.join(configDir, "orchestrator-agent.json"),
4344
+ url,
4345
+ token,
4346
+ scrollback: args.scrollback,
4347
+ idleMs: args.idleMs,
4348
+ ...args.shell ? { shell: args.shell } : {},
4349
+ mcpScript: [path18.resolve(here, "tring-mcp.js"), path18.resolve(here, "mcp-cli.ts")].find((p) => existsSync2(p)) ?? null,
4350
+ node: process.execPath
4351
+ });
4352
+ const tools = new OrchestratorTools({ pm, inbox });
3057
4353
  const handle = createHandler({
3058
4354
  pm,
3059
4355
  webRoot,
@@ -3064,7 +4360,9 @@ async function main() {
3064
4360
  inbox,
3065
4361
  onPermission: (item) => {
3066
4362
  void auto.offer(item);
3067
- }
4363
+ },
4364
+ tools,
4365
+ agentSession: (id) => agent.find(id)
3068
4366
  });
3069
4367
  const listener = (req, res) => {
3070
4368
  void handle(req, res).catch(() => {
@@ -3073,8 +4371,9 @@ async function main() {
3073
4371
  };
3074
4372
  const server = tls ? createSecureServer(tls, listener) : createServer(listener);
3075
4373
  const wss = new WebSocketServer({ server, verifyClient: upgradeGuard(sameOrigin) });
3076
- const hub = new Hub({ pm, token, inbox, auto });
4374
+ const hub = new Hub({ pm, token, inbox, auto, agent });
3077
4375
  hub.attach(wss);
4376
+ await agent.load();
3078
4377
  const authUrl = token ? `${url}/?token=${encodeURIComponent(token)}` : url;
3079
4378
  server.listen(args.port, args.host, () => {
3080
4379
  console.log(`tring listening on ${url}`);
@@ -3086,7 +4385,7 @@ async function main() {
3086
4385
  console.warn(`warning: ${url} is plain http \u2014 the token, every keystroke and all terminal output cross the network in clear. Use an encrypted overlay (Tailscale, WireGuard) or pass --tls-cert/--tls-key.`);
3087
4386
  }
3088
4387
  if (args.updateCheck) {
3089
- void checkForUpdate(path14.join(path14.dirname(pm.statePath), "update-check.json")).then((latest) => {
4388
+ void checkForUpdate(path18.join(path18.dirname(pm.statePath), "update-check.json")).then((latest) => {
3090
4389
  if (!latest) return;
3091
4390
  hub.setUpdate({ current: currentVersion(), latest });
3092
4391
  console.log(`update available: ${currentVersion()} -> ${latest} (npm i -g tring-chat)`);
@@ -3102,6 +4401,7 @@ async function main() {
3102
4401
  });
3103
4402
  const shutdown = async () => {
3104
4403
  hub.dispose();
4404
+ agent.dispose();
3105
4405
  await uploads.dispose();
3106
4406
  await pm.dispose();
3107
4407
  server.close(() => process.exit(0));