tring-chat 0.1.19 → 0.1.22
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/README.md +64 -0
- package/dist/tring-mcp.js +129 -0
- package/dist/tring.js +1555 -90
- package/dist/web/assets/index-CdkPwCXa.js +83 -0
- package/dist/web/assets/{index-Da6ZZKaU.css → index-ru5HIKUf.css} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/index-DJrdNuH4.js +0 -77
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
|
|
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
|
|
206
|
+
let cache2 = null;
|
|
207
207
|
try {
|
|
208
|
-
|
|
208
|
+
cache2 = JSON.parse(await readFile(cachePath, "utf8"));
|
|
209
209
|
} catch {
|
|
210
|
-
|
|
210
|
+
cache2 = null;
|
|
211
211
|
}
|
|
212
|
-
if (
|
|
213
|
-
return isNewer(
|
|
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
|
|
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 (
|
|
460
|
-
|
|
459
|
+
if (run3 && run3.fg === fg && run3.bg === bg && run3.bold === bold) {
|
|
460
|
+
run3.text += text2;
|
|
461
461
|
} else {
|
|
462
|
-
|
|
463
|
-
out.push(
|
|
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.
|
|
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
|
|
1239
|
+
import { readdir as readdir4, realpath, stat as stat6 } from "node:fs/promises";
|
|
1179
1240
|
import os5 from "node:os";
|
|
1180
|
-
import
|
|
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
|
|
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
|
|
1433
|
-
(err) => process.platform === "win32" && err.code === "ENOENT" ?
|
|
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,1060 @@ async function uninstallHooks(file = defaultClaudeSettingsPath()) {
|
|
|
1915
1981
|
return true;
|
|
1916
1982
|
}
|
|
1917
1983
|
|
|
1984
|
+
// src/orchestrator-tools.ts
|
|
1985
|
+
import { stat as stat5 } 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 { stat as stat3 } from "node:fs/promises";
|
|
1991
|
+
import path9 from "node:path";
|
|
1992
|
+
import { promisify as promisify2 } from "node:util";
|
|
1993
|
+
var run2 = promisify2(execFile2);
|
|
1994
|
+
async function git2(cwd, args, timeout = 5e3) {
|
|
1995
|
+
try {
|
|
1996
|
+
const { stdout } = await run2("git", ["-c", "core.fsmonitor=false", ...args], { cwd, encoding: "utf8", timeout });
|
|
1997
|
+
return stdout;
|
|
1998
|
+
} catch {
|
|
1999
|
+
return null;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
function samePath(a, b) {
|
|
2003
|
+
return normal(a) === normal(b);
|
|
2004
|
+
}
|
|
2005
|
+
function normal(p) {
|
|
2006
|
+
const r = path9.resolve(p).replace(/[\\/]+$/, "");
|
|
2007
|
+
return process.platform === "win32" ? r.toLowerCase() : r;
|
|
2008
|
+
}
|
|
2009
|
+
function repoName(commonDir) {
|
|
2010
|
+
const base2 = path9.basename(commonDir);
|
|
2011
|
+
return base2 === ".git" ? path9.basename(path9.dirname(commonDir)) : base2.replace(/\.git$/, "");
|
|
2012
|
+
}
|
|
2013
|
+
function branchSlug(branch) {
|
|
2014
|
+
return branch.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "worktree";
|
|
2015
|
+
}
|
|
2016
|
+
function parseWorktreeList(text2) {
|
|
2017
|
+
const out = [];
|
|
2018
|
+
for (const block of text2.replace(/\r\n/g, "\n").split(/\n\n+/)) {
|
|
2019
|
+
const lines = block.split("\n").filter(Boolean);
|
|
2020
|
+
const first = lines[0];
|
|
2021
|
+
if (!first?.startsWith("worktree ")) continue;
|
|
2022
|
+
const w = {
|
|
2023
|
+
path: first.slice("worktree ".length),
|
|
2024
|
+
branch: null,
|
|
2025
|
+
head: null,
|
|
2026
|
+
bare: false,
|
|
2027
|
+
detached: false,
|
|
2028
|
+
locked: false,
|
|
2029
|
+
prunable: false
|
|
2030
|
+
};
|
|
2031
|
+
for (const l of lines.slice(1)) {
|
|
2032
|
+
if (l.startsWith("HEAD ")) w.head = l.slice(5);
|
|
2033
|
+
else if (l.startsWith("branch ")) w.branch = l.slice(7).replace(/^refs\/heads\//, "");
|
|
2034
|
+
else if (l === "bare") w.bare = true;
|
|
2035
|
+
else if (l === "detached") w.detached = true;
|
|
2036
|
+
else if (l === "locked" || l.startsWith("locked ")) w.locked = true;
|
|
2037
|
+
else if (l === "prunable" || l.startsWith("prunable ")) w.prunable = true;
|
|
2038
|
+
}
|
|
2039
|
+
out.push(w);
|
|
2040
|
+
}
|
|
2041
|
+
return out;
|
|
2042
|
+
}
|
|
2043
|
+
function defaultWorktreePath(commonDir, existing, branch) {
|
|
2044
|
+
const slug = branchSlug(branch);
|
|
2045
|
+
const linked = existing.filter((w, i) => i > 0 && !w.bare && !w.prunable);
|
|
2046
|
+
const parents = [...new Set(linked.map((w) => normal(path9.dirname(w.path))))];
|
|
2047
|
+
if (parents.length === 1) return path9.join(path9.dirname(linked[0].path), slug);
|
|
2048
|
+
const repoDir = path9.basename(commonDir) === ".git" ? path9.dirname(commonDir) : commonDir;
|
|
2049
|
+
return path9.join(path9.dirname(repoDir), `${repoName(commonDir)}.worktrees`, slug);
|
|
2050
|
+
}
|
|
2051
|
+
var roots = /* @__PURE__ */ new Map();
|
|
2052
|
+
function worktreeRootOf(p) {
|
|
2053
|
+
const start = path9.resolve(p);
|
|
2054
|
+
const k = normal(start);
|
|
2055
|
+
let hit = roots.get(k);
|
|
2056
|
+
if (!hit) {
|
|
2057
|
+
hit = (async () => {
|
|
2058
|
+
let dir = start;
|
|
2059
|
+
for (let i = 0; i < 64; i++) {
|
|
2060
|
+
try {
|
|
2061
|
+
await stat3(path9.join(dir, ".git"));
|
|
2062
|
+
return dir;
|
|
2063
|
+
} catch {
|
|
2064
|
+
}
|
|
2065
|
+
const up = path9.dirname(dir);
|
|
2066
|
+
if (up === dir) return null;
|
|
2067
|
+
dir = up;
|
|
2068
|
+
}
|
|
2069
|
+
return null;
|
|
2070
|
+
})();
|
|
2071
|
+
roots.set(k, hit);
|
|
2072
|
+
}
|
|
2073
|
+
return hit;
|
|
2074
|
+
}
|
|
2075
|
+
var realGit = {
|
|
2076
|
+
rootOf: worktreeRootOf,
|
|
2077
|
+
async place(dir) {
|
|
2078
|
+
const out = await git2(dir, ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-dir", "--git-common-dir"]);
|
|
2079
|
+
const [root, gitDir, commonDir] = out?.trim().split(/\r?\n/) ?? [];
|
|
2080
|
+
if (!root || !gitDir || !commonDir) return null;
|
|
2081
|
+
const branch = (await git2(dir, ["symbolic-ref", "--quiet", "--short", "HEAD"]))?.trim() || null;
|
|
2082
|
+
const detached = !branch && await git2(dir, ["rev-parse", "--verify", "--quiet", "HEAD"]) !== null;
|
|
2083
|
+
return { root: path9.resolve(root), commonDir: path9.resolve(commonDir), linked: !samePath(gitDir, commonDir), branch, detached };
|
|
2084
|
+
},
|
|
2085
|
+
async worktrees(dir) {
|
|
2086
|
+
const out = await git2(dir, ["worktree", "list", "--porcelain"]);
|
|
2087
|
+
return out ? parseWorktreeList(out).map((w) => ({ ...w, path: path9.resolve(w.path) })) : [];
|
|
2088
|
+
},
|
|
2089
|
+
async branchExists(dir, branch) {
|
|
2090
|
+
return await git2(dir, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]) !== null;
|
|
2091
|
+
},
|
|
2092
|
+
async checkBranch(dir, branch) {
|
|
2093
|
+
if (!branch || branch.startsWith("-")) return `"${branch}" is not a usable branch name`;
|
|
2094
|
+
return await git2(dir, ["check-ref-format", "--branch", branch]) === null ? `"${branch}" is not a valid branch name` : null;
|
|
2095
|
+
},
|
|
2096
|
+
async addWorktree(dir, spec) {
|
|
2097
|
+
const args = spec.create ? ["worktree", "add", "-b", spec.branch, spec.path, ...spec.base ? [spec.base] : []] : ["worktree", "add", spec.path, spec.branch];
|
|
2098
|
+
try {
|
|
2099
|
+
await run2("git", args, { cwd: dir, encoding: "utf8", timeout: 18e4 });
|
|
2100
|
+
return null;
|
|
2101
|
+
} catch (err) {
|
|
2102
|
+
const e = err;
|
|
2103
|
+
return (e.stderr || e.message).trim().split(/\r?\n/).slice(-3).join(" ");
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
};
|
|
2107
|
+
|
|
2108
|
+
// src/type-prompt.ts
|
|
2109
|
+
var PASTE_SETTLE_MS = 60;
|
|
2110
|
+
function cleanPrompt(text2) {
|
|
2111
|
+
return String(text2 ?? "").replace(/\x1b\[20[01]~/g, "").replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "").trimEnd();
|
|
2112
|
+
}
|
|
2113
|
+
function typePrompt(target, text2) {
|
|
2114
|
+
target.write(`\x1B[200~${text2}\x1B[201~`);
|
|
2115
|
+
setTimeout(() => target.write("\r"), PASTE_SETTLE_MS).unref?.();
|
|
2116
|
+
}
|
|
2117
|
+
|
|
2118
|
+
// src/transcript.ts
|
|
2119
|
+
import { open, readdir as readdir3, stat as stat4 } from "node:fs/promises";
|
|
2120
|
+
import path10 from "node:path";
|
|
2121
|
+
var SYSTEM_TAG = /^<(command-|local-command-|task-notification|system-reminder|user-prompt-submit-hook)/;
|
|
2122
|
+
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
2123
|
+
var READ_TOOLS = /* @__PURE__ */ new Set(["Read", "Grep", "Glob", "LS", "NotebookRead"]);
|
|
2124
|
+
var SHELL_TOOLS = /* @__PURE__ */ new Set(["Bash", "PowerShell"]);
|
|
2125
|
+
var MAX_PER_TURN = 40;
|
|
2126
|
+
var MAX_COMMAND = 300;
|
|
2127
|
+
var addCapped = (list, v) => {
|
|
2128
|
+
if (list.length < MAX_PER_TURN && !list.includes(v)) list.push(v);
|
|
2129
|
+
};
|
|
2130
|
+
var WHOLE_BYTES = 8 << 20;
|
|
2131
|
+
var HEAD_BYTES = 512 << 10;
|
|
2132
|
+
var TAIL_BYTES = 8 << 20;
|
|
2133
|
+
function humanPrompt(j) {
|
|
2134
|
+
const msg = j["message"];
|
|
2135
|
+
if (j["isMeta"] || j["isSidechain"]) return null;
|
|
2136
|
+
const origin = j["origin"];
|
|
2137
|
+
if (origin && origin.kind !== "human") return null;
|
|
2138
|
+
let text2 = null;
|
|
2139
|
+
if (typeof msg?.content === "string") text2 = msg.content;
|
|
2140
|
+
else if (Array.isArray(msg?.content)) {
|
|
2141
|
+
const blocks = msg.content;
|
|
2142
|
+
if (blocks.some((b) => b.type === "tool_result")) return null;
|
|
2143
|
+
text2 = blocks.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n") || null;
|
|
2144
|
+
}
|
|
2145
|
+
text2 = text2?.trim() ?? null;
|
|
2146
|
+
if (!text2 || SYSTEM_TAG.test(text2)) return null;
|
|
2147
|
+
return text2;
|
|
2148
|
+
}
|
|
2149
|
+
function parseTranscript(lines) {
|
|
2150
|
+
let title = null;
|
|
2151
|
+
const turns = [];
|
|
2152
|
+
for (const line of lines) {
|
|
2153
|
+
if (!line.trim()) continue;
|
|
2154
|
+
let j;
|
|
2155
|
+
try {
|
|
2156
|
+
j = JSON.parse(line);
|
|
2157
|
+
} catch {
|
|
2158
|
+
continue;
|
|
2159
|
+
}
|
|
2160
|
+
const at = typeof j["timestamp"] === "string" ? j["timestamp"] : null;
|
|
2161
|
+
if (j["type"] === "ai-title" && typeof j["aiTitle"] === "string") {
|
|
2162
|
+
title = j["aiTitle"];
|
|
2163
|
+
continue;
|
|
2164
|
+
}
|
|
2165
|
+
if (j["type"] === "user") {
|
|
2166
|
+
const text2 = humanPrompt(j);
|
|
2167
|
+
if (text2) turns.push({ role: "user", text: text2, at });
|
|
2168
|
+
continue;
|
|
2169
|
+
}
|
|
2170
|
+
if (j["type"] !== "assistant" || j["isSidechain"]) continue;
|
|
2171
|
+
const blocks = j["message"]?.content;
|
|
2172
|
+
if (!Array.isArray(blocks)) continue;
|
|
2173
|
+
const texts = [];
|
|
2174
|
+
const files = [];
|
|
2175
|
+
const paths = [];
|
|
2176
|
+
const commands = [];
|
|
2177
|
+
for (const b of blocks) {
|
|
2178
|
+
if (b.type === "text" && b.text?.trim()) texts.push(b.text.trim());
|
|
2179
|
+
if (b.type !== "tool_use" || !b.name) continue;
|
|
2180
|
+
const input = b.input ?? {};
|
|
2181
|
+
if (EDIT_TOOLS.has(b.name)) {
|
|
2182
|
+
const f = input["file_path"] ?? input["notebook_path"];
|
|
2183
|
+
if (typeof f === "string") files.push(f);
|
|
2184
|
+
} else if (READ_TOOLS.has(b.name)) {
|
|
2185
|
+
const p = input["file_path"] ?? input["path"] ?? input["notebook_path"];
|
|
2186
|
+
if (typeof p === "string" && p) addCapped(paths, p);
|
|
2187
|
+
} else if (SHELL_TOOLS.has(b.name) && typeof input["command"] === "string") {
|
|
2188
|
+
addCapped(commands, input["command"].slice(0, MAX_COMMAND));
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
if (!texts.length && !files.length && !paths.length && !commands.length) continue;
|
|
2192
|
+
let last = turns[turns.length - 1];
|
|
2193
|
+
if (last?.role !== "assistant") {
|
|
2194
|
+
last = { role: "assistant", text: "", at };
|
|
2195
|
+
turns.push(last);
|
|
2196
|
+
}
|
|
2197
|
+
if (texts.length) last.text = [last.text, ...texts].filter(Boolean).join("\n\n");
|
|
2198
|
+
if (files.length) last.files = [.../* @__PURE__ */ new Set([...last.files ?? [], ...files])];
|
|
2199
|
+
for (const p of paths) addCapped(last.paths ??= [], p);
|
|
2200
|
+
for (const c of commands) addCapped(last.commands ??= [], c);
|
|
2201
|
+
}
|
|
2202
|
+
return { title, turns };
|
|
2203
|
+
}
|
|
2204
|
+
async function readRange(file, start, length) {
|
|
2205
|
+
const fh = await open(file, "r");
|
|
2206
|
+
try {
|
|
2207
|
+
const buf = Buffer.alloc(length);
|
|
2208
|
+
const { bytesRead } = await fh.read(buf, 0, length, start);
|
|
2209
|
+
return buf.subarray(0, bytesRead).toString("utf8");
|
|
2210
|
+
} finally {
|
|
2211
|
+
await fh.close();
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
var cache = /* @__PURE__ */ new Map();
|
|
2215
|
+
var CACHE_LIMIT = 48;
|
|
2216
|
+
async function readTranscript(file) {
|
|
2217
|
+
let info;
|
|
2218
|
+
try {
|
|
2219
|
+
info = await stat4(file);
|
|
2220
|
+
} catch {
|
|
2221
|
+
return null;
|
|
2222
|
+
}
|
|
2223
|
+
const key = `${info.size}:${info.mtimeMs}`;
|
|
2224
|
+
const hit = cache.get(file);
|
|
2225
|
+
if (hit?.key === key) return hit.value;
|
|
2226
|
+
let lines;
|
|
2227
|
+
let partial = false;
|
|
2228
|
+
try {
|
|
2229
|
+
if (info.size <= WHOLE_BYTES) {
|
|
2230
|
+
lines = (await readRange(file, 0, info.size)).split("\n");
|
|
2231
|
+
} else {
|
|
2232
|
+
const head2 = (await readRange(file, 0, HEAD_BYTES)).split("\n").slice(0, -1);
|
|
2233
|
+
const tail = (await readRange(file, info.size - TAIL_BYTES, TAIL_BYTES)).split("\n").slice(1);
|
|
2234
|
+
lines = [...head2, ...tail];
|
|
2235
|
+
partial = true;
|
|
2236
|
+
}
|
|
2237
|
+
} catch {
|
|
2238
|
+
return null;
|
|
2239
|
+
}
|
|
2240
|
+
const value = { ...parseTranscript(lines), partial };
|
|
2241
|
+
cache.delete(file);
|
|
2242
|
+
cache.set(file, { key, value });
|
|
2243
|
+
if (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
|
|
2244
|
+
return value;
|
|
2245
|
+
}
|
|
2246
|
+
async function findTranscript(projectsDir, id) {
|
|
2247
|
+
if (!/^[0-9a-f-]{36}$/i.test(id)) return null;
|
|
2248
|
+
let dirs;
|
|
2249
|
+
try {
|
|
2250
|
+
dirs = await readdir3(projectsDir);
|
|
2251
|
+
} catch {
|
|
2252
|
+
return null;
|
|
2253
|
+
}
|
|
2254
|
+
for (const d of dirs) {
|
|
2255
|
+
const f = path10.join(projectsDir, d, `${id}.jsonl`);
|
|
2256
|
+
try {
|
|
2257
|
+
if ((await stat4(f)).isFile()) return f;
|
|
2258
|
+
} catch {
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
return null;
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2264
|
+
// src/orchestrator-tools.ts
|
|
2265
|
+
var ToolError = class extends Error {
|
|
2266
|
+
};
|
|
2267
|
+
var SESSION_REF = {
|
|
2268
|
+
type: "string",
|
|
2269
|
+
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.'
|
|
2270
|
+
};
|
|
2271
|
+
var TOOLS = [
|
|
2272
|
+
{
|
|
2273
|
+
name: "list_sessions",
|
|
2274
|
+
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.",
|
|
2275
|
+
inputSchema: {
|
|
2276
|
+
type: "object",
|
|
2277
|
+
properties: { project: { type: "string", description: "Only this project (name or id)." } },
|
|
2278
|
+
additionalProperties: false
|
|
2279
|
+
}
|
|
2280
|
+
},
|
|
2281
|
+
{
|
|
2282
|
+
name: "list_worktrees",
|
|
2283
|
+
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.",
|
|
2284
|
+
inputSchema: {
|
|
2285
|
+
type: "object",
|
|
2286
|
+
properties: { project: { type: "string", description: "Only this project's repository (name or id)." } },
|
|
2287
|
+
additionalProperties: false
|
|
2288
|
+
}
|
|
2289
|
+
},
|
|
2290
|
+
{
|
|
2291
|
+
name: "find_work",
|
|
2292
|
+
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.',
|
|
2293
|
+
inputSchema: {
|
|
2294
|
+
type: "object",
|
|
2295
|
+
properties: { query: { type: "string", description: 'What the user is talking about, in their words, e.g. "reporting box colour".' } },
|
|
2296
|
+
required: ["query"],
|
|
2297
|
+
additionalProperties: false
|
|
2298
|
+
}
|
|
2299
|
+
},
|
|
2300
|
+
{
|
|
2301
|
+
name: "session_history",
|
|
2302
|
+
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.",
|
|
2303
|
+
inputSchema: {
|
|
2304
|
+
type: "object",
|
|
2305
|
+
properties: {
|
|
2306
|
+
session: SESSION_REF,
|
|
2307
|
+
turns: { type: "integer", minimum: 1, maximum: 60, description: "How many recent turns, default 12." },
|
|
2308
|
+
search: { type: "string", description: "Only turns mentioning these words." }
|
|
2309
|
+
},
|
|
2310
|
+
required: ["session"],
|
|
2311
|
+
additionalProperties: false
|
|
2312
|
+
}
|
|
2313
|
+
},
|
|
2314
|
+
{
|
|
2315
|
+
name: "read_session",
|
|
2316
|
+
description: "The last lines of a tile's terminal (screen and scrollback) as plain text: what its agent or shell is showing right now.",
|
|
2317
|
+
inputSchema: {
|
|
2318
|
+
type: "object",
|
|
2319
|
+
properties: {
|
|
2320
|
+
session: SESSION_REF,
|
|
2321
|
+
lines: { type: "integer", minimum: 1, maximum: 400, description: "How many lines, default 80." }
|
|
2322
|
+
},
|
|
2323
|
+
required: ["session"],
|
|
2324
|
+
additionalProperties: false
|
|
2325
|
+
}
|
|
2326
|
+
},
|
|
2327
|
+
{
|
|
2328
|
+
name: "session_changes",
|
|
2329
|
+
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).",
|
|
2330
|
+
inputSchema: {
|
|
2331
|
+
type: "object",
|
|
2332
|
+
properties: {
|
|
2333
|
+
session: SESSION_REF,
|
|
2334
|
+
file: { type: "string", description: "Only this file's patch (a path from the file list)." }
|
|
2335
|
+
},
|
|
2336
|
+
required: ["session"],
|
|
2337
|
+
additionalProperties: false
|
|
2338
|
+
}
|
|
2339
|
+
},
|
|
2340
|
+
{
|
|
2341
|
+
name: "send_prompt",
|
|
2342
|
+
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.",
|
|
2343
|
+
inputSchema: {
|
|
2344
|
+
type: "object",
|
|
2345
|
+
properties: {
|
|
2346
|
+
session: SESSION_REF,
|
|
2347
|
+
text: { type: "string", description: "The prompt. Write it as a complete instruction; that agent cannot see this conversation." }
|
|
2348
|
+
},
|
|
2349
|
+
required: ["session", "text"],
|
|
2350
|
+
additionalProperties: false
|
|
2351
|
+
}
|
|
2352
|
+
},
|
|
2353
|
+
{
|
|
2354
|
+
name: "create_session",
|
|
2355
|
+
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.",
|
|
2356
|
+
inputSchema: {
|
|
2357
|
+
type: "object",
|
|
2358
|
+
properties: {
|
|
2359
|
+
project: { type: "string", description: "Project name or id; default the project the user is viewing." },
|
|
2360
|
+
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." },
|
|
2361
|
+
branch: { type: "string", description: 'Run in a worktree for this branch, e.g. "feature/CHV-3193-login".' },
|
|
2362
|
+
base: { type: "string", description: "With a new `branch`: what to branch from (branch, tag or commit); default the repository's current HEAD." },
|
|
2363
|
+
worktree_path: { type: "string", description: "With `branch`: where to put a new worktree. Default: beside the existing worktrees, or <parent>/<repo>.worktrees/<branch>." },
|
|
2364
|
+
name: { type: "string", description: 'A short tile name, e.g. "api tests"; defaults to the branch.' },
|
|
2365
|
+
prompt: { type: "string", description: "First prompt, sent once Claude Code is ready." }
|
|
2366
|
+
},
|
|
2367
|
+
additionalProperties: false
|
|
2368
|
+
}
|
|
2369
|
+
},
|
|
2370
|
+
{
|
|
2371
|
+
name: "wait_for",
|
|
2372
|
+
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.",
|
|
2373
|
+
inputSchema: {
|
|
2374
|
+
type: "object",
|
|
2375
|
+
properties: {
|
|
2376
|
+
sessions: { type: "array", items: SESSION_REF, minItems: 1 },
|
|
2377
|
+
timeout_seconds: { type: "integer", minimum: 5, maximum: 900, description: "Default 300." }
|
|
2378
|
+
},
|
|
2379
|
+
required: ["sessions"],
|
|
2380
|
+
additionalProperties: false
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
];
|
|
2384
|
+
var MAX_LAST_MESSAGE = 600;
|
|
2385
|
+
var MAX_PATCH_CHARS = 16e3;
|
|
2386
|
+
var READY_TIMEOUT_MS = 3e4;
|
|
2387
|
+
var READY_SETTLE_MS = 1500;
|
|
2388
|
+
var PROMPT_GRACE_MS = 15e3;
|
|
2389
|
+
var clip = (s, n) => s.length > n ? `${s.slice(0, n)}\u2026 (${s.length - n} more characters)` : s;
|
|
2390
|
+
async function isDirectory(p) {
|
|
2391
|
+
try {
|
|
2392
|
+
return (await stat5(p)).isDirectory();
|
|
2393
|
+
} catch {
|
|
2394
|
+
return false;
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2397
|
+
var workdir = (s) => s.agentCwd ?? s.cwd;
|
|
2398
|
+
var OrchestratorTools = class {
|
|
2399
|
+
constructor(d) {
|
|
2400
|
+
this.d = d;
|
|
2401
|
+
}
|
|
2402
|
+
get now() {
|
|
2403
|
+
return (this.d.now ?? Date.now)();
|
|
2404
|
+
}
|
|
2405
|
+
get git() {
|
|
2406
|
+
return this.d.git ?? realGit;
|
|
2407
|
+
}
|
|
2408
|
+
sleep(ms) {
|
|
2409
|
+
return (this.d.sleep ?? ((t) => new Promise((r) => setTimeout(r, t))))(ms);
|
|
2410
|
+
}
|
|
2411
|
+
async call(name, args, signal) {
|
|
2412
|
+
switch (name) {
|
|
2413
|
+
case "list_sessions":
|
|
2414
|
+
return this.listSessions(str(args["project"]));
|
|
2415
|
+
case "list_worktrees":
|
|
2416
|
+
return this.listWorktrees(str(args["project"]));
|
|
2417
|
+
case "find_work":
|
|
2418
|
+
return this.findWork(String(args["query"] ?? ""));
|
|
2419
|
+
case "session_history":
|
|
2420
|
+
return this.sessionHistory(this.resolve(args["session"]), num(args["turns"]) ?? 12, str(args["search"]));
|
|
2421
|
+
case "read_session":
|
|
2422
|
+
return this.readSession(this.resolve(args["session"]), num(args["lines"]) ?? 80);
|
|
2423
|
+
case "session_changes":
|
|
2424
|
+
return this.changes(this.resolve(args["session"]), str(args["file"]));
|
|
2425
|
+
case "send_prompt":
|
|
2426
|
+
return this.sendPrompt(this.resolve(args["session"]), String(args["text"] ?? ""));
|
|
2427
|
+
case "create_session":
|
|
2428
|
+
return this.createSession(args, signal);
|
|
2429
|
+
case "wait_for":
|
|
2430
|
+
return this.waitFor(args, signal);
|
|
2431
|
+
}
|
|
2432
|
+
throw new ToolError(`unknown tool ${name}`);
|
|
2433
|
+
}
|
|
2434
|
+
/** "<project>/<slot>", a session id, or a slot in the viewed project. */
|
|
2435
|
+
resolve(ref) {
|
|
2436
|
+
const r = String(ref ?? "").trim();
|
|
2437
|
+
if (!r) throw new ToolError("session is required");
|
|
2438
|
+
const byId = this.d.pm.findSession(r);
|
|
2439
|
+
if (byId) return byId;
|
|
2440
|
+
const at = r.lastIndexOf("/");
|
|
2441
|
+
const projectRef = at >= 0 ? r.slice(0, at) : null;
|
|
2442
|
+
const slot = Number(at >= 0 ? r.slice(at + 1) : r);
|
|
2443
|
+
const project = projectRef !== null ? this.d.pm.findProject(projectRef) : this.d.pm.list().find((p) => p.id === this.d.pm.activeProjectId);
|
|
2444
|
+
if (!project) throw new ToolError(`no project ${projectRef ?? "(none is being viewed)"}; see list_sessions`);
|
|
2445
|
+
if (!Number.isInteger(slot)) throw new ToolError(`cannot read "${r}" as a session; use an id or "<project>/<slot>"`);
|
|
2446
|
+
const info = project.sessions.find((s2) => s2.slot === slot);
|
|
2447
|
+
const s = info && this.d.pm.findSession(info.id);
|
|
2448
|
+
if (!s) throw new ToolError(`slot ${slot} in ${project.name} is empty`);
|
|
2449
|
+
return s;
|
|
2450
|
+
}
|
|
2451
|
+
ref(s) {
|
|
2452
|
+
const project = this.d.pm.list().find((p) => p.id === s.projectId);
|
|
2453
|
+
return `${project?.name ?? "project"}/${s.slot}`;
|
|
2454
|
+
}
|
|
2455
|
+
label(s) {
|
|
2456
|
+
return `${this.ref(s)}${s.name ? ` (${s.name})` : ""}`;
|
|
2457
|
+
}
|
|
2458
|
+
waiting(s) {
|
|
2459
|
+
return this.d.inbox.list().filter((i) => i.sessionId === s.id && i.kind !== "reply");
|
|
2460
|
+
}
|
|
2461
|
+
allSessions() {
|
|
2462
|
+
return this.d.pm.list().flatMap((p) => p.sessions).map((i) => this.d.pm.findSession(i.id)).filter((s) => !!s);
|
|
2463
|
+
}
|
|
2464
|
+
/** Every tile with its repository and worktree, in one pass of git calls. */
|
|
2465
|
+
async placeAll(sessions = this.allSessions()) {
|
|
2466
|
+
const memo = /* @__PURE__ */ new Map();
|
|
2467
|
+
const place = (dir) => {
|
|
2468
|
+
const k = normal(dir);
|
|
2469
|
+
if (!memo.has(k)) memo.set(k, this.git.place(dir));
|
|
2470
|
+
return memo.get(k);
|
|
2471
|
+
};
|
|
2472
|
+
return Promise.all(sessions.map(async (s) => ({ s, ref: this.ref(s), place: await place(workdir(s)) })));
|
|
2473
|
+
}
|
|
2474
|
+
/** Other live tiles whose agents are in the same worktree as `p`. */
|
|
2475
|
+
sharing(p, all) {
|
|
2476
|
+
if (!p.place) return [];
|
|
2477
|
+
return all.filter((o) => o.s.id !== p.s.id && o.place && o.s.tracker.status !== "exited" && samePath(o.place.root, p.place.root));
|
|
2478
|
+
}
|
|
2479
|
+
async listSessions(only) {
|
|
2480
|
+
let projects = this.d.pm.list();
|
|
2481
|
+
if (only) {
|
|
2482
|
+
const p = this.d.pm.findProject(only);
|
|
2483
|
+
if (!p) throw new ToolError(`no project ${only}; projects: ${projects.map((x) => x.name).join(", ")}`);
|
|
2484
|
+
projects = [p];
|
|
2485
|
+
}
|
|
2486
|
+
const placed = await this.placeAll();
|
|
2487
|
+
const byId = new Map(placed.map((p) => [p.s.id, p]));
|
|
2488
|
+
const talks = new Map(await Promise.all(placed.map(async (p) => [p.s.id, await this.history(p.s)])));
|
|
2489
|
+
const worked = new Map(await Promise.all(placed.map(async (p) => [p.s.id, await this.workedIn(talks.get(p.s.id) ?? null)])));
|
|
2490
|
+
const out = projects.map((p) => ({
|
|
2491
|
+
project: p.name,
|
|
2492
|
+
id: p.id,
|
|
2493
|
+
root: p.root,
|
|
2494
|
+
viewing: p.id === this.d.pm.activeProjectId,
|
|
2495
|
+
sessions: p.sessions.map((info) => {
|
|
2496
|
+
const pl = byId.get(info.id);
|
|
2497
|
+
const s = pl?.s;
|
|
2498
|
+
const waiting = s ? this.waiting(s) : [];
|
|
2499
|
+
const shared = pl ? this.sharing(pl, placed).map((o) => o.ref) : [];
|
|
2500
|
+
const agentDir = s?.agentCwd && !samePath(s.agentCwd, info.cwd) ? s.agentCwd : null;
|
|
2501
|
+
return {
|
|
2502
|
+
ref: `${p.name}/${info.slot}`,
|
|
2503
|
+
id: info.id,
|
|
2504
|
+
slot: info.slot,
|
|
2505
|
+
name: info.name ?? info.title ?? null,
|
|
2506
|
+
status: info.status,
|
|
2507
|
+
cwd: info.cwd,
|
|
2508
|
+
...agentDir ? { agentCwd: agentDir } : {},
|
|
2509
|
+
git: pl?.place ? gitSummary(pl.place) : null,
|
|
2510
|
+
...shared.length ? { sameWorktreeAs: shared } : {},
|
|
2511
|
+
agent: s?.claude ? "claude" : null,
|
|
2512
|
+
...conversationSummary(talks.get(info.id) ?? null),
|
|
2513
|
+
...workedSummary(worked.get(info.id) ?? []),
|
|
2514
|
+
...waiting.length ? { waitingOnUser: waiting.map(summary) } : {},
|
|
2515
|
+
...s?.lastMessage ? { lastMessage: clip(s.lastMessage, MAX_LAST_MESSAGE) } : {}
|
|
2516
|
+
};
|
|
2517
|
+
})
|
|
2518
|
+
}));
|
|
2519
|
+
return JSON.stringify({ projects: out }, null, 2);
|
|
2520
|
+
}
|
|
2521
|
+
async listWorktrees(only) {
|
|
2522
|
+
let projects = this.d.pm.list();
|
|
2523
|
+
if (only) {
|
|
2524
|
+
const p = this.d.pm.findProject(only);
|
|
2525
|
+
if (!p) throw new ToolError(`no project ${only}; projects: ${projects.map((x) => x.name).join(", ")}`);
|
|
2526
|
+
projects = [p];
|
|
2527
|
+
}
|
|
2528
|
+
const placed = await this.placeAll();
|
|
2529
|
+
const repos = /* @__PURE__ */ new Map();
|
|
2530
|
+
const add2 = (place, dir, project) => {
|
|
2531
|
+
if (!place) return;
|
|
2532
|
+
const k = normal(place.commonDir);
|
|
2533
|
+
const r = repos.get(k) ?? { dir, projects: /* @__PURE__ */ new Set() };
|
|
2534
|
+
if (project) r.projects.add(project);
|
|
2535
|
+
repos.set(k, r);
|
|
2536
|
+
};
|
|
2537
|
+
const roots2 = await Promise.all(projects.map(async (p) => ({ p, place: await this.git.place(p.root) })));
|
|
2538
|
+
for (const { p, place } of roots2) add2(place, p.root, p.name);
|
|
2539
|
+
const wanted = new Set(projects.map((p) => p.id));
|
|
2540
|
+
for (const pl of placed) if (wanted.has(pl.s.projectId)) add2(pl.place, workdir(pl.s));
|
|
2541
|
+
if (repos.size === 0) return "No git repositories: none of these projects or tiles is inside one.";
|
|
2542
|
+
const out = await Promise.all([...repos.entries()].map(async ([commonDir, r]) => {
|
|
2543
|
+
const trees = await this.git.worktrees(r.dir);
|
|
2544
|
+
return {
|
|
2545
|
+
repo: repoName(commonDir),
|
|
2546
|
+
...r.projects.size ? { projects: [...r.projects] } : {},
|
|
2547
|
+
// git lists the main worktree first; in a bare-repo layout that entry
|
|
2548
|
+
// is the bare repository itself, and every checkout is a linked one.
|
|
2549
|
+
worktrees: trees.map((w, i) => ({ w, main: i === 0 && !w.bare })).filter(({ w }) => !w.bare).map(({ w, main: main2 }) => {
|
|
2550
|
+
const tiles = placed.filter((pl) => pl.place && samePath(pl.place.root, w.path));
|
|
2551
|
+
return {
|
|
2552
|
+
path: w.path,
|
|
2553
|
+
branch: w.branch ?? (w.detached ? "(detached)" : null),
|
|
2554
|
+
main: main2,
|
|
2555
|
+
tiles: tiles.map((t) => `${t.ref} ${t.s.tracker.status}${t.s.claude ? " claude" : ""}`),
|
|
2556
|
+
...w.locked ? { locked: true } : {},
|
|
2557
|
+
...w.prunable ? { prunable: true } : {}
|
|
2558
|
+
};
|
|
2559
|
+
})
|
|
2560
|
+
};
|
|
2561
|
+
}));
|
|
2562
|
+
return JSON.stringify({ repos: out }, null, 2);
|
|
2563
|
+
}
|
|
2564
|
+
/**
|
|
2565
|
+
* The worktrees an agent has really been working in, by the files it edited
|
|
2566
|
+
* and read and the paths in the commands it ran — not where its shell sits.
|
|
2567
|
+
* A Claude started in the home directory that spends the day editing one
|
|
2568
|
+
* repository is working in that repository.
|
|
2569
|
+
*/
|
|
2570
|
+
async workedIn(talk) {
|
|
2571
|
+
if (!talk) return [];
|
|
2572
|
+
const tally = /* @__PURE__ */ new Map();
|
|
2573
|
+
const count = async (p, kind) => {
|
|
2574
|
+
if (!path11.isAbsolute(p)) return;
|
|
2575
|
+
const root = await this.git.rootOf(p);
|
|
2576
|
+
if (!root) return;
|
|
2577
|
+
const k = normal(root);
|
|
2578
|
+
const t = tally.get(k) ?? { root, edits: 0, reads: 0 };
|
|
2579
|
+
t[kind]++;
|
|
2580
|
+
tally.set(k, t);
|
|
2581
|
+
};
|
|
2582
|
+
const jobs = [];
|
|
2583
|
+
for (const t of talk.turns) {
|
|
2584
|
+
for (const f of t.files ?? []) jobs.push(count(f, "edits"));
|
|
2585
|
+
for (const p of t.paths ?? []) jobs.push(count(p, "reads"));
|
|
2586
|
+
for (const c of t.commands ?? []) for (const p of pathsIn(c)) jobs.push(count(p, "reads"));
|
|
2587
|
+
}
|
|
2588
|
+
await Promise.all(jobs);
|
|
2589
|
+
return [...tally.values()].sort((a, b) => b.edits * 3 + b.reads - (a.edits * 3 + a.reads)).slice(0, 5);
|
|
2590
|
+
}
|
|
2591
|
+
/** The tile's conversation, from the transcript its hooks named, or found by id. */
|
|
2592
|
+
async history(s) {
|
|
2593
|
+
const t = this.d.transcripts ?? {
|
|
2594
|
+
read: readTranscript,
|
|
2595
|
+
find: (id) => findTranscript(defaultTranscriptDir(), id)
|
|
2596
|
+
};
|
|
2597
|
+
const file = s.transcript ?? (s.claude ? await t.find(s.claude.id) : null);
|
|
2598
|
+
return file ? t.read(file) : null;
|
|
2599
|
+
}
|
|
2600
|
+
async sessionHistory(s, count, search) {
|
|
2601
|
+
const talk = await this.history(s);
|
|
2602
|
+
if (!talk) {
|
|
2603
|
+
return `${this.label(s)}: no conversation to read${s.claude ? " (its transcript was not found)" : " \u2014 it is not running Claude Code"}.`;
|
|
2604
|
+
}
|
|
2605
|
+
const n = Math.max(1, Math.min(60, Math.floor(count)));
|
|
2606
|
+
let turns = talk.turns;
|
|
2607
|
+
if (search) {
|
|
2608
|
+
const ws = words(search);
|
|
2609
|
+
turns = turns.filter((t) => ws.some((w) => turnText(t).toLowerCase().includes(w)));
|
|
2610
|
+
if (!turns.length) return `${this.label(s)}: nothing in its conversation mentions "${search}".`;
|
|
2611
|
+
}
|
|
2612
|
+
const shown = turns.slice(-n);
|
|
2613
|
+
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)" : ""}`;
|
|
2614
|
+
const body = shown.map((t) => {
|
|
2615
|
+
const who = t.role === "user" ? "PROMPT" : "AGENT";
|
|
2616
|
+
const files = t.files?.length ? `
|
|
2617
|
+
(edited: ${t.files.join(", ")})` : "";
|
|
2618
|
+
return `[${who}${t.at ? ` ${t.at.slice(0, 16).replace("T", " ")}` : ""}]
|
|
2619
|
+
${clip(t.text, t.role === "user" ? 800 : 1500)}${files}`;
|
|
2620
|
+
});
|
|
2621
|
+
return `${head2}
|
|
2622
|
+
|
|
2623
|
+
${body.join("\n\n")}`;
|
|
2624
|
+
}
|
|
2625
|
+
/**
|
|
2626
|
+
* Ranks tiles against what the user said. Each word counts for more the
|
|
2627
|
+
* fewer tiles mention it — "change" is everywhere, "reporting" is not — and
|
|
2628
|
+
* what a tile was asked, titled or edited counts for more than what its
|
|
2629
|
+
* agent happened to say, as do its recent turns over its old ones.
|
|
2630
|
+
*/
|
|
2631
|
+
async findWork(query) {
|
|
2632
|
+
const ws = words(query);
|
|
2633
|
+
if (!ws.length) throw new ToolError('say what the work is about, e.g. "reporting box"');
|
|
2634
|
+
const placed = await this.placeAll();
|
|
2635
|
+
const docs = await Promise.all(placed.map(async (p) => {
|
|
2636
|
+
const talk = await this.history(p.s);
|
|
2637
|
+
const worked = await this.workedIn(talk);
|
|
2638
|
+
const fields = [
|
|
2639
|
+
{ why: "name", text: [p.s.name, p.s.title].filter(Boolean).join(" "), weight: 4 },
|
|
2640
|
+
{ why: "branch", text: [p.place?.branch, p.place?.root].filter(Boolean).join(" "), weight: 4 },
|
|
2641
|
+
{ why: "title", text: talk?.title ?? "", weight: 4 },
|
|
2642
|
+
{ why: "worked in", text: worked.map((w) => w.root).join(" "), weight: 4 },
|
|
2643
|
+
{ why: "last message", text: p.s.lastMessage ?? "", weight: 1 }
|
|
2644
|
+
];
|
|
2645
|
+
const turns = talk?.turns ?? [];
|
|
2646
|
+
turns.forEach((t, i) => {
|
|
2647
|
+
const recent = i >= turns.length - 10 ? 2 : 1;
|
|
2648
|
+
if (t.role === "user") fields.push({ why: "prompt", text: t.text, weight: 3 * recent });
|
|
2649
|
+
else fields.push({ why: "agent said", text: t.text, weight: recent });
|
|
2650
|
+
if (t.files?.length) fields.push({ why: "edited", text: t.files.join(" "), weight: 3 * recent });
|
|
2651
|
+
if (t.paths?.length) fields.push({ why: "read", text: t.paths.join(" "), weight: recent });
|
|
2652
|
+
if (t.commands?.length) fields.push({ why: "ran", text: t.commands.join(" "), weight: recent });
|
|
2653
|
+
});
|
|
2654
|
+
return { p, fields };
|
|
2655
|
+
}));
|
|
2656
|
+
const df = new Map(ws.map((w) => [w, docs.filter((d) => d.fields.some((f) => f.text.toLowerCase().includes(w))).length]));
|
|
2657
|
+
const known = ws.filter((w) => df.get(w) > 0);
|
|
2658
|
+
const ranked = docs.map(({ p, fields }) => {
|
|
2659
|
+
let score = 0;
|
|
2660
|
+
const why = /* @__PURE__ */ new Set();
|
|
2661
|
+
let best = null;
|
|
2662
|
+
let whole = false;
|
|
2663
|
+
const strong = /* @__PURE__ */ new Set();
|
|
2664
|
+
for (const f of fields) {
|
|
2665
|
+
const low = f.text.toLowerCase();
|
|
2666
|
+
const hit = ws.filter((w) => low.includes(w));
|
|
2667
|
+
if (!hit.length) continue;
|
|
2668
|
+
const s = f.weight * hit.reduce((n, w) => n + 1 / df.get(w), 0) * (hit.length === ws.length ? 2 : 1);
|
|
2669
|
+
score += s;
|
|
2670
|
+
why.add(f.why);
|
|
2671
|
+
if (!best || s > best.score) best = { score: s, text: snippet(f.text, hit[0]) };
|
|
2672
|
+
if (hit.length === ws.length) whole = true;
|
|
2673
|
+
if (STRONG.has(f.why)) for (const w of hit) strong.add(w);
|
|
2674
|
+
}
|
|
2675
|
+
const confident = whole || strong.size >= Math.max(1, known.length / 2) || [...strong].some((w) => df.get(w) === 1);
|
|
2676
|
+
return { p, score, confident, why: [...why], snippet: best?.text ?? "" };
|
|
2677
|
+
}).filter((r) => r.score > 0).sort((a, b) => b.score - a.score);
|
|
2678
|
+
const top = ranked.slice(0, 5);
|
|
2679
|
+
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(", ")})
|
|
2680
|
+
"${r.snippet}"`);
|
|
2681
|
+
const sure = top.filter((r) => r.confident);
|
|
2682
|
+
if (!sure.length) {
|
|
2683
|
+
return `No tile clearly matches "${query}". Ask the user which tile, or offer a new one in its own worktree.` + (lines.length ? `
|
|
2684
|
+
|
|
2685
|
+
Only passing mentions:
|
|
2686
|
+
${lines.join("\n")}` : "");
|
|
2687
|
+
}
|
|
2688
|
+
const close = sure.length > 1 && sure[1].score >= sure[0].score * 0.75;
|
|
2689
|
+
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.`;
|
|
2690
|
+
return `${verdict}
|
|
2691
|
+
|
|
2692
|
+
${lines.join("\n")}`;
|
|
2693
|
+
}
|
|
2694
|
+
readSession(s, lines) {
|
|
2695
|
+
const n = Math.max(1, Math.min(400, Math.floor(lines)));
|
|
2696
|
+
return `${this.label(s)} \u2014 ${s.tracker.status}, ${workdir(s)}
|
|
2697
|
+
|
|
2698
|
+
${s.recentText(n) || "(nothing on screen)"}`;
|
|
2699
|
+
}
|
|
2700
|
+
async changes(s, file) {
|
|
2701
|
+
const r = await (this.d.diff ?? gitDiff)(workdir(s));
|
|
2702
|
+
if ("error" in r) return `${this.label(s)}: ${r.error}`;
|
|
2703
|
+
if (r.files.length === 0) return `${this.label(s)}: no uncommitted changes in ${r.cwd}`;
|
|
2704
|
+
const list = r.files.map((f) => `${f.path} +${f.added} -${f.removed}${f.note ? ` (${f.note})` : ""}`);
|
|
2705
|
+
const head2 = `${this.label(s)}: ${r.files.length} changed file(s) in ${r.cwd}${r.truncated ? " (patch truncated)" : ""}
|
|
2706
|
+
${list.join("\n")}`;
|
|
2707
|
+
if (file) {
|
|
2708
|
+
const f = r.files.find((x) => x.path === file || x.path.endsWith(`/${file}`));
|
|
2709
|
+
if (!f) throw new ToolError(`${file} has no changes; changed: ${r.files.map((x) => x.path).join(", ")}`);
|
|
2710
|
+
return `${head2}
|
|
2711
|
+
|
|
2712
|
+
--- ${f.path}
|
|
2713
|
+
${clip(f.patch || f.note || "", MAX_PATCH_CHARS * 2)}`;
|
|
2714
|
+
}
|
|
2715
|
+
let budget = MAX_PATCH_CHARS;
|
|
2716
|
+
const patches = [];
|
|
2717
|
+
for (const f of r.files) {
|
|
2718
|
+
if (!f.patch || budget <= 0) continue;
|
|
2719
|
+
const p = clip(f.patch, budget);
|
|
2720
|
+
budget -= p.length;
|
|
2721
|
+
patches.push(`--- ${f.path}
|
|
2722
|
+
${p}`);
|
|
2723
|
+
}
|
|
2724
|
+
const rest = budget <= 0 ? "\n\n(more patches left out; ask for one file with `file`)" : "";
|
|
2725
|
+
return `${head2}
|
|
2726
|
+
|
|
2727
|
+
${patches.join("\n\n")}${rest}`;
|
|
2728
|
+
}
|
|
2729
|
+
/** Why this tile cannot take a prompt now, or null when it can. */
|
|
2730
|
+
refusal(s) {
|
|
2731
|
+
if (s.tracker.status === "exited") return `${this.label(s)} has exited`;
|
|
2732
|
+
if (!s.claude) {
|
|
2733
|
+
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.`;
|
|
2734
|
+
}
|
|
2735
|
+
const waiting = this.waiting(s);
|
|
2736
|
+
if (waiting.length) {
|
|
2737
|
+
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.`;
|
|
2738
|
+
}
|
|
2739
|
+
return null;
|
|
2740
|
+
}
|
|
2741
|
+
deliver(s, text2) {
|
|
2742
|
+
s.prompted();
|
|
2743
|
+
(this.d.type ?? typePrompt)(s, text2);
|
|
2744
|
+
}
|
|
2745
|
+
/** A warning for the agent when another agent is busy in the same worktree. */
|
|
2746
|
+
async crowding(s) {
|
|
2747
|
+
const placed = await this.placeAll();
|
|
2748
|
+
const me = placed.find((p) => p.s.id === s.id);
|
|
2749
|
+
const busy = me ? this.sharing(me, placed).filter((o) => o.s.claude && o.s.tracker.status === "busy") : [];
|
|
2750
|
+
if (!busy.length || !me?.place) return "";
|
|
2751
|
+
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.`;
|
|
2752
|
+
}
|
|
2753
|
+
async sendPrompt(s, raw) {
|
|
2754
|
+
const text2 = cleanPrompt(raw);
|
|
2755
|
+
if (!text2) throw new ToolError("text is empty");
|
|
2756
|
+
const why = this.refusal(s);
|
|
2757
|
+
if (why) throw new ToolError(why);
|
|
2758
|
+
const busy = s.tracker.status === "busy";
|
|
2759
|
+
const warning = await this.crowding(s);
|
|
2760
|
+
this.deliver(s, text2);
|
|
2761
|
+
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.`;
|
|
2762
|
+
}
|
|
2763
|
+
/**
|
|
2764
|
+
* The worktree for `branch`: the one it is already checked out in, or a new
|
|
2765
|
+
* one. Returns the directory to start in, and what was done, in words.
|
|
2766
|
+
*/
|
|
2767
|
+
async worktreeFor(repoDir, args) {
|
|
2768
|
+
const branch = str(args["branch"]);
|
|
2769
|
+
const git3 = this.git;
|
|
2770
|
+
const place = await git3.place(repoDir);
|
|
2771
|
+
if (!place) throw new ToolError(`${repoDir} is not inside a git repository, so there is no worktree to make`);
|
|
2772
|
+
const bad = await git3.checkBranch(repoDir, branch);
|
|
2773
|
+
if (bad) throw new ToolError(bad);
|
|
2774
|
+
const trees = await git3.worktrees(repoDir);
|
|
2775
|
+
const there = trees.find((w) => w.branch === branch && !w.prunable);
|
|
2776
|
+
if (there) {
|
|
2777
|
+
const inside2 = (await this.placeAll()).filter((p) => p.place && samePath(p.place.root, there.path) && p.s.tracker.status !== "exited");
|
|
2778
|
+
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.` : "";
|
|
2779
|
+
return { dir: there.path, note: `Reused the existing worktree ${there.path}, which has ${branch} checked out.${crowd}` };
|
|
2780
|
+
}
|
|
2781
|
+
const base2 = str(args["base"]);
|
|
2782
|
+
if (base2?.startsWith("-")) throw new ToolError(`"${base2}" is not a usable base`);
|
|
2783
|
+
const exists = await git3.branchExists(repoDir, branch);
|
|
2784
|
+
const wanted = str(args["worktree_path"]);
|
|
2785
|
+
const dir = wanted ? path11.resolve(repoDir, wanted) : defaultWorktreePath(place.commonDir, trees, branch);
|
|
2786
|
+
if (await (this.d.isDir ?? isDirectory)(dir)) throw new ToolError(`${dir} already exists; pick another worktree_path`);
|
|
2787
|
+
const err = await git3.addWorktree(repoDir, { path: dir, branch, create: !exists, ...base2 && !exists ? { base: base2 } : {} });
|
|
2788
|
+
if (err) throw new ToolError(`git worktree add failed: ${err}`);
|
|
2789
|
+
const what = exists ? `checked out the existing branch ${branch}` : `created ${branch} from ${base2 ?? "the current HEAD"}`;
|
|
2790
|
+
return { dir, note: `Added the worktree ${dir} and ${what}.` };
|
|
2791
|
+
}
|
|
2792
|
+
async createSession(args, signal) {
|
|
2793
|
+
const projectRef = str(args["project"]);
|
|
2794
|
+
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];
|
|
2795
|
+
if (!project) throw new ToolError(projectRef ? `no project ${projectRef}; see list_sessions` : "there are no projects yet");
|
|
2796
|
+
const cwdArg = str(args["cwd"]);
|
|
2797
|
+
let cwd = cwdArg ? path11.resolve(project.root, cwdArg) : project.root;
|
|
2798
|
+
if (!await (this.d.isDir ?? isDirectory)(cwd)) throw new ToolError(`${cwd} is not a directory`);
|
|
2799
|
+
const branch = str(args["branch"]);
|
|
2800
|
+
let note = "";
|
|
2801
|
+
if (branch) {
|
|
2802
|
+
const wt = await this.worktreeFor(cwd, args);
|
|
2803
|
+
cwd = wt.dir;
|
|
2804
|
+
note = ` ${wt.note}`;
|
|
2805
|
+
}
|
|
2806
|
+
let s;
|
|
2807
|
+
try {
|
|
2808
|
+
s = this.d.pm.create(project.id, { cwd, command: "claude", name: str(args["name"]) ?? branch ?? null });
|
|
2809
|
+
} catch (err) {
|
|
2810
|
+
throw new ToolError(`${err.message}.${note}`);
|
|
2811
|
+
}
|
|
2812
|
+
if (!s) throw new ToolError(`could not start a session.${note}`);
|
|
2813
|
+
const started = `Started ${this.label(s)} (id ${s.id}) running claude in ${cwd}.${note}`;
|
|
2814
|
+
const prompt = cleanPrompt(String(args["prompt"] ?? ""));
|
|
2815
|
+
if (!prompt) return started;
|
|
2816
|
+
const ready = await this.ready(s, signal);
|
|
2817
|
+
if (!ready) {
|
|
2818
|
+
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.`;
|
|
2819
|
+
}
|
|
2820
|
+
this.deliver(s, prompt);
|
|
2821
|
+
return `${started} First prompt sent. Use wait_for with "${s.id}" for the answer.`;
|
|
2822
|
+
}
|
|
2823
|
+
/** Claude has started (SessionStart hook) and drawn its prompt. */
|
|
2824
|
+
async ready(s, signal) {
|
|
2825
|
+
const until = this.now + READY_TIMEOUT_MS;
|
|
2826
|
+
let since = null;
|
|
2827
|
+
while (this.now < until && !signal?.aborted) {
|
|
2828
|
+
if (s.tracker.status === "exited") return false;
|
|
2829
|
+
if (s.claude && s.tracker.status !== "busy") {
|
|
2830
|
+
since ??= this.now;
|
|
2831
|
+
if (this.now - since >= READY_SETTLE_MS) return true;
|
|
2832
|
+
} else {
|
|
2833
|
+
since = null;
|
|
2834
|
+
}
|
|
2835
|
+
await this.sleep(250);
|
|
2836
|
+
}
|
|
2837
|
+
return false;
|
|
2838
|
+
}
|
|
2839
|
+
async waitFor(args, signal) {
|
|
2840
|
+
const refs = Array.isArray(args["sessions"]) ? args["sessions"] : [args["sessions"]];
|
|
2841
|
+
const sessions = refs.map((r) => this.resolve(r));
|
|
2842
|
+
const timeout = Math.max(5, Math.min(900, num(args["timeout_seconds"]) ?? 300)) * 1e3;
|
|
2843
|
+
const until = this.now + timeout;
|
|
2844
|
+
while (!signal?.aborted) {
|
|
2845
|
+
if (sessions.every((s) => this.state(s) !== "working") || this.now >= until) break;
|
|
2846
|
+
await this.sleep(1e3);
|
|
2847
|
+
}
|
|
2848
|
+
const timedOut = sessions.some((s) => this.state(s) === "working");
|
|
2849
|
+
const lines = sessions.map((s) => {
|
|
2850
|
+
const st = this.state(s);
|
|
2851
|
+
const waiting = this.waiting(s);
|
|
2852
|
+
const said = s.lastMessage && s.stoppedAt >= s.promptedAt ? `
|
|
2853
|
+
${clip(s.lastMessage, 4e3)}` : "";
|
|
2854
|
+
const why = st === "needs-user" ? ` \u2014 waiting on the user: ${waiting.map(summary).join("; ")}` : "";
|
|
2855
|
+
return `## ${this.label(s)} \u2014 ${st === "working" ? "still working" : st}${why}${said}`;
|
|
2856
|
+
});
|
|
2857
|
+
return (timedOut ? `Timed out after ${timeout / 1e3}s.
|
|
2858
|
+
|
|
2859
|
+
` : "") + lines.join("\n\n");
|
|
2860
|
+
}
|
|
2861
|
+
state(s) {
|
|
2862
|
+
if (s.tracker.status === "exited") return "exited";
|
|
2863
|
+
if (this.waiting(s).length) return "needs-user";
|
|
2864
|
+
if (s.tracker.status === "busy") return "working";
|
|
2865
|
+
if (s.promptedAt > s.stoppedAt && this.now - s.promptedAt < PROMPT_GRACE_MS) return "working";
|
|
2866
|
+
return "finished";
|
|
2867
|
+
}
|
|
2868
|
+
};
|
|
2869
|
+
function conversationSummary(t) {
|
|
2870
|
+
if (!t) return {};
|
|
2871
|
+
const prompts = t.turns.filter((x) => x.role === "user").map((x) => clip(x.text.replace(/\s+/g, " "), 200));
|
|
2872
|
+
if (!t.title && !prompts.length) return {};
|
|
2873
|
+
return {
|
|
2874
|
+
conversation: {
|
|
2875
|
+
...t.title ? { title: t.title } : {},
|
|
2876
|
+
...prompts.length ? { firstPrompt: prompts[0] } : {},
|
|
2877
|
+
...prompts.length > 1 ? { recentPrompts: prompts.slice(-3) } : {}
|
|
2878
|
+
}
|
|
2879
|
+
};
|
|
2880
|
+
}
|
|
2881
|
+
var STRONG = /* @__PURE__ */ new Set(["name", "branch", "title", "worked in", "prompt", "edited"]);
|
|
2882
|
+
function workedSummary(w) {
|
|
2883
|
+
if (!w.length) return {};
|
|
2884
|
+
return { workedIn: w.map((x) => `${x.root} (${x.edits} edits, ${x.reads} reads)`) };
|
|
2885
|
+
}
|
|
2886
|
+
function pathsIn(command) {
|
|
2887
|
+
const out = /* @__PURE__ */ new Set();
|
|
2888
|
+
const abs = /^(?:[A-Za-z]:[\\/]|\/(?!\/))/;
|
|
2889
|
+
for (const m of command.matchAll(/"([^"\n]+)"|'([^'\n]+)'/g)) {
|
|
2890
|
+
const p = (m[1] ?? m[2] ?? "").trim();
|
|
2891
|
+
if (abs.test(p)) out.add(p);
|
|
2892
|
+
}
|
|
2893
|
+
for (const m of command.replace(/"[^"\n]*"|'[^'\n]*'/g, " ").matchAll(/(?:^|[\s=(])((?:[A-Za-z]:[\\/]|\/)[^\s"'`;|&<>()]+)/g)) {
|
|
2894
|
+
if (abs.test(m[1]) && m[1] !== "/") out.add(m[1]);
|
|
2895
|
+
}
|
|
2896
|
+
return [...out].slice(0, 10);
|
|
2897
|
+
}
|
|
2898
|
+
var STOP = /* @__PURE__ */ new Set([
|
|
2899
|
+
"the",
|
|
2900
|
+
"and",
|
|
2901
|
+
"for",
|
|
2902
|
+
"with",
|
|
2903
|
+
"that",
|
|
2904
|
+
"this",
|
|
2905
|
+
"from",
|
|
2906
|
+
"into",
|
|
2907
|
+
"onto",
|
|
2908
|
+
"then",
|
|
2909
|
+
"than",
|
|
2910
|
+
"please",
|
|
2911
|
+
"can",
|
|
2912
|
+
"could",
|
|
2913
|
+
"would",
|
|
2914
|
+
"should",
|
|
2915
|
+
"you",
|
|
2916
|
+
"your",
|
|
2917
|
+
"our",
|
|
2918
|
+
"its",
|
|
2919
|
+
"are",
|
|
2920
|
+
"was",
|
|
2921
|
+
"were",
|
|
2922
|
+
"has",
|
|
2923
|
+
"have",
|
|
2924
|
+
"had",
|
|
2925
|
+
"not",
|
|
2926
|
+
"but",
|
|
2927
|
+
"all",
|
|
2928
|
+
"any",
|
|
2929
|
+
"some",
|
|
2930
|
+
"one",
|
|
2931
|
+
"out",
|
|
2932
|
+
"make",
|
|
2933
|
+
"change",
|
|
2934
|
+
"update",
|
|
2935
|
+
"fix",
|
|
2936
|
+
"add",
|
|
2937
|
+
"set",
|
|
2938
|
+
"get",
|
|
2939
|
+
"put",
|
|
2940
|
+
"use",
|
|
2941
|
+
"now",
|
|
2942
|
+
"also",
|
|
2943
|
+
"just",
|
|
2944
|
+
"like",
|
|
2945
|
+
"want",
|
|
2946
|
+
"need",
|
|
2947
|
+
"tile",
|
|
2948
|
+
"terminal",
|
|
2949
|
+
"session",
|
|
2950
|
+
"agent",
|
|
2951
|
+
"work",
|
|
2952
|
+
"working",
|
|
2953
|
+
"thing",
|
|
2954
|
+
"there",
|
|
2955
|
+
"since",
|
|
2956
|
+
"because",
|
|
2957
|
+
"when",
|
|
2958
|
+
"where",
|
|
2959
|
+
"what",
|
|
2960
|
+
"which",
|
|
2961
|
+
"while",
|
|
2962
|
+
"about",
|
|
2963
|
+
"after",
|
|
2964
|
+
"before",
|
|
2965
|
+
"still",
|
|
2966
|
+
"very",
|
|
2967
|
+
"really",
|
|
2968
|
+
"only",
|
|
2969
|
+
"even",
|
|
2970
|
+
"more",
|
|
2971
|
+
"most",
|
|
2972
|
+
"much",
|
|
2973
|
+
"many",
|
|
2974
|
+
"other",
|
|
2975
|
+
"over",
|
|
2976
|
+
"under",
|
|
2977
|
+
"again",
|
|
2978
|
+
"seems",
|
|
2979
|
+
"look",
|
|
2980
|
+
"looks",
|
|
2981
|
+
"see",
|
|
2982
|
+
"show",
|
|
2983
|
+
"shows",
|
|
2984
|
+
"does",
|
|
2985
|
+
"doesn",
|
|
2986
|
+
"don",
|
|
2987
|
+
"did",
|
|
2988
|
+
"will",
|
|
2989
|
+
"won",
|
|
2990
|
+
"cannot",
|
|
2991
|
+
"edit",
|
|
2992
|
+
"sure",
|
|
2993
|
+
"should",
|
|
2994
|
+
"here",
|
|
2995
|
+
"they",
|
|
2996
|
+
"them",
|
|
2997
|
+
"their",
|
|
2998
|
+
"what",
|
|
2999
|
+
"who",
|
|
3000
|
+
"how",
|
|
3001
|
+
"why",
|
|
3002
|
+
"yes",
|
|
3003
|
+
"okay"
|
|
3004
|
+
]);
|
|
3005
|
+
function words(query) {
|
|
3006
|
+
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);
|
|
3007
|
+
return [...new Set(out)];
|
|
3008
|
+
}
|
|
3009
|
+
function turnText(t) {
|
|
3010
|
+
return `${t.text} ${t.files?.join(" ") ?? ""}`;
|
|
3011
|
+
}
|
|
3012
|
+
function snippet(text2, word) {
|
|
3013
|
+
const flat = text2.replace(/\s+/g, " ");
|
|
3014
|
+
const i = flat.toLowerCase().indexOf(word);
|
|
3015
|
+
const from = Math.max(0, i - 60);
|
|
3016
|
+
return `${from > 0 ? "\u2026" : ""}${flat.slice(from, from + 160)}${from + 160 < flat.length ? "\u2026" : ""}`;
|
|
3017
|
+
}
|
|
3018
|
+
function gitSummary(p) {
|
|
3019
|
+
return {
|
|
3020
|
+
repo: repoName(p.commonDir),
|
|
3021
|
+
branch: p.branch ?? (p.detached ? "(detached)" : null),
|
|
3022
|
+
worktree: p.root,
|
|
3023
|
+
linkedWorktree: p.linked
|
|
3024
|
+
};
|
|
3025
|
+
}
|
|
3026
|
+
function summary(i) {
|
|
3027
|
+
if (i.kind === "question") return `question: ${clip(i.questions?.map((q) => q.question).join(" / ") ?? "", 200)}`;
|
|
3028
|
+
const input = i.input ?? {};
|
|
3029
|
+
const what = String(input["command"] ?? input["file_path"] ?? input["url"] ?? "");
|
|
3030
|
+
return `permission for ${i.tool ?? "a tool"}${what ? `: ${clip(what, 200)}` : ""}`;
|
|
3031
|
+
}
|
|
3032
|
+
var str = (v) => typeof v === "string" && v.trim() ? v.trim() : void 0;
|
|
3033
|
+
var num = (v) => {
|
|
3034
|
+
const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
|
|
3035
|
+
return Number.isFinite(n) ? n : void 0;
|
|
3036
|
+
};
|
|
3037
|
+
|
|
1918
3038
|
// src/http.ts
|
|
1919
3039
|
var MIME = {
|
|
1920
3040
|
".html": "text/html; charset=utf-8",
|
|
@@ -1987,19 +3107,19 @@ function createHandler(opts) {
|
|
|
1987
3107
|
let usage = null;
|
|
1988
3108
|
const homeDir = () => process.env["HOME"] ?? os5.homedir();
|
|
1989
3109
|
const within = (root, dir) => {
|
|
1990
|
-
const rel =
|
|
1991
|
-
return rel === "" || !rel.startsWith("..") && !
|
|
3110
|
+
const rel = path12.relative(path12.resolve(root), dir);
|
|
3111
|
+
return rel === "" || !rel.startsWith("..") && !path12.isAbsolute(rel);
|
|
1992
3112
|
};
|
|
1993
3113
|
const real = async (p) => {
|
|
1994
3114
|
try {
|
|
1995
3115
|
return await realpath(p);
|
|
1996
3116
|
} catch {
|
|
1997
|
-
return
|
|
3117
|
+
return path12.resolve(p);
|
|
1998
3118
|
}
|
|
1999
3119
|
};
|
|
2000
3120
|
const browsable = async (dir) => {
|
|
2001
|
-
const
|
|
2002
|
-
const [target, ...resolved] = await Promise.all([dir, ...
|
|
3121
|
+
const roots2 = [homeDir(), ...pm.list().map((p) => p.root), ...opts.fsRoots ?? []];
|
|
3122
|
+
const [target, ...resolved] = await Promise.all([dir, ...roots2].map(real));
|
|
2003
3123
|
return resolved.some((root) => within(root, target));
|
|
2004
3124
|
};
|
|
2005
3125
|
return async function handle(req, res) {
|
|
@@ -2023,8 +3143,10 @@ function createHandler(opts) {
|
|
|
2023
3143
|
}
|
|
2024
3144
|
const hook = url.pathname.match(/^\/api\/sessions\/([^/]+)\/hook$/);
|
|
2025
3145
|
if (hook && req.method === "POST") {
|
|
2026
|
-
const
|
|
2027
|
-
|
|
3146
|
+
const id = decodeURIComponent(hook[1]);
|
|
3147
|
+
const agent = opts.agentSession?.(id);
|
|
3148
|
+
const s = pm.findSession(id);
|
|
3149
|
+
if (!s && !agent) return json(res, 404, { error: "no such session" });
|
|
2028
3150
|
const raw = await readBody(req);
|
|
2029
3151
|
if (raw === null) return tooLarge(req, res, "body too large");
|
|
2030
3152
|
let body;
|
|
@@ -2035,6 +3157,12 @@ function createHandler(opts) {
|
|
|
2035
3157
|
}
|
|
2036
3158
|
if (typeof body.event !== "string") return json(res, 400, { error: "event is required" });
|
|
2037
3159
|
const payload = body.payload && typeof body.payload === "object" ? body.payload : {};
|
|
3160
|
+
if (agent) {
|
|
3161
|
+
const conv = body.event === "SessionStart" ? claudeConversation({ id: payload.session_id, cwd: payload.cwd }) : null;
|
|
3162
|
+
if (conv) agent.setClaude(conv);
|
|
3163
|
+
return json(res, 200, { output: null });
|
|
3164
|
+
}
|
|
3165
|
+
if (!s) return json(res, 404, { error: "no such session" });
|
|
2038
3166
|
if (!opts.inbox) {
|
|
2039
3167
|
if (body.event === "Stop" || body.event === "Notification") s.hook();
|
|
2040
3168
|
return json(res, 200, { output: null });
|
|
@@ -2054,6 +3182,36 @@ function createHandler(opts) {
|
|
|
2054
3182
|
if (gone.signal.aborted) return;
|
|
2055
3183
|
return json(res, 200, { output });
|
|
2056
3184
|
}
|
|
3185
|
+
if (url.pathname === "/api/orchestrator/tools" && req.method === "GET") {
|
|
3186
|
+
return json(res, 200, { tools: TOOLS });
|
|
3187
|
+
}
|
|
3188
|
+
if (url.pathname === "/api/orchestrator/call" && req.method === "POST") {
|
|
3189
|
+
const tools = opts.tools;
|
|
3190
|
+
if (!tools) return json(res, 503, { error: "the orchestrator agent is not available" });
|
|
3191
|
+
const raw = await readBody(req);
|
|
3192
|
+
if (raw === null) return tooLarge(req, res, "body too large");
|
|
3193
|
+
let body;
|
|
3194
|
+
try {
|
|
3195
|
+
body = JSON.parse(raw || "{}");
|
|
3196
|
+
} catch {
|
|
3197
|
+
return json(res, 400, { error: "malformed body" });
|
|
3198
|
+
}
|
|
3199
|
+
if (typeof body.name !== "string") return json(res, 400, { error: "name is required" });
|
|
3200
|
+
const args = body.arguments && typeof body.arguments === "object" ? body.arguments : {};
|
|
3201
|
+
const gone = new AbortController();
|
|
3202
|
+
res.on("close", () => {
|
|
3203
|
+
if (!res.writableFinished) gone.abort();
|
|
3204
|
+
});
|
|
3205
|
+
try {
|
|
3206
|
+
const text2 = await tools.call(body.name, args, gone.signal);
|
|
3207
|
+
if (gone.signal.aborted) return;
|
|
3208
|
+
return json(res, 200, { text: text2, isError: false });
|
|
3209
|
+
} catch (err) {
|
|
3210
|
+
if (gone.signal.aborted) return;
|
|
3211
|
+
if (err instanceof ToolError) return json(res, 200, { text: err.message, isError: true });
|
|
3212
|
+
return json(res, 200, { text: `tring could not do that: ${err.message}`, isError: true });
|
|
3213
|
+
}
|
|
3214
|
+
}
|
|
2057
3215
|
if (url.pathname === "/api/hooks" && req.method === "GET") {
|
|
2058
3216
|
return json(res, 200, await hooksStatus(opts.claudeSettingsPath));
|
|
2059
3217
|
}
|
|
@@ -2090,12 +3248,12 @@ function createHandler(opts) {
|
|
|
2090
3248
|
}
|
|
2091
3249
|
if (url.pathname === "/api/fs" && req.method === "GET") {
|
|
2092
3250
|
const raw = url.searchParams.get("path")?.trim();
|
|
2093
|
-
const dir = raw ?
|
|
3251
|
+
const dir = raw ? path12.resolve(raw) : homeDir();
|
|
2094
3252
|
if (!await browsable(dir)) return json(res, 403, { error: "outside the browsable roots" });
|
|
2095
3253
|
try {
|
|
2096
|
-
const found = await
|
|
2097
|
-
const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path:
|
|
2098
|
-
const parent =
|
|
3254
|
+
const found = await readdir4(dir, { withFileTypes: true });
|
|
3255
|
+
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));
|
|
3256
|
+
const parent = path12.dirname(dir);
|
|
2099
3257
|
const up = parent !== dir && await browsable(parent) ? parent : null;
|
|
2100
3258
|
return json(res, 200, { path: dir, parent: up, entries });
|
|
2101
3259
|
} catch {
|
|
@@ -2142,15 +3300,15 @@ function createHandler(opts) {
|
|
|
2142
3300
|
}
|
|
2143
3301
|
async function serveStatic(res, pathname) {
|
|
2144
3302
|
const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
|
|
2145
|
-
const file =
|
|
2146
|
-
if (file !== webRoot && !file.startsWith(webRoot +
|
|
3303
|
+
const file = path12.resolve(webRoot, rel);
|
|
3304
|
+
if (file !== webRoot && !file.startsWith(webRoot + path12.sep)) {
|
|
2147
3305
|
text(res, 403, "forbidden");
|
|
2148
3306
|
return;
|
|
2149
3307
|
}
|
|
2150
3308
|
try {
|
|
2151
|
-
const info = await
|
|
3309
|
+
const info = await stat6(file);
|
|
2152
3310
|
if (!info.isFile()) throw new Error("not a file");
|
|
2153
|
-
head(res, 200, MIME[
|
|
3311
|
+
head(res, 200, MIME[path12.extname(file)] ?? "application/octet-stream");
|
|
2154
3312
|
createReadStream(file).pipe(res);
|
|
2155
3313
|
} catch {
|
|
2156
3314
|
if (rel === "index.html") {
|
|
@@ -2164,7 +3322,6 @@ function createHandler(opts) {
|
|
|
2164
3322
|
}
|
|
2165
3323
|
|
|
2166
3324
|
// src/ws.ts
|
|
2167
|
-
var PASTE_SETTLE_MS = 60;
|
|
2168
3325
|
var Hub = class {
|
|
2169
3326
|
constructor(opts) {
|
|
2170
3327
|
this.opts = opts;
|
|
@@ -2183,12 +3340,17 @@ var Hub = class {
|
|
|
2183
3340
|
};
|
|
2184
3341
|
if (opts.inbox) opts.inbox.onChange = () => this.broadcastInbox();
|
|
2185
3342
|
if (opts.auto) opts.auto.onChange = () => this.broadcastAuto();
|
|
2186
|
-
|
|
3343
|
+
const output = (s, data) => {
|
|
2187
3344
|
const frame = encodeOutput(s.id, Buffer.from(data, "utf8"));
|
|
2188
3345
|
for (const c of this.clients) {
|
|
2189
3346
|
if (c.authed && c.focusedId === s.id) c.ws.send(frame, { binary: true });
|
|
2190
3347
|
}
|
|
2191
3348
|
};
|
|
3349
|
+
pm.onSessionData = output;
|
|
3350
|
+
if (opts.agent) {
|
|
3351
|
+
opts.agent.onData = output;
|
|
3352
|
+
opts.agent.onChange = () => this.broadcastAgent();
|
|
3353
|
+
}
|
|
2192
3354
|
this.timer = setInterval(() => this.pumpSnapshots(), opts.snapshotMs ?? 250);
|
|
2193
3355
|
this.timer.unref?.();
|
|
2194
3356
|
}
|
|
@@ -2240,6 +3402,7 @@ var Hub = class {
|
|
|
2240
3402
|
this.sendSnapshots(c);
|
|
2241
3403
|
if (this.opts.inbox) this.send(c, { type: "inbox", items: this.opts.inbox.list() });
|
|
2242
3404
|
if (this.opts.auto) this.send(c, this.autoMessage(this.opts.auto));
|
|
3405
|
+
if (this.opts.agent) this.send(c, { type: "agent", agent: this.opts.agent.info() });
|
|
2243
3406
|
return;
|
|
2244
3407
|
}
|
|
2245
3408
|
if (!c.authed) return this.send(c, { type: "error", message: "expected hello" });
|
|
@@ -2247,7 +3410,7 @@ var Hub = class {
|
|
|
2247
3410
|
case "activateProject": {
|
|
2248
3411
|
pm.activate(msg.projectId);
|
|
2249
3412
|
c.projectId = msg.projectId;
|
|
2250
|
-
c.focusedId =
|
|
3413
|
+
c.focusedId = this.keepFocus(c);
|
|
2251
3414
|
this.sendState(c);
|
|
2252
3415
|
this.sendSnapshots(c);
|
|
2253
3416
|
break;
|
|
@@ -2264,7 +3427,7 @@ var Hub = class {
|
|
|
2264
3427
|
pm.deleteProject(msg.projectId);
|
|
2265
3428
|
if (c.projectId === msg.projectId) {
|
|
2266
3429
|
c.projectId = pm.activeProjectId;
|
|
2267
|
-
c.focusedId =
|
|
3430
|
+
c.focusedId = this.keepFocus(c);
|
|
2268
3431
|
}
|
|
2269
3432
|
break;
|
|
2270
3433
|
case "create":
|
|
@@ -2278,18 +3441,25 @@ var Hub = class {
|
|
|
2278
3441
|
case "focus": {
|
|
2279
3442
|
c.focusedId = msg.id;
|
|
2280
3443
|
if (!msg.id) break;
|
|
2281
|
-
const s =
|
|
3444
|
+
const s = this.find(msg.id);
|
|
2282
3445
|
if (!s) break;
|
|
2283
3446
|
s.resize(msg.cols, msg.rows);
|
|
2284
3447
|
this.send(c, { type: "screen", id: s.id, ansi: s.serialize() });
|
|
2285
3448
|
break;
|
|
2286
3449
|
}
|
|
2287
3450
|
case "input": {
|
|
2288
|
-
|
|
3451
|
+
this.find(msg.id)?.write(msg.data);
|
|
2289
3452
|
break;
|
|
2290
3453
|
}
|
|
2291
3454
|
case "resize": {
|
|
2292
|
-
if (c.focusedId)
|
|
3455
|
+
if (c.focusedId) this.find(c.focusedId)?.resize(msg.cols, msg.rows);
|
|
3456
|
+
break;
|
|
3457
|
+
}
|
|
3458
|
+
case "agent": {
|
|
3459
|
+
const agent = this.opts.agent;
|
|
3460
|
+
if (!agent) break;
|
|
3461
|
+
if (typeof msg.enabled === "boolean") void agent.setEnabled(msg.enabled);
|
|
3462
|
+
else if (msg.restart === "resume" || msg.restart === "fresh") void agent.restart(msg.restart === "fresh");
|
|
2293
3463
|
break;
|
|
2294
3464
|
}
|
|
2295
3465
|
case "kill":
|
|
@@ -2331,11 +3501,10 @@ var Hub = class {
|
|
|
2331
3501
|
const item = inbox?.get(msg.itemId);
|
|
2332
3502
|
if (!inbox || !item || item.kind !== "reply") break;
|
|
2333
3503
|
const s = pm.findSession(item.sessionId);
|
|
2334
|
-
const text2 =
|
|
3504
|
+
const text2 = cleanPrompt(msg.text);
|
|
2335
3505
|
if (!s || s.tracker.status === "busy" || s.tracker.status === "exited" || !text2) break;
|
|
2336
3506
|
inbox.answer(item.id, { decision: "allow" });
|
|
2337
|
-
s
|
|
2338
|
-
setTimeout(() => s.write("\r"), PASTE_SETTLE_MS).unref?.();
|
|
3507
|
+
typePrompt(s, text2);
|
|
2339
3508
|
break;
|
|
2340
3509
|
}
|
|
2341
3510
|
}
|
|
@@ -2395,6 +3564,20 @@ var Hub = class {
|
|
|
2395
3564
|
broadcastAuto() {
|
|
2396
3565
|
if (this.opts.auto) this.broadcast(this.autoMessage(this.opts.auto));
|
|
2397
3566
|
}
|
|
3567
|
+
/**
|
|
3568
|
+
* What a socket stays focused on when its project changes: the orchestrator
|
|
3569
|
+
* agent, which is in no project, and nothing else.
|
|
3570
|
+
*/
|
|
3571
|
+
keepFocus(c) {
|
|
3572
|
+
return c.focusedId && this.opts.agent?.find(c.focusedId) ? c.focusedId : null;
|
|
3573
|
+
}
|
|
3574
|
+
/** A tile, or the orchestrator agent's own terminal. */
|
|
3575
|
+
find(id) {
|
|
3576
|
+
return this.opts.pm.findSession(id) ?? this.opts.agent?.find(id);
|
|
3577
|
+
}
|
|
3578
|
+
broadcastAgent() {
|
|
3579
|
+
if (this.opts.agent) this.broadcast({ type: "agent", agent: this.opts.agent.info() });
|
|
3580
|
+
}
|
|
2398
3581
|
broadcastInbox() {
|
|
2399
3582
|
if (this.opts.inbox) this.broadcast({ type: "inbox", items: this.opts.inbox.list() });
|
|
2400
3583
|
}
|
|
@@ -2432,11 +3615,11 @@ function isWsl() {
|
|
|
2432
3615
|
}
|
|
2433
3616
|
function wslCandidates() {
|
|
2434
3617
|
const user = process.env["WSL_USER"] ?? "";
|
|
2435
|
-
const
|
|
3618
|
+
const roots2 = ["/mnt/c/Program Files", "/mnt/c/Program Files (x86)"];
|
|
2436
3619
|
const paths = [
|
|
2437
|
-
...
|
|
2438
|
-
...
|
|
2439
|
-
...
|
|
3620
|
+
...roots2.map((r) => `${r}/Google/Chrome/Application/chrome.exe`),
|
|
3621
|
+
...roots2.map((r) => `${r}/Microsoft/Edge/Application/msedge.exe`),
|
|
3622
|
+
...roots2.map((r) => `${r}/BraveSoftware/Brave-Browser/Application/brave.exe`)
|
|
2440
3623
|
];
|
|
2441
3624
|
if (user) paths.push(`/mnt/c/Users/${user}/AppData/Local/Google/Chrome/Application/chrome.exe`);
|
|
2442
3625
|
return paths;
|
|
@@ -2544,25 +3727,25 @@ import {
|
|
|
2544
3727
|
readdirSync
|
|
2545
3728
|
} from "node:fs";
|
|
2546
3729
|
import { createRequire as createRequire4 } from "node:module";
|
|
2547
|
-
import
|
|
3730
|
+
import path13 from "node:path";
|
|
2548
3731
|
var EXEC = 73;
|
|
2549
3732
|
function nodePtyRoot() {
|
|
2550
3733
|
try {
|
|
2551
|
-
return
|
|
3734
|
+
return path13.dirname(createRequire4(import.meta.url).resolve("node-pty/package.json"));
|
|
2552
3735
|
} catch {
|
|
2553
3736
|
return null;
|
|
2554
3737
|
}
|
|
2555
3738
|
}
|
|
2556
3739
|
function spawnHelperPaths(root) {
|
|
2557
|
-
const found = [
|
|
3740
|
+
const found = [path13.join(root, "build", "Release", "spawn-helper")];
|
|
2558
3741
|
let prebuilds;
|
|
2559
3742
|
try {
|
|
2560
|
-
prebuilds = readdirSync(
|
|
3743
|
+
prebuilds = readdirSync(path13.join(root, "prebuilds"), { withFileTypes: true });
|
|
2561
3744
|
} catch {
|
|
2562
3745
|
return found;
|
|
2563
3746
|
}
|
|
2564
3747
|
for (const entry of prebuilds) {
|
|
2565
|
-
if (entry.isDirectory()) found.push(
|
|
3748
|
+
if (entry.isDirectory()) found.push(path13.join(root, "prebuilds", entry.name, "spawn-helper"));
|
|
2566
3749
|
}
|
|
2567
3750
|
return found;
|
|
2568
3751
|
}
|
|
@@ -2591,7 +3774,7 @@ function fixSpawnHelper(root = nodePtyRoot()) {
|
|
|
2591
3774
|
import { spawn as spawn4 } from "node:child_process";
|
|
2592
3775
|
import { mkdir as mkdir5, readFile as readFile6, writeFile as writeFile5 } from "node:fs/promises";
|
|
2593
3776
|
import os7 from "node:os";
|
|
2594
|
-
import
|
|
3777
|
+
import path14 from "node:path";
|
|
2595
3778
|
var BASH_ALWAYS_ASK = [
|
|
2596
3779
|
/\brm\s+(-[a-zA-Z]*[rRf]|--recursive|--force)/,
|
|
2597
3780
|
/\bsudo\b|\bdoas\b|\bsu\s/,
|
|
@@ -2615,8 +3798,8 @@ var BASH_ALWAYS_ASK = [
|
|
|
2615
3798
|
var PATH_ALWAYS_ASK = /(^|\/)(\.env[^/]*|\.git\/|\.ssh\/|\.aws\/|id_rsa|id_ed25519|credentials[^/]*|\.npmrc|\.netrc|secrets?\.[a-z]+)$|(^|\/)\.git\//;
|
|
2616
3799
|
var FILE_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
2617
3800
|
var inside = (cwd, p) => {
|
|
2618
|
-
const rel =
|
|
2619
|
-
return rel === "" || !rel.startsWith("..") && !
|
|
3801
|
+
const rel = path14.relative(path14.resolve(cwd), path14.resolve(cwd, p));
|
|
3802
|
+
return rel === "" || !rel.startsWith("..") && !path14.isAbsolute(rel);
|
|
2620
3803
|
};
|
|
2621
3804
|
function rule(item, cwd) {
|
|
2622
3805
|
if (item.kind !== "permission") return { verdict: "ask", reason: "only permission prompts are auto-answered" };
|
|
@@ -2629,7 +3812,7 @@ function rule(item, cwd) {
|
|
|
2629
3812
|
const p = String(input["file_path"] ?? input["notebook_path"] ?? "");
|
|
2630
3813
|
if (!p) return { verdict: "ask", reason: "no file path given" };
|
|
2631
3814
|
if (!inside(cwd, p)) return { verdict: "ask", reason: "outside the session directory" };
|
|
2632
|
-
if (PATH_ALWAYS_ASK.test(
|
|
3815
|
+
if (PATH_ALWAYS_ASK.test(path14.resolve(cwd, p))) return { verdict: "ask", reason: "a secrets or git file" };
|
|
2633
3816
|
return { verdict: "classify" };
|
|
2634
3817
|
}
|
|
2635
3818
|
if (tool === "Bash") {
|
|
@@ -2750,7 +3933,7 @@ var AutoAnswerer = class {
|
|
|
2750
3933
|
this.on = on;
|
|
2751
3934
|
this.onChange?.();
|
|
2752
3935
|
if (!this.opts.statePath) return;
|
|
2753
|
-
await mkdir5(
|
|
3936
|
+
await mkdir5(path14.dirname(this.opts.statePath), { recursive: true });
|
|
2754
3937
|
await writeFile5(this.opts.statePath, JSON.stringify({ autoAnswer: on }, null, 2) + "\n", "utf8");
|
|
2755
3938
|
}
|
|
2756
3939
|
/**
|
|
@@ -2796,37 +3979,37 @@ var AutoAnswerer = class {
|
|
|
2796
3979
|
|
|
2797
3980
|
// src/hook-shim.ts
|
|
2798
3981
|
import { chmod, mkdir as mkdir6, writeFile as writeFile6 } from "node:fs/promises";
|
|
2799
|
-
import
|
|
3982
|
+
import path15 from "node:path";
|
|
2800
3983
|
async function writeHookShim(dir, node, script) {
|
|
2801
3984
|
await mkdir6(dir, { recursive: true });
|
|
2802
3985
|
const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
|
|
2803
|
-
await writeFile6(
|
|
3986
|
+
await writeFile6(path15.join(dir, "tring-hook"), `#!/bin/sh
|
|
2804
3987
|
exec ${q(node)} ${q(script)} "$@"
|
|
2805
3988
|
`, "utf8");
|
|
2806
|
-
await chmod(
|
|
2807
|
-
await writeFile6(
|
|
3989
|
+
await chmod(path15.join(dir, "tring-hook"), 493);
|
|
3990
|
+
await writeFile6(path15.join(dir, "tring-hook.cmd"), `@"${node}" "${script}" %*\r
|
|
2808
3991
|
`, "utf8");
|
|
2809
3992
|
}
|
|
2810
3993
|
function prependPath(current, dir) {
|
|
2811
|
-
const parts = (current ?? "").split(
|
|
2812
|
-
return [dir, ...parts].join(
|
|
3994
|
+
const parts = (current ?? "").split(path15.delimiter).filter((p) => p && p !== dir);
|
|
3995
|
+
return [dir, ...parts].join(path15.delimiter);
|
|
2813
3996
|
}
|
|
2814
3997
|
|
|
2815
3998
|
// src/autostart.ts
|
|
2816
|
-
import { execFile as
|
|
3999
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
2817
4000
|
import { mkdir as mkdir7, readFile as readFile7, rename as rename2, rm as rm2, writeFile as writeFile7 } from "node:fs/promises";
|
|
2818
4001
|
import os8 from "node:os";
|
|
2819
|
-
import
|
|
4002
|
+
import path16 from "node:path";
|
|
2820
4003
|
var MARKER = "written by tring autostart";
|
|
2821
4004
|
var LABEL = "chat.tring.daemon";
|
|
2822
4005
|
function autostartFile(e) {
|
|
2823
|
-
if (e.platform === "darwin") return
|
|
4006
|
+
if (e.platform === "darwin") return path16.join(e.home, "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
2824
4007
|
if (e.platform === "win32") {
|
|
2825
|
-
const appData = e.env["APPDATA"] ??
|
|
2826
|
-
return
|
|
4008
|
+
const appData = e.env["APPDATA"] ?? path16.join(e.home, "AppData", "Roaming");
|
|
4009
|
+
return path16.win32.join(appData, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "tring.cmd");
|
|
2827
4010
|
}
|
|
2828
|
-
const config = e.env["XDG_CONFIG_HOME"] ??
|
|
2829
|
-
return
|
|
4011
|
+
const config = e.env["XDG_CONFIG_HOME"] ?? path16.join(e.home, ".config");
|
|
4012
|
+
return path16.join(config, "systemd", "user", "tring.service");
|
|
2830
4013
|
}
|
|
2831
4014
|
var sdQuote = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
|
|
2832
4015
|
var xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
@@ -2884,7 +4067,7 @@ RestartSec=2
|
|
|
2884
4067
|
WantedBy=default.target
|
|
2885
4068
|
`;
|
|
2886
4069
|
}
|
|
2887
|
-
var defaultRun = (cmd, args) => new Promise((resolve) =>
|
|
4070
|
+
var defaultRun = (cmd, args) => new Promise((resolve) => execFile3(cmd, args, (err) => resolve(!err)));
|
|
2888
4071
|
async function autostartStatus(e) {
|
|
2889
4072
|
const file = autostartFile(e);
|
|
2890
4073
|
try {
|
|
@@ -2902,14 +4085,14 @@ async function autostartOn(e, flags = []) {
|
|
|
2902
4085
|
throw new ForeignAutostart(`${st.file} already exists and tring did not write it, so it was left alone.
|
|
2903
4086
|
If it already starts tring at login there is nothing to do; otherwise move it aside and run this again.`);
|
|
2904
4087
|
}
|
|
2905
|
-
await mkdir7(
|
|
4088
|
+
await mkdir7(path16.dirname(st.file), { recursive: true });
|
|
2906
4089
|
const tmp = `${st.file}.tring-${process.pid}`;
|
|
2907
4090
|
await writeFile7(tmp, autostartContent(e, flags), "utf8");
|
|
2908
4091
|
await rename2(tmp, st.file);
|
|
2909
|
-
const
|
|
4092
|
+
const run3 = e.run ?? defaultRun;
|
|
2910
4093
|
if (e.platform === "linux") {
|
|
2911
|
-
await
|
|
2912
|
-
if (!await
|
|
4094
|
+
await run3("systemctl", ["--user", "daemon-reload"]);
|
|
4095
|
+
if (!await run3("systemctl", ["--user", "enable", "tring.service"])) {
|
|
2913
4096
|
throw new Error(`wrote ${st.file}, but systemctl --user enable tring.service failed`);
|
|
2914
4097
|
}
|
|
2915
4098
|
}
|
|
@@ -2919,14 +4102,279 @@ async function autostartOff(e) {
|
|
|
2919
4102
|
const st = await autostartStatus(e);
|
|
2920
4103
|
if (!st.present) return false;
|
|
2921
4104
|
if (!st.ours) throw new ForeignAutostart(`${st.file} was not written by tring, so it was left alone.`);
|
|
2922
|
-
const
|
|
2923
|
-
if (e.platform === "linux") await
|
|
2924
|
-
if (e.platform === "darwin") await
|
|
4105
|
+
const run3 = e.run ?? defaultRun;
|
|
4106
|
+
if (e.platform === "linux") await run3("systemctl", ["--user", "disable", "tring.service"]);
|
|
4107
|
+
if (e.platform === "darwin") await run3("launchctl", ["bootout", `gui/${os8.userInfo().uid}/${LABEL}`]);
|
|
2925
4108
|
await rm2(st.file, { force: true });
|
|
2926
|
-
if (e.platform === "linux") await
|
|
4109
|
+
if (e.platform === "linux") await run3("systemctl", ["--user", "daemon-reload"]);
|
|
2927
4110
|
return true;
|
|
2928
4111
|
}
|
|
2929
4112
|
|
|
4113
|
+
// src/orchestrator-agent.ts
|
|
4114
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
4115
|
+
import { chmod as chmod2, mkdir as mkdir8, readFile as readFile8, writeFile as writeFile8, access } from "node:fs/promises";
|
|
4116
|
+
import path17 from "node:path";
|
|
4117
|
+
var PRE_ALLOWED = ["list_sessions", "list_worktrees", "find_work", "session_history", "read_session", "session_changes", "send_prompt", "wait_for"].map((t) => `mcp__tring__${t}`);
|
|
4118
|
+
var RESUME_FAIL_MS = 1e4;
|
|
4119
|
+
var OrchestratorAgent = class {
|
|
4120
|
+
constructor(opts) {
|
|
4121
|
+
this.opts = opts;
|
|
4122
|
+
}
|
|
4123
|
+
on = false;
|
|
4124
|
+
conversation = null;
|
|
4125
|
+
current = null;
|
|
4126
|
+
startedAt = 0;
|
|
4127
|
+
error = null;
|
|
4128
|
+
timer = null;
|
|
4129
|
+
onChange = null;
|
|
4130
|
+
onData = null;
|
|
4131
|
+
get enabled() {
|
|
4132
|
+
return this.on;
|
|
4133
|
+
}
|
|
4134
|
+
get session() {
|
|
4135
|
+
return this.current;
|
|
4136
|
+
}
|
|
4137
|
+
/** The agent's session, if `id` is it. */
|
|
4138
|
+
find(id) {
|
|
4139
|
+
return this.current && this.current.id === id ? this.current : void 0;
|
|
4140
|
+
}
|
|
4141
|
+
info() {
|
|
4142
|
+
return {
|
|
4143
|
+
enabled: this.on,
|
|
4144
|
+
id: this.current?.id ?? null,
|
|
4145
|
+
status: this.current?.tracker.status ?? null,
|
|
4146
|
+
error: this.error
|
|
4147
|
+
};
|
|
4148
|
+
}
|
|
4149
|
+
async load() {
|
|
4150
|
+
try {
|
|
4151
|
+
const raw = JSON.parse(await readFile8(this.opts.statePath, "utf8"));
|
|
4152
|
+
this.on = raw.enabled === true;
|
|
4153
|
+
this.conversation = claudeConversation(raw.claude);
|
|
4154
|
+
} catch {
|
|
4155
|
+
this.on = false;
|
|
4156
|
+
}
|
|
4157
|
+
if (this.on) await this.start();
|
|
4158
|
+
}
|
|
4159
|
+
async setEnabled(on) {
|
|
4160
|
+
if (on === this.on) return;
|
|
4161
|
+
this.on = on;
|
|
4162
|
+
if (on) await this.start();
|
|
4163
|
+
else this.stop();
|
|
4164
|
+
await this.save();
|
|
4165
|
+
this.onChange?.();
|
|
4166
|
+
}
|
|
4167
|
+
/** A fresh conversation, or the same one again after Claude was quit. */
|
|
4168
|
+
async restart(fresh) {
|
|
4169
|
+
if (!this.on) return;
|
|
4170
|
+
if (fresh) this.conversation = null;
|
|
4171
|
+
this.stop();
|
|
4172
|
+
await this.start();
|
|
4173
|
+
await this.save();
|
|
4174
|
+
this.onChange?.();
|
|
4175
|
+
}
|
|
4176
|
+
dispose() {
|
|
4177
|
+
this.stop();
|
|
4178
|
+
}
|
|
4179
|
+
stop() {
|
|
4180
|
+
if (this.timer) clearInterval(this.timer);
|
|
4181
|
+
this.timer = null;
|
|
4182
|
+
this.current?.dispose();
|
|
4183
|
+
this.current = null;
|
|
4184
|
+
}
|
|
4185
|
+
async start() {
|
|
4186
|
+
if (this.current) return;
|
|
4187
|
+
this.error = null;
|
|
4188
|
+
if (!this.opts.mcpScript) {
|
|
4189
|
+
this.error = "the tring MCP relay is missing from this install, so the agent would have no tools";
|
|
4190
|
+
this.onChange?.();
|
|
4191
|
+
return;
|
|
4192
|
+
}
|
|
4193
|
+
try {
|
|
4194
|
+
await this.writeWorkspace();
|
|
4195
|
+
} catch (err) {
|
|
4196
|
+
this.error = `cannot write ${this.opts.dir}: ${err.message}`;
|
|
4197
|
+
this.onChange?.();
|
|
4198
|
+
return;
|
|
4199
|
+
}
|
|
4200
|
+
const resume = this.conversation ? ` --resume ${this.conversation.id}` : "";
|
|
4201
|
+
const command = `claude --mcp-config tring-mcp.json${resume}`;
|
|
4202
|
+
const s = (this.opts.spawn ?? ((o) => new Session(o)))({
|
|
4203
|
+
id: randomUUID4(),
|
|
4204
|
+
projectId: "",
|
|
4205
|
+
projectName: "orchestrator",
|
|
4206
|
+
slot: 0,
|
|
4207
|
+
cwd: this.opts.dir,
|
|
4208
|
+
command,
|
|
4209
|
+
name: "Orchestrator",
|
|
4210
|
+
url: this.opts.url,
|
|
4211
|
+
token: this.opts.token,
|
|
4212
|
+
scrollback: this.opts.scrollback,
|
|
4213
|
+
idleMs: this.opts.idleMs,
|
|
4214
|
+
...this.opts.shell ? { shell: this.opts.shell } : {},
|
|
4215
|
+
autorun: true
|
|
4216
|
+
});
|
|
4217
|
+
this.current = s;
|
|
4218
|
+
this.startedAt = Date.now();
|
|
4219
|
+
this.timer = setInterval(() => s.tick(Date.now()), 500);
|
|
4220
|
+
this.timer.unref?.();
|
|
4221
|
+
s.onData = (data) => this.onData?.(s, data);
|
|
4222
|
+
s.onStatusChange = () => this.onChange?.();
|
|
4223
|
+
s.onClaudeChange = () => {
|
|
4224
|
+
if (s.claude) this.conversation = s.claude;
|
|
4225
|
+
void this.save();
|
|
4226
|
+
};
|
|
4227
|
+
s.onExit = () => {
|
|
4228
|
+
if (resume && Date.now() - this.startedAt < RESUME_FAIL_MS && this.current === s) {
|
|
4229
|
+
this.conversation = null;
|
|
4230
|
+
this.stop();
|
|
4231
|
+
void this.start().then(() => this.save()).then(() => this.onChange?.());
|
|
4232
|
+
return;
|
|
4233
|
+
}
|
|
4234
|
+
this.onChange?.();
|
|
4235
|
+
};
|
|
4236
|
+
this.onChange?.();
|
|
4237
|
+
}
|
|
4238
|
+
async save() {
|
|
4239
|
+
try {
|
|
4240
|
+
await mkdir8(path17.dirname(this.opts.statePath), { recursive: true });
|
|
4241
|
+
const saved = { enabled: this.on, claude: this.conversation };
|
|
4242
|
+
await writeFile8(this.opts.statePath, JSON.stringify(saved, null, 2) + "\n", "utf8");
|
|
4243
|
+
} catch {
|
|
4244
|
+
}
|
|
4245
|
+
}
|
|
4246
|
+
/**
|
|
4247
|
+
* Rewritten on every start, so an upgrade brings new instructions and a
|
|
4248
|
+
* moved Node with it. CLAUDE.md is the user's: written once, and it only
|
|
4249
|
+
* imports TRING.md, so anything they add there survives.
|
|
4250
|
+
*/
|
|
4251
|
+
async writeWorkspace() {
|
|
4252
|
+
const dir = this.opts.dir;
|
|
4253
|
+
await mkdir8(path17.join(dir, ".claude"), { recursive: true });
|
|
4254
|
+
const tokenFile = path17.join(dir, ".token");
|
|
4255
|
+
if (this.opts.token) {
|
|
4256
|
+
await writeFile8(tokenFile, `${this.opts.token}
|
|
4257
|
+
`, { mode: 384 });
|
|
4258
|
+
await chmod2(tokenFile, 384).catch(() => {
|
|
4259
|
+
});
|
|
4260
|
+
}
|
|
4261
|
+
const script = this.opts.mcpScript;
|
|
4262
|
+
const nodeArgs = script.endsWith(".ts") ? ["--experimental-strip-types", "--no-warnings"] : [];
|
|
4263
|
+
const mcp = {
|
|
4264
|
+
mcpServers: {
|
|
4265
|
+
tring: {
|
|
4266
|
+
type: "stdio",
|
|
4267
|
+
command: this.opts.node,
|
|
4268
|
+
args: [...nodeArgs, script, "--url", this.opts.url, ...this.opts.token ? ["--token-file", tokenFile] : []]
|
|
4269
|
+
}
|
|
4270
|
+
}
|
|
4271
|
+
};
|
|
4272
|
+
await writeFile8(path17.join(dir, "tring-mcp.json"), JSON.stringify(mcp, null, 2) + "\n", "utf8");
|
|
4273
|
+
await writeFile8(path17.join(dir, ".claude", "settings.json"), JSON.stringify({
|
|
4274
|
+
permissions: { allow: PRE_ALLOWED }
|
|
4275
|
+
}, null, 2) + "\n", "utf8");
|
|
4276
|
+
await writeFile8(path17.join(dir, "TRING.md"), INSTRUCTIONS, "utf8");
|
|
4277
|
+
const claudeMd = path17.join(dir, "CLAUDE.md");
|
|
4278
|
+
try {
|
|
4279
|
+
await access(claudeMd);
|
|
4280
|
+
} catch {
|
|
4281
|
+
await writeFile8(claudeMd, "@TRING.md\n\n# Your own instructions for the orchestrator go below.\n", "utf8");
|
|
4282
|
+
}
|
|
4283
|
+
}
|
|
4284
|
+
};
|
|
4285
|
+
var INSTRUCTIONS = `# You are the tring orchestrator
|
|
4286
|
+
|
|
4287
|
+
The user runs many terminal tiles in tring, most of them Claude Code agents,
|
|
4288
|
+
each in its own slot of a project. You sit in the centre of tring's
|
|
4289
|
+
orchestrator mode: the user talks to you instead of typing into each tile, and
|
|
4290
|
+
you get the work done through the agents in those tiles.
|
|
4291
|
+
|
|
4292
|
+
## Your tools (the \`tring\` MCP server)
|
|
4293
|
+
|
|
4294
|
+
- \`list_sessions\` \u2014 every project and tile: status (busy = working, done =
|
|
4295
|
+
finished and waiting, idle, exited), the directory its agent works in, its
|
|
4296
|
+
repository, worktree and branch, the repositories its agent has edited in
|
|
4297
|
+
(\`workedIn\`), whether it runs Claude Code, what it is waiting on, and what
|
|
4298
|
+
its agent last said. \`sameWorktreeAs\` marks tiles sharing a worktree.
|
|
4299
|
+
Start here whenever you need to know what is going on.
|
|
4300
|
+
- \`list_worktrees\` \u2014 every worktree of each repository, its branch, and
|
|
4301
|
+
which tiles are in it. Free worktrees are the ones with no tiles.
|
|
4302
|
+
- \`find_work\` \u2014 which tiles have been working on a topic, ranked: by name,
|
|
4303
|
+
branch, conversation title, the prompts they were given, what their agent
|
|
4304
|
+
said and the files they edited.
|
|
4305
|
+
- \`session_history\` \u2014 a tile's conversation: prompts, answers, edited files.
|
|
4306
|
+
- \`read_session\` \u2014 the last lines of a tile's terminal.
|
|
4307
|
+
- \`session_changes\` \u2014 the uncommitted git changes in a tile's worktree.
|
|
4308
|
+
- \`send_prompt\` \u2014 give an agent an instruction, as if the user typed it.
|
|
4309
|
+
- \`create_session\` \u2014 start a new Claude Code tile, optionally with a first
|
|
4310
|
+
prompt, and with \`branch\` in its own git worktree. The user approves each one.
|
|
4311
|
+
- \`wait_for\` \u2014 wait until tiles finish, then read what they said.
|
|
4312
|
+
|
|
4313
|
+
Refer to tiles the way the user does: by project and slot (\`tring.chat/3\`),
|
|
4314
|
+
or by name. A bare slot number means the project the user is looking at.
|
|
4315
|
+
|
|
4316
|
+
## How to work
|
|
4317
|
+
|
|
4318
|
+
- Delegate. You coordinate; the agents in the tiles do the coding, in their
|
|
4319
|
+
own repositories. Do not edit project files yourself unless the user asks.
|
|
4320
|
+
- The agents cannot see this conversation. Every prompt you send must stand
|
|
4321
|
+
on its own: the goal, the context they need, and what "done" looks like.
|
|
4322
|
+
- Pick the tile whose directory and branch fit the task. If none fits, or the
|
|
4323
|
+
work should run in parallel, offer to start a new tile.
|
|
4324
|
+
- After sending work, use \`wait_for\` and report back what each agent did, in
|
|
4325
|
+
a few lines. Quote them when it matters; never claim work an agent has not
|
|
4326
|
+
reported.
|
|
4327
|
+
- Permission prompts and questions from the agents are the user's to answer
|
|
4328
|
+
in tring's inbox, beside you. If a tile is waiting on one, say so; do not
|
|
4329
|
+
try to answer it by typing into that tile (send_prompt refuses anyway).
|
|
4330
|
+
- Keep replies short and scannable. The user is juggling many sessions.
|
|
4331
|
+
|
|
4332
|
+
## Which tile? Route by what each one has been doing
|
|
4333
|
+
|
|
4334
|
+
The user talks about work, not slots: "make the reporting box green". Send it
|
|
4335
|
+
to the agent that has been working on that, which already has the context.
|
|
4336
|
+
|
|
4337
|
+
1. Call \`find_work\` with the user's words. \`list_sessions\` also shows each
|
|
4338
|
+
tile's conversation title and recent prompts.
|
|
4339
|
+
2. One clear best match: confirm with \`session_history\` (\`search\` for the
|
|
4340
|
+
topic) when the match is thin, then send it there and tell the user which
|
|
4341
|
+
tile you chose and why, in one line.
|
|
4342
|
+
3. Several match about equally, or none does: do not guess. Ask the user,
|
|
4343
|
+
naming the candidates (slot, name, branch), or offer to start a new tile
|
|
4344
|
+
in its own worktree for it.
|
|
4345
|
+
4. A clear match that is busy, waiting on the user, or exited: say so, and ask
|
|
4346
|
+
whether to queue it there or start a new tile.
|
|
4347
|
+
|
|
4348
|
+
A tile's directory is where its shell started, not what it works on. A Claude
|
|
4349
|
+
started in the home directory may spend all day editing one repository:
|
|
4350
|
+
\`workedIn\` in \`list_sessions\` lists the repositories its agent has really
|
|
4351
|
+
edited and read in. When the user names an app or repository ("edit tring"),
|
|
4352
|
+
look there and in \`find_work\`, not only at directories and branches.
|
|
4353
|
+
|
|
4354
|
+
Never search the disk for a repository (no recursive listings of drives or
|
|
4355
|
+
home folders): it is slow and the user has to stop it. If the tools do not
|
|
4356
|
+
show it, ask the user for the path.
|
|
4357
|
+
|
|
4358
|
+
## Git worktrees
|
|
4359
|
+
|
|
4360
|
+
The user works in git worktrees: one branch, one worktree, one agent. Treat
|
|
4361
|
+
that as a rule, not a preference.
|
|
4362
|
+
|
|
4363
|
+
- Know where each agent is before you give it work: its \`git.branch\` and
|
|
4364
|
+
\`git.worktree\` in \`list_sessions\`, not just the tile's name. An agent can
|
|
4365
|
+
move into a worktree after its tile started; the tools follow it there.
|
|
4366
|
+
- Never give two agents work in the same worktree at once; they would edit the
|
|
4367
|
+
same files. If \`sameWorktreeAs\` shows a clash, tell the user.
|
|
4368
|
+
- New parallel work gets its own worktree: \`create_session\` with a
|
|
4369
|
+
\`branch\` (and \`base\` when it should not start from the current HEAD).
|
|
4370
|
+
If a worktree already has that branch, it is reused, not duplicated.
|
|
4371
|
+
- Name branches the way the user's existing branches are named (look at
|
|
4372
|
+
\`list_worktrees\`), e.g. with their ticket number when they use one.
|
|
4373
|
+
- Say which branch and worktree each piece of work is on when you report back.
|
|
4374
|
+
- Do not remove worktrees, delete branches, merge or push unless the user asks;
|
|
4375
|
+
when they do, have the agent in that worktree do it.
|
|
4376
|
+
`;
|
|
4377
|
+
|
|
2930
4378
|
// src/index.ts
|
|
2931
4379
|
function resolveAuth(args) {
|
|
2932
4380
|
if (args.insecureNoToken) return { token: null, persisted: false };
|
|
@@ -3015,15 +4463,15 @@ async function main() {
|
|
|
3015
4463
|
const tls = args.tlsCert && args.tlsKey ? loadTls(args.tlsCert, args.tlsKey) : null;
|
|
3016
4464
|
const url = `${tls ? "https" : "http"}://${args.host}:${args.port}`;
|
|
3017
4465
|
const cleartextOffBox = !tls && !isLoopbackBind(args.host);
|
|
3018
|
-
const here =
|
|
4466
|
+
const here = path18.dirname(fileURLToPath(import.meta.url));
|
|
3019
4467
|
const webRoot = [
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
].find((p) => existsSync2(p)) ??
|
|
4468
|
+
path18.resolve(here, "web"),
|
|
4469
|
+
path18.resolve(here, "../../web/dist")
|
|
4470
|
+
].find((p) => existsSync2(p)) ?? path18.resolve(here, "web");
|
|
3023
4471
|
for (const file of fixSpawnHelper()) console.log(`made ${file} executable`);
|
|
3024
|
-
const hookScript = [
|
|
4472
|
+
const hookScript = [path18.resolve(here, "tring-hook.js"), path18.resolve(here, "hook-cli.ts")].find((p) => existsSync2(p));
|
|
3025
4473
|
if (hookScript) {
|
|
3026
|
-
const binDir =
|
|
4474
|
+
const binDir = path18.join(path18.dirname(defaultTokenPath()), "bin");
|
|
3027
4475
|
try {
|
|
3028
4476
|
await writeHookShim(binDir, process.execPath, hookScript);
|
|
3029
4477
|
process.env["PATH"] = prependPath(process.env["PATH"], binDir);
|
|
@@ -3041,11 +4489,11 @@ async function main() {
|
|
|
3041
4489
|
...args.shell ? { shell: args.shell } : {}
|
|
3042
4490
|
});
|
|
3043
4491
|
const sameOrigin = createOriginCheck({ host: args.host, allow: args.allowOrigin });
|
|
3044
|
-
const uploads = new UploadStore(
|
|
4492
|
+
const uploads = new UploadStore(path18.join(path18.dirname(pm.statePath), "uploads"));
|
|
3045
4493
|
const inbox = new Inbox();
|
|
3046
4494
|
const auto = new AutoAnswerer({
|
|
3047
4495
|
inbox,
|
|
3048
|
-
statePath:
|
|
4496
|
+
statePath: path18.join(path18.dirname(pm.statePath), "orchestrator.json"),
|
|
3049
4497
|
context: (id) => {
|
|
3050
4498
|
const s = pm.findSession(id);
|
|
3051
4499
|
if (!s) return null;
|
|
@@ -3054,6 +4502,19 @@ async function main() {
|
|
|
3054
4502
|
}
|
|
3055
4503
|
});
|
|
3056
4504
|
await auto.load();
|
|
4505
|
+
const configDir = path18.dirname(pm.statePath);
|
|
4506
|
+
const agent = new OrchestratorAgent({
|
|
4507
|
+
dir: path18.join(configDir, "orchestrator"),
|
|
4508
|
+
statePath: path18.join(configDir, "orchestrator-agent.json"),
|
|
4509
|
+
url,
|
|
4510
|
+
token,
|
|
4511
|
+
scrollback: args.scrollback,
|
|
4512
|
+
idleMs: args.idleMs,
|
|
4513
|
+
...args.shell ? { shell: args.shell } : {},
|
|
4514
|
+
mcpScript: [path18.resolve(here, "tring-mcp.js"), path18.resolve(here, "mcp-cli.ts")].find((p) => existsSync2(p)) ?? null,
|
|
4515
|
+
node: process.execPath
|
|
4516
|
+
});
|
|
4517
|
+
const tools = new OrchestratorTools({ pm, inbox });
|
|
3057
4518
|
const handle = createHandler({
|
|
3058
4519
|
pm,
|
|
3059
4520
|
webRoot,
|
|
@@ -3064,7 +4525,9 @@ async function main() {
|
|
|
3064
4525
|
inbox,
|
|
3065
4526
|
onPermission: (item) => {
|
|
3066
4527
|
void auto.offer(item);
|
|
3067
|
-
}
|
|
4528
|
+
},
|
|
4529
|
+
tools,
|
|
4530
|
+
agentSession: (id) => agent.find(id)
|
|
3068
4531
|
});
|
|
3069
4532
|
const listener = (req, res) => {
|
|
3070
4533
|
void handle(req, res).catch(() => {
|
|
@@ -3073,8 +4536,9 @@ async function main() {
|
|
|
3073
4536
|
};
|
|
3074
4537
|
const server = tls ? createSecureServer(tls, listener) : createServer(listener);
|
|
3075
4538
|
const wss = new WebSocketServer({ server, verifyClient: upgradeGuard(sameOrigin) });
|
|
3076
|
-
const hub = new Hub({ pm, token, inbox, auto });
|
|
4539
|
+
const hub = new Hub({ pm, token, inbox, auto, agent });
|
|
3077
4540
|
hub.attach(wss);
|
|
4541
|
+
await agent.load();
|
|
3078
4542
|
const authUrl = token ? `${url}/?token=${encodeURIComponent(token)}` : url;
|
|
3079
4543
|
server.listen(args.port, args.host, () => {
|
|
3080
4544
|
console.log(`tring listening on ${url}`);
|
|
@@ -3086,7 +4550,7 @@ async function main() {
|
|
|
3086
4550
|
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
4551
|
}
|
|
3088
4552
|
if (args.updateCheck) {
|
|
3089
|
-
void checkForUpdate(
|
|
4553
|
+
void checkForUpdate(path18.join(path18.dirname(pm.statePath), "update-check.json")).then((latest) => {
|
|
3090
4554
|
if (!latest) return;
|
|
3091
4555
|
hub.setUpdate({ current: currentVersion(), latest });
|
|
3092
4556
|
console.log(`update available: ${currentVersion()} -> ${latest} (npm i -g tring-chat)`);
|
|
@@ -3102,6 +4566,7 @@ async function main() {
|
|
|
3102
4566
|
});
|
|
3103
4567
|
const shutdown = async () => {
|
|
3104
4568
|
hub.dispose();
|
|
4569
|
+
agent.dispose();
|
|
3105
4570
|
await uploads.dispose();
|
|
3106
4571
|
await pm.dispose();
|
|
3107
4572
|
server.close(() => process.exit(0));
|