tring-chat 0.1.18 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tring.js CHANGED
@@ -4,7 +4,8 @@
4
4
  import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
5
5
  import { createServer } from "node:http";
6
6
  import { createServer as createSecureServer } from "node:https";
7
- import path12 from "node:path";
7
+ import os9 from "node:os";
8
+ import path18 from "node:path";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { WebSocketServer } from "ws";
10
11
 
@@ -202,14 +203,14 @@ function isNewer(latest, current) {
202
203
  var DAY_MS = 24 * 60 * 60 * 1e3;
203
204
  async function checkForUpdate(cachePath) {
204
205
  const current = currentVersion();
205
- let cache = null;
206
+ let cache2 = null;
206
207
  try {
207
- cache = JSON.parse(await readFile(cachePath, "utf8"));
208
+ cache2 = JSON.parse(await readFile(cachePath, "utf8"));
208
209
  } catch {
209
- cache = null;
210
+ cache2 = null;
210
211
  }
211
- if (cache && Date.now() - cache.checkedAt < DAY_MS) {
212
- return isNewer(cache.latest, current) ? cache.latest : null;
212
+ if (cache2 && Date.now() - cache2.checkedAt < DAY_MS) {
213
+ return isNewer(cache2.latest, current) ? cache2.latest : null;
213
214
  }
214
215
  let latest;
215
216
  try {
@@ -240,6 +241,10 @@ var HELP = `tring \u2014 focus-centred terminal deck
240
241
  add or remove the Claude Code hooks orchestrator mode
241
242
  reads, in ~/.claude/settings.json. They do nothing
242
243
  outside a tring session
244
+ tring autostart on|off|status [flags]
245
+ start tring at login (systemd user unit, LaunchAgent, or
246
+ the Windows Startup folder), with the given flags.
247
+ With the hooks, a reboot reopens every Claude conversation
243
248
 
244
249
  --port <n> default ${DEFAULT_PORT}
245
250
  --host <addr> default ${DEFAULT_HOST}
@@ -395,13 +400,14 @@ function parseArgs(argv) {
395
400
  import { randomUUID as randomUUID2 } from "node:crypto";
396
401
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
397
402
  import os2 from "node:os";
398
- import path3 from "node:path";
403
+ import path4 from "node:path";
399
404
 
400
405
  // src/session-manager.ts
401
406
  import { randomUUID } from "node:crypto";
402
407
 
403
408
  // src/session.ts
404
409
  import { readlinkSync } from "node:fs";
410
+ import path3 from "node:path";
405
411
  import { createRequire as createRequire3 } from "node:module";
406
412
  import { spawn } from "node-pty";
407
413
 
@@ -441,7 +447,7 @@ function snapshot(term) {
441
447
  const line = buf.getLine(buf.viewportY + y);
442
448
  const out = [];
443
449
  if (line) {
444
- let run2 = null;
450
+ let run3 = null;
445
451
  for (let x = 0; x < term.cols; x++) {
446
452
  const cell = line.getCell(x);
447
453
  if (!cell) break;
@@ -450,11 +456,11 @@ function snapshot(term) {
450
456
  const fg = cell.isFgDefault() ? -1 : cell.getFgColor();
451
457
  const bg = cell.isBgDefault() ? -1 : cell.getBgColor();
452
458
  const bold = cell.isBold() !== 0;
453
- if (run2 && run2.fg === fg && run2.bg === bg && run2.bold === bold) {
454
- run2.text += text2;
459
+ if (run3 && run3.fg === fg && run3.bg === bg && run3.bold === bold) {
460
+ run3.text += text2;
455
461
  } else {
456
- run2 = { text: text2, fg, bg, bold };
457
- out.push(run2);
462
+ run3 = { text: text2, fg, bg, bold };
463
+ out.push(run3);
458
464
  }
459
465
  }
460
466
  while (out.length > 0) {
@@ -528,6 +534,25 @@ var { Terminal } = require4("@xterm/headless");
528
534
  var { SerializeAddon } = require4("@xterm/addon-serialize");
529
535
  var CWD_POLL_MS = 2e3;
530
536
  var CWD_ENFORCE_MS = 400;
537
+ var CLAUDE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
538
+ var INHERITED_CLAUDE = [
539
+ "CLAUDECODE",
540
+ "CLAUDE_PID",
541
+ "CLAUDE_EFFORT",
542
+ "CLAUDE_CODE_SESSION_ID",
543
+ "CLAUDE_CODE_CHILD_SESSION",
544
+ "CLAUDE_CODE_ENTRYPOINT",
545
+ "CLAUDE_CODE_SESSION_ATTENDED",
546
+ "CLAUDE_CODE_EXECPATH",
547
+ "CLAUDE_CODE_MESSAGING_SOCKET",
548
+ "CLAUDE_CODE_MESSAGING_TOKEN"
549
+ ];
550
+ function claudeConversation(v) {
551
+ if (!v || typeof v !== "object") return null;
552
+ const { id, cwd } = v;
553
+ if (typeof id !== "string" || !CLAUDE_ID.test(id)) return null;
554
+ return { id, cwd: typeof cwd === "string" && path3.isAbsolute(cwd) ? cwd : "" };
555
+ }
531
556
  var Session = class {
532
557
  id;
533
558
  projectId;
@@ -537,6 +562,23 @@ var Session = class {
537
562
  name;
538
563
  color;
539
564
  title = null;
565
+ /** The conversation running here, kept so a restart can reopen it. */
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;
540
582
  tracker;
541
583
  onData = null;
542
584
  onStatusChange = null;
@@ -553,6 +595,8 @@ var Session = class {
553
595
  hasInput = false;
554
596
  /** Fires when the shell moves, so the new location gets persisted. */
555
597
  onCwdChange = null;
598
+ /** Fires when Claude starts, switches or ends a conversation here. */
599
+ onClaudeChange = null;
556
600
  /**
557
601
  * Where the shell *is*, not where it started. A session spawned in a project
558
602
  * root that the developer then `cd`s out of must come back to where they
@@ -573,6 +617,7 @@ var Session = class {
573
617
  const shell = opts.shell ?? defaultShell();
574
618
  const env = {};
575
619
  for (const [k, v] of Object.entries(process.env)) if (v !== void 0) env[k] = v;
620
+ for (const k of INHERITED_CLAUDE) delete env[k];
576
621
  env["TRING_SESSION_ID"] = this.id;
577
622
  env["TRING_SLOT"] = String(this.slot);
578
623
  env["TRING_PROJECT"] = opts.projectName;
@@ -621,8 +666,15 @@ var Session = class {
621
666
  this.term.write(chunk);
622
667
  this.onData?.(chunk);
623
668
  });
624
- if (!(this.command && autorun) && usesPosixCd(shell)) {
625
- this.enforceTimer = setTimeout(() => this.enforceCwd(), CWD_ENFORCE_MS);
669
+ const interactive = !(this.command && autorun);
670
+ const resume = interactive ? claudeConversation(opts.resume) : null;
671
+ this.claude = resume;
672
+ const posix = usesPosixCd(shell);
673
+ if (interactive && (posix || resume)) {
674
+ this.enforceTimer = setTimeout(() => {
675
+ if (posix) this.enforceCwd();
676
+ if (resume) this.typeResume(resume, posix);
677
+ }, CWD_ENFORCE_MS);
626
678
  this.enforceTimer.unref?.();
627
679
  }
628
680
  this.pty.onExit(({ exitCode }) => {
@@ -683,6 +735,36 @@ var Session = class {
683
735
  snapshotNow() {
684
736
  return snapshot(this.term);
685
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
+ }
686
768
  /** Only when the screen actually changed, which is what keeps 16 tiles cheap. */
687
769
  takeSnapshot() {
688
770
  const shot = snapshot(this.term);
@@ -716,6 +798,27 @@ var Session = class {
716
798
  } catch {
717
799
  }
718
800
  }
801
+ /**
802
+ * Claude Code's hook payload is the only source of these, and it reports a
803
+ * conversation start (new, resumed, after /clear) and end. Null forgets it.
804
+ */
805
+ setClaude(conv) {
806
+ const next = conv ? claudeConversation(conv) : null;
807
+ if (conv && !next) return;
808
+ if (next?.id === this.claude?.id && next?.cwd === this.claude?.cwd) return;
809
+ this.claude = next;
810
+ this.onClaudeChange?.();
811
+ }
812
+ /**
813
+ * Typed straight to the PTY rather than through write(): it is tring's
814
+ * keystroke, not the user's, and must not count as them having taken over
815
+ * the shell. Skipped if they already have, since then the prompt is theirs.
816
+ */
817
+ typeResume(conv, posix) {
818
+ if (this.disposed || this.hasInput) return;
819
+ const cd = posix && conv.cwd && conv.cwd !== this.spawnCwd ? `cd -- ${shQuote(conv.cwd)} && ` : "";
820
+ this.pty.write(`${cd}claude --resume ${conv.id}\r`);
821
+ }
719
822
  /** Runs once, only if the shell is not where it was asked to be. */
720
823
  enforceCwd() {
721
824
  if (this.disposed || this.hasInput || process.platform !== "linux") return;
@@ -808,12 +911,14 @@ var SessionManager = class {
808
911
  scrollback: this.opts.scrollback,
809
912
  idleMs: this.opts.idleMs,
810
913
  ...this.opts.shell ? { shell: this.opts.shell } : {},
811
- autorun: spec.autorun
914
+ autorun: spec.autorun,
915
+ resume: spec.resume ?? null
812
916
  });
813
917
  session.onData = (data) => this.onSessionData?.(session, data);
814
918
  session.onStatusChange = () => this.onSessionStatus?.(session);
815
919
  session.onExit = (code) => this.onSessionExit?.(session, code);
816
920
  session.onCwdChange = () => this.structureChanged();
921
+ session.onClaudeChange = () => this.structureChanged();
817
922
  this.bySlot.set(slot, session);
818
923
  this.byId.set(session.id, session);
819
924
  this.structureChanged();
@@ -886,7 +991,10 @@ var SessionManager = class {
886
991
  command: old.command,
887
992
  name: old.name,
888
993
  color: old.color,
889
- autorun: true
994
+ autorun: true,
995
+ // A dead tile that was a shell running Claude comes back to the same
996
+ // conversation; one with its own command re-runs that instead.
997
+ resume: old.claude
890
998
  };
891
999
  this.quiet = true;
892
1000
  try {
@@ -915,8 +1023,8 @@ var SessionManager = class {
915
1023
 
916
1024
  // src/project-manager.ts
917
1025
  function defaultStatePath() {
918
- const base2 = process.env["XDG_CONFIG_HOME"] ?? path3.join(os2.homedir(), ".config");
919
- return path3.join(base2, "tring", "projects.json");
1026
+ const base2 = process.env["XDG_CONFIG_HOME"] ?? path4.join(os2.homedir(), ".config");
1027
+ return path4.join(base2, "tring", "projects.json");
920
1028
  }
921
1029
  var ProjectManager = class _ProjectManager {
922
1030
  constructor(opts) {
@@ -926,6 +1034,13 @@ var ProjectManager = class _ProjectManager {
926
1034
  activeId = null;
927
1035
  timer = null;
928
1036
  writing = Promise.resolve();
1037
+ /**
1038
+ * Set once shutdown starts. Stopping the daemon (or the machine) signals
1039
+ * every shell and Claude in it as well, and what they do on the way out —
1040
+ * exiting, ending their conversation — must not be saved as the state to
1041
+ * come back to.
1042
+ */
1043
+ closing = false;
929
1044
  onChange = null;
930
1045
  onSessionData = null;
931
1046
  onSessionStatus = null;
@@ -978,13 +1093,23 @@ var ProjectManager = class _ProjectManager {
978
1093
  this.changed();
979
1094
  }
980
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) {
981
1107
  const e = this.entries.get(id);
982
1108
  if (!e) return null;
983
- this.activeId = id;
984
1109
  if (!e.manager) {
985
1110
  e.manager = this.spawnManager(e);
986
1111
  for (const rec of e.pending) {
987
- e.manager.create({ ...rec, autorun: false });
1112
+ e.manager.create({ ...rec, autorun: false, resume: rec.claude ?? null });
988
1113
  }
989
1114
  e.pending = [];
990
1115
  }
@@ -1000,9 +1125,15 @@ var ProjectManager = class _ProjectManager {
1000
1125
  create(projectId, spec) {
1001
1126
  const id = projectId ?? this.activeId;
1002
1127
  if (!id) return null;
1003
- const mgr = this.managerFor(id) ?? this.activate(id);
1128
+ const mgr = this.ensure(id);
1004
1129
  return mgr ? mgr.create(spec) : null;
1005
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
+ }
1006
1137
  /** Session lookup by globally unique id, across every live project. */
1007
1138
  findSession(sessionId) {
1008
1139
  for (const e of this.entries.values()) {
@@ -1018,6 +1149,7 @@ var ProjectManager = class _ProjectManager {
1018
1149
  return void 0;
1019
1150
  }
1020
1151
  async dispose() {
1152
+ this.closing = true;
1021
1153
  if (this.timer) clearInterval(this.timer);
1022
1154
  this.timer = null;
1023
1155
  for (const e of this.entries.values()) e.manager?.disposeAll();
@@ -1048,6 +1180,7 @@ var ProjectManager = class _ProjectManager {
1048
1180
  for (const e of this.entries.values()) e.manager?.tick(now);
1049
1181
  }
1050
1182
  changed() {
1183
+ if (this.closing) return;
1051
1184
  this.onChange?.();
1052
1185
  void this.save();
1053
1186
  }
@@ -1064,7 +1197,8 @@ var ProjectManager = class _ProjectManager {
1064
1197
  name: s.name,
1065
1198
  cwd: s.cwd,
1066
1199
  command: s.command,
1067
- color: s.color
1200
+ color: s.color,
1201
+ ...s.claude ? { claude: s.claude } : {}
1068
1202
  })) : e.pending
1069
1203
  }))
1070
1204
  };
@@ -1072,7 +1206,7 @@ var ProjectManager = class _ProjectManager {
1072
1206
  save() {
1073
1207
  const state = this.snapshotState();
1074
1208
  this.writing = this.writing.then(async () => {
1075
- await mkdir2(path3.dirname(this.statePath), { recursive: true });
1209
+ await mkdir2(path4.dirname(this.statePath), { recursive: true });
1076
1210
  await writeFile2(this.statePath, JSON.stringify(state, null, 2), "utf8");
1077
1211
  }).catch(() => {
1078
1212
  });
@@ -1102,9 +1236,9 @@ var ProjectManager = class _ProjectManager {
1102
1236
 
1103
1237
  // src/http.ts
1104
1238
  import { createReadStream } from "node:fs";
1105
- import { readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";
1239
+ import { readdir as readdir4, realpath, stat as stat5 } from "node:fs/promises";
1106
1240
  import os5 from "node:os";
1107
- import path8 from "node:path";
1241
+ import path12 from "node:path";
1108
1242
 
1109
1243
  // src/security.ts
1110
1244
  import { createHash, timingSafeEqual } from "node:crypto";
@@ -1180,7 +1314,7 @@ var SECURITY_HEADERS = Object.freeze({
1180
1314
  import { spawn as spawn2 } from "node:child_process";
1181
1315
  import { readdir, readFile as readFile3, stat } from "node:fs/promises";
1182
1316
  import os3 from "node:os";
1183
- import path4 from "node:path";
1317
+ import path5 from "node:path";
1184
1318
  var WINDOW_MS = 5 * 36e5;
1185
1319
  var WEEK_MS = 7 * 24 * 36e5;
1186
1320
  var PRICES = [
@@ -1192,8 +1326,8 @@ var PRICES = [
1192
1326
  ["claude-haiku-", 1, 5]
1193
1327
  ];
1194
1328
  function defaultTranscriptDir() {
1195
- const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path4.join(os3.homedir(), ".claude");
1196
- return path4.join(base2, "projects");
1329
+ const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path5.join(os3.homedir(), ".claude");
1330
+ return path5.join(base2, "projects");
1197
1331
  }
1198
1332
  var empty = () => ({ tokens: 0, cacheReadTokens: 0, cost: 0, messages: 0 });
1199
1333
  function add(b, e) {
@@ -1301,7 +1435,7 @@ async function transcripts(dir, since) {
1301
1435
  const out = [];
1302
1436
  for (const name of names) {
1303
1437
  if (!name.endsWith(".jsonl")) continue;
1304
- const file = path4.join(dir, name);
1438
+ const file = path5.join(dir, name);
1305
1439
  try {
1306
1440
  if ((await stat(file)).mtimeMs >= since) out.push(file);
1307
1441
  } catch {
@@ -1326,7 +1460,7 @@ function parseLimits(text2) {
1326
1460
  }
1327
1461
  function readLimits(timeoutMs = 3e4) {
1328
1462
  const args = ["-p", "/usage", "--output-format", "json"];
1329
- const run2 = (cmd) => new Promise((resolve, reject) => {
1463
+ const run3 = (cmd) => new Promise((resolve, reject) => {
1330
1464
  const child = spawn2(cmd, args, { stdio: ["ignore", "pipe", "ignore"] });
1331
1465
  let out = "";
1332
1466
  let settled = false;
@@ -1356,8 +1490,8 @@ function readLimits(timeoutMs = 3e4) {
1356
1490
  }, 50);
1357
1491
  });
1358
1492
  });
1359
- return run2("claude").catch(
1360
- (err) => process.platform === "win32" && err.code === "ENOENT" ? run2("claude.cmd") : Promise.reject(err)
1493
+ return run3("claude").catch(
1494
+ (err) => process.platform === "win32" && err.code === "ENOENT" ? run3("claude.cmd") : Promise.reject(err)
1361
1495
  );
1362
1496
  }
1363
1497
  async function collectUsage(dir, now) {
@@ -1381,7 +1515,7 @@ function describe(err) {
1381
1515
  // src/uploads.ts
1382
1516
  import { randomBytes as randomBytes2 } from "node:crypto";
1383
1517
  import { mkdir as mkdir3, readdir as readdir2, rm, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
1384
- import path5 from "node:path";
1518
+ import path6 from "node:path";
1385
1519
  var MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
1386
1520
  var KEEP = 20;
1387
1521
  function sniffImage(bytes) {
@@ -1410,7 +1544,7 @@ var UploadStore = class {
1410
1544
  const ext = sniffImage(bytes);
1411
1545
  const tail = ext ?? "-" + (name.replace(/[^\w.-]+/g, "_").slice(-80) || "file");
1412
1546
  await mkdir3(this.dir, { recursive: true, mode: 448 });
1413
- const file = path5.join(this.dir, randomBytes2(8).toString("hex") + tail);
1547
+ const file = path6.join(this.dir, randomBytes2(8).toString("hex") + tail);
1414
1548
  await writeFile3(file, bytes, { mode: 384 });
1415
1549
  await this.prune();
1416
1550
  return file;
@@ -1429,7 +1563,7 @@ var UploadStore = class {
1429
1563
  const names = await readdir2(this.dir);
1430
1564
  if (names.length <= this.keep) return;
1431
1565
  const dated = await Promise.all(names.map(async (name) => {
1432
- const full = path5.join(this.dir, name);
1566
+ const full = path6.join(this.dir, name);
1433
1567
  return { full, at: (await stat2(full)).mtimeMs };
1434
1568
  }));
1435
1569
  dated.sort((a, b) => b.at - a.at);
@@ -1442,7 +1576,7 @@ var UploadStore = class {
1442
1576
  // src/git-diff.ts
1443
1577
  import { execFile } from "node:child_process";
1444
1578
  import { lstat, readFile as readFile4 } from "node:fs/promises";
1445
- import path6 from "node:path";
1579
+ import path7 from "node:path";
1446
1580
  import { promisify } from "node:util";
1447
1581
  var run = promisify(execFile);
1448
1582
  var MAX_PATCH_BYTES = 1 << 20;
@@ -1497,7 +1631,7 @@ function splitPatch(text2) {
1497
1631
  return out;
1498
1632
  }
1499
1633
  async function untracked(root, rel, budget) {
1500
- const full = path6.join(root, rel);
1634
+ const full = path7.join(root, rel);
1501
1635
  let bytes;
1502
1636
  try {
1503
1637
  const st = await lstat(full);
@@ -1677,10 +1811,14 @@ function hookOutput(event, input, s) {
1677
1811
  }
1678
1812
 
1679
1813
  // src/hook-route.ts
1814
+ var USER_ENDED = /* @__PURE__ */ new Set(["prompt_input_exit", "logout", "clear"]);
1680
1815
  function routeHook(req) {
1681
1816
  const { inbox, session, event, payload } = req;
1682
1817
  const tool = payload.tool_name;
1683
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);
1684
1822
  switch (event) {
1685
1823
  case "PermissionRequest":
1686
1824
  if (!tool || tool === "AskUserQuestion") return Promise.resolve(null);
@@ -1694,15 +1832,25 @@ function routeHook(req) {
1694
1832
  case "Stop": {
1695
1833
  session.hook();
1696
1834
  const said = payload.last_assistant_message?.trim();
1835
+ session.said?.(said ?? "");
1697
1836
  if (said) inbox.reply(session.id, said);
1698
1837
  return Promise.resolve(null);
1699
1838
  }
1700
1839
  case "Notification":
1701
1840
  session.hook();
1702
1841
  return Promise.resolve(null);
1842
+ // New, resumed, after /clear or a compaction: whichever, it is now the
1843
+ // conversation this tile would reopen.
1844
+ case "SessionStart":
1845
+ if (payload.session_id) session.setClaude({ id: payload.session_id, cwd: payload.cwd ?? "" });
1846
+ return Promise.resolve(null);
1847
+ case "SessionEnd":
1848
+ if (payload.reason && USER_ENDED.has(payload.reason)) session.setClaude(null);
1849
+ return Promise.resolve(null);
1703
1850
  // The user typed into this session's own terminal: whatever its cards
1704
1851
  // were asking has been dealt with there.
1705
1852
  case "UserPromptSubmit":
1853
+ session.prompted?.();
1706
1854
  inbox.dropSession(session.id);
1707
1855
  return Promise.resolve(null);
1708
1856
  // The tool ran (or failed), so its permission prompt is over. Matched on
@@ -1736,7 +1884,7 @@ function hold(req, fields) {
1736
1884
  // src/hooks-install.ts
1737
1885
  import { copyFile, mkdir as mkdir4, readFile as readFile5, rename, writeFile as writeFile4 } from "node:fs/promises";
1738
1886
  import os4 from "node:os";
1739
- import path7 from "node:path";
1887
+ import path8 from "node:path";
1740
1888
  var HOOK_COMMAND = "tring-hook";
1741
1889
  var HOOK_SPECS = [
1742
1890
  { event: "PermissionRequest", timeout: 3600 },
@@ -1745,11 +1893,14 @@ var HOOK_SPECS = [
1745
1893
  { event: "PostToolUseFailure", timeout: 10 },
1746
1894
  { event: "UserPromptSubmit", timeout: 10 },
1747
1895
  { event: "Notification", timeout: 10 },
1748
- { event: "Stop", timeout: 10 }
1896
+ { event: "Stop", timeout: 10 },
1897
+ // Which conversation each tile is running, so a restart can reopen it.
1898
+ { event: "SessionStart", timeout: 10 },
1899
+ { event: "SessionEnd", timeout: 10 }
1749
1900
  ];
1750
1901
  function defaultClaudeSettingsPath() {
1751
- const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path7.join(os4.homedir(), ".claude");
1752
- return path7.join(base2, "settings.json");
1902
+ const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path8.join(os4.homedir(), ".claude");
1903
+ return path8.join(base2, "settings.json");
1753
1904
  }
1754
1905
  var ours = (h) => typeof h.command === "string" && h.command.trim().startsWith(HOOK_COMMAND + " ");
1755
1906
  function withoutHooks(settings) {
@@ -1803,7 +1954,7 @@ async function read(file) {
1803
1954
  return parsed;
1804
1955
  }
1805
1956
  async function write(file, previous, settings) {
1806
- await mkdir4(path7.dirname(file), { recursive: true });
1957
+ await mkdir4(path8.dirname(file), { recursive: true });
1807
1958
  if (previous) await copyFile(file, `${file}.tring-backup`);
1808
1959
  const tmp = `${file}.tring-${process.pid}`;
1809
1960
  await writeFile4(tmp, JSON.stringify(settings, null, 2) + "\n", "utf8");
@@ -1830,6 +1981,913 @@ async function uninstallHooks(file = defaultClaudeSettingsPath()) {
1830
1981
  return true;
1831
1982
  }
1832
1983
 
1984
+ // src/orchestrator-tools.ts
1985
+ import { stat as stat4 } from "node:fs/promises";
1986
+ import path11 from "node:path";
1987
+
1988
+ // src/git-worktrees.ts
1989
+ import { execFile as execFile2 } from "node:child_process";
1990
+ import path9 from "node:path";
1991
+ import { promisify as promisify2 } from "node:util";
1992
+ var run2 = promisify2(execFile2);
1993
+ async function git2(cwd, args, timeout = 5e3) {
1994
+ try {
1995
+ const { stdout } = await run2("git", ["-c", "core.fsmonitor=false", ...args], { cwd, encoding: "utf8", timeout });
1996
+ return stdout;
1997
+ } catch {
1998
+ return null;
1999
+ }
2000
+ }
2001
+ function samePath(a, b) {
2002
+ return normal(a) === normal(b);
2003
+ }
2004
+ function normal(p) {
2005
+ const r = path9.resolve(p).replace(/[\\/]+$/, "");
2006
+ return process.platform === "win32" ? r.toLowerCase() : r;
2007
+ }
2008
+ function repoName(commonDir) {
2009
+ const base2 = path9.basename(commonDir);
2010
+ return base2 === ".git" ? path9.basename(path9.dirname(commonDir)) : base2.replace(/\.git$/, "");
2011
+ }
2012
+ function branchSlug(branch) {
2013
+ return branch.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "worktree";
2014
+ }
2015
+ function parseWorktreeList(text2) {
2016
+ const out = [];
2017
+ for (const block of text2.replace(/\r\n/g, "\n").split(/\n\n+/)) {
2018
+ const lines = block.split("\n").filter(Boolean);
2019
+ const first = lines[0];
2020
+ if (!first?.startsWith("worktree ")) continue;
2021
+ const w = {
2022
+ path: first.slice("worktree ".length),
2023
+ branch: null,
2024
+ head: null,
2025
+ bare: false,
2026
+ detached: false,
2027
+ locked: false,
2028
+ prunable: false
2029
+ };
2030
+ for (const l of lines.slice(1)) {
2031
+ if (l.startsWith("HEAD ")) w.head = l.slice(5);
2032
+ else if (l.startsWith("branch ")) w.branch = l.slice(7).replace(/^refs\/heads\//, "");
2033
+ else if (l === "bare") w.bare = true;
2034
+ else if (l === "detached") w.detached = true;
2035
+ else if (l === "locked" || l.startsWith("locked ")) w.locked = true;
2036
+ else if (l === "prunable" || l.startsWith("prunable ")) w.prunable = true;
2037
+ }
2038
+ out.push(w);
2039
+ }
2040
+ return out;
2041
+ }
2042
+ function defaultWorktreePath(commonDir, existing, branch) {
2043
+ const slug = branchSlug(branch);
2044
+ const linked = existing.filter((w, i) => i > 0 && !w.bare && !w.prunable);
2045
+ const parents = [...new Set(linked.map((w) => normal(path9.dirname(w.path))))];
2046
+ if (parents.length === 1) return path9.join(path9.dirname(linked[0].path), slug);
2047
+ const repoDir = path9.basename(commonDir) === ".git" ? path9.dirname(commonDir) : commonDir;
2048
+ return path9.join(path9.dirname(repoDir), `${repoName(commonDir)}.worktrees`, slug);
2049
+ }
2050
+ var realGit = {
2051
+ async place(dir) {
2052
+ const out = await git2(dir, ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-dir", "--git-common-dir"]);
2053
+ const [root, gitDir, commonDir] = out?.trim().split(/\r?\n/) ?? [];
2054
+ if (!root || !gitDir || !commonDir) return null;
2055
+ const branch = (await git2(dir, ["symbolic-ref", "--quiet", "--short", "HEAD"]))?.trim() || null;
2056
+ const detached = !branch && await git2(dir, ["rev-parse", "--verify", "--quiet", "HEAD"]) !== null;
2057
+ return { root: path9.resolve(root), commonDir: path9.resolve(commonDir), linked: !samePath(gitDir, commonDir), branch, detached };
2058
+ },
2059
+ async worktrees(dir) {
2060
+ const out = await git2(dir, ["worktree", "list", "--porcelain"]);
2061
+ return out ? parseWorktreeList(out).map((w) => ({ ...w, path: path9.resolve(w.path) })) : [];
2062
+ },
2063
+ async branchExists(dir, branch) {
2064
+ return await git2(dir, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]) !== null;
2065
+ },
2066
+ async checkBranch(dir, branch) {
2067
+ if (!branch || branch.startsWith("-")) return `"${branch}" is not a usable branch name`;
2068
+ return await git2(dir, ["check-ref-format", "--branch", branch]) === null ? `"${branch}" is not a valid branch name` : null;
2069
+ },
2070
+ async addWorktree(dir, spec) {
2071
+ const args = spec.create ? ["worktree", "add", "-b", spec.branch, spec.path, ...spec.base ? [spec.base] : []] : ["worktree", "add", spec.path, spec.branch];
2072
+ try {
2073
+ await run2("git", args, { cwd: dir, encoding: "utf8", timeout: 18e4 });
2074
+ return null;
2075
+ } catch (err) {
2076
+ const e = err;
2077
+ return (e.stderr || e.message).trim().split(/\r?\n/).slice(-3).join(" ");
2078
+ }
2079
+ }
2080
+ };
2081
+
2082
+ // src/type-prompt.ts
2083
+ var PASTE_SETTLE_MS = 60;
2084
+ function cleanPrompt(text2) {
2085
+ return String(text2 ?? "").replace(/\x1b\[20[01]~/g, "").replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "").trimEnd();
2086
+ }
2087
+ function typePrompt(target, text2) {
2088
+ target.write(`\x1B[200~${text2}\x1B[201~`);
2089
+ setTimeout(() => target.write("\r"), PASTE_SETTLE_MS).unref?.();
2090
+ }
2091
+
2092
+ // src/transcript.ts
2093
+ import { open, readdir as readdir3, stat as stat3 } from "node:fs/promises";
2094
+ import path10 from "node:path";
2095
+ var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
2096
+ var WHOLE_BYTES = 8 << 20;
2097
+ var HEAD_BYTES = 512 << 10;
2098
+ var TAIL_BYTES = 8 << 20;
2099
+ function humanPrompt(j) {
2100
+ const msg = j["message"];
2101
+ if (j["isMeta"] || j["isSidechain"]) return null;
2102
+ const origin = j["origin"];
2103
+ if (origin && origin.kind !== "human") return null;
2104
+ let text2 = null;
2105
+ if (typeof msg?.content === "string") text2 = msg.content;
2106
+ else if (Array.isArray(msg?.content)) {
2107
+ const blocks = msg.content;
2108
+ if (blocks.some((b) => b.type === "tool_result")) return null;
2109
+ text2 = blocks.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n") || null;
2110
+ }
2111
+ text2 = text2?.trim() ?? null;
2112
+ if (!text2 || text2.startsWith("<")) return null;
2113
+ return text2;
2114
+ }
2115
+ function parseTranscript(lines) {
2116
+ let title = null;
2117
+ const turns = [];
2118
+ for (const line of lines) {
2119
+ if (!line.trim()) continue;
2120
+ let j;
2121
+ try {
2122
+ j = JSON.parse(line);
2123
+ } catch {
2124
+ continue;
2125
+ }
2126
+ const at = typeof j["timestamp"] === "string" ? j["timestamp"] : null;
2127
+ if (j["type"] === "ai-title" && typeof j["aiTitle"] === "string") {
2128
+ title = j["aiTitle"];
2129
+ continue;
2130
+ }
2131
+ if (j["type"] === "user") {
2132
+ const text2 = humanPrompt(j);
2133
+ if (text2) turns.push({ role: "user", text: text2, at });
2134
+ continue;
2135
+ }
2136
+ if (j["type"] !== "assistant" || j["isSidechain"]) continue;
2137
+ const blocks = j["message"]?.content;
2138
+ if (!Array.isArray(blocks)) continue;
2139
+ const texts = [];
2140
+ const files = [];
2141
+ for (const b of blocks) {
2142
+ if (b.type === "text" && b.text?.trim()) texts.push(b.text.trim());
2143
+ if (b.type === "tool_use" && b.name && EDIT_TOOLS.has(b.name)) {
2144
+ const f = b.input?.["file_path"] ?? b.input?.["notebook_path"];
2145
+ if (typeof f === "string") files.push(f);
2146
+ }
2147
+ }
2148
+ if (!texts.length && !files.length) continue;
2149
+ const last = turns[turns.length - 1];
2150
+ if (last?.role === "assistant") {
2151
+ if (texts.length) last.text = [last.text, ...texts].filter(Boolean).join("\n\n");
2152
+ if (files.length) last.files = [.../* @__PURE__ */ new Set([...last.files ?? [], ...files])];
2153
+ } else {
2154
+ turns.push({ role: "assistant", text: texts.join("\n\n"), at, ...files.length ? { files: [...new Set(files)] } : {} });
2155
+ }
2156
+ }
2157
+ return { title, turns };
2158
+ }
2159
+ async function readRange(file, start, length) {
2160
+ const fh = await open(file, "r");
2161
+ try {
2162
+ const buf = Buffer.alloc(length);
2163
+ const { bytesRead } = await fh.read(buf, 0, length, start);
2164
+ return buf.subarray(0, bytesRead).toString("utf8");
2165
+ } finally {
2166
+ await fh.close();
2167
+ }
2168
+ }
2169
+ var cache = /* @__PURE__ */ new Map();
2170
+ var CACHE_LIMIT = 48;
2171
+ async function readTranscript(file) {
2172
+ let info;
2173
+ try {
2174
+ info = await stat3(file);
2175
+ } catch {
2176
+ return null;
2177
+ }
2178
+ const key = `${info.size}:${info.mtimeMs}`;
2179
+ const hit = cache.get(file);
2180
+ if (hit?.key === key) return hit.value;
2181
+ let lines;
2182
+ let partial = false;
2183
+ try {
2184
+ if (info.size <= WHOLE_BYTES) {
2185
+ lines = (await readRange(file, 0, info.size)).split("\n");
2186
+ } else {
2187
+ const head2 = (await readRange(file, 0, HEAD_BYTES)).split("\n").slice(0, -1);
2188
+ const tail = (await readRange(file, info.size - TAIL_BYTES, TAIL_BYTES)).split("\n").slice(1);
2189
+ lines = [...head2, ...tail];
2190
+ partial = true;
2191
+ }
2192
+ } catch {
2193
+ return null;
2194
+ }
2195
+ const value = { ...parseTranscript(lines), partial };
2196
+ cache.delete(file);
2197
+ cache.set(file, { key, value });
2198
+ if (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
2199
+ return value;
2200
+ }
2201
+ async function findTranscript(projectsDir, id) {
2202
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return null;
2203
+ let dirs;
2204
+ try {
2205
+ dirs = await readdir3(projectsDir);
2206
+ } catch {
2207
+ return null;
2208
+ }
2209
+ for (const d of dirs) {
2210
+ const f = path10.join(projectsDir, d, `${id}.jsonl`);
2211
+ try {
2212
+ if ((await stat3(f)).isFile()) return f;
2213
+ } catch {
2214
+ }
2215
+ }
2216
+ return null;
2217
+ }
2218
+
2219
+ // src/orchestrator-tools.ts
2220
+ var ToolError = class extends Error {
2221
+ };
2222
+ var SESSION_REF = {
2223
+ type: "string",
2224
+ description: 'A session id from list_sessions, or "<project>/<slot>" such as "tring.chat/3". A bare slot number means the project the user is viewing.'
2225
+ };
2226
+ var TOOLS = [
2227
+ {
2228
+ name: "list_sessions",
2229
+ description: "Every project and terminal tile in tring: slot, name, status (busy = working, done = finished and waiting for the user, idle, exited), the directory its agent is working in, its git repository, worktree and branch, whether it runs Claude Code, what it is waiting on, and the last thing its agent said. Flags tiles that share a worktree. Call this first to know what is going on.",
2230
+ inputSchema: {
2231
+ type: "object",
2232
+ properties: { project: { type: "string", description: "Only this project (name or id)." } },
2233
+ additionalProperties: false
2234
+ }
2235
+ },
2236
+ {
2237
+ name: "list_worktrees",
2238
+ description: "Every git worktree of each project's repository (and of any repository a tile is in): path, branch, whether it is the main checkout, and which tiles are working in it. Use it to find a free worktree for new work, or to see where a branch is checked out.",
2239
+ inputSchema: {
2240
+ type: "object",
2241
+ properties: { project: { type: "string", description: "Only this project's repository (name or id)." } },
2242
+ additionalProperties: false
2243
+ }
2244
+ },
2245
+ {
2246
+ name: "find_work",
2247
+ description: 'Which tiles have been working on something: ranks every tile by how well the request matches its name, branch, worktree, conversation title, the prompts it was given, what its agent said and the files it edited. Use it whenever the user refers to work by topic ("the reporting box", "the login bug") instead of by tile.',
2248
+ inputSchema: {
2249
+ type: "object",
2250
+ properties: { query: { type: "string", description: 'What the user is talking about, in their words, e.g. "reporting box colour".' } },
2251
+ required: ["query"],
2252
+ additionalProperties: false
2253
+ }
2254
+ },
2255
+ {
2256
+ name: "session_history",
2257
+ description: "A tile's Claude Code conversation: the prompts it was given, what its agent answered and the files it edited, newest last. With `search`, only the turns that mention it. Use it to confirm a tile is the one working on something before sending it work.",
2258
+ inputSchema: {
2259
+ type: "object",
2260
+ properties: {
2261
+ session: SESSION_REF,
2262
+ turns: { type: "integer", minimum: 1, maximum: 60, description: "How many recent turns, default 12." },
2263
+ search: { type: "string", description: "Only turns mentioning these words." }
2264
+ },
2265
+ required: ["session"],
2266
+ additionalProperties: false
2267
+ }
2268
+ },
2269
+ {
2270
+ name: "read_session",
2271
+ description: "The last lines of a tile's terminal (screen and scrollback) as plain text: what its agent or shell is showing right now.",
2272
+ inputSchema: {
2273
+ type: "object",
2274
+ properties: {
2275
+ session: SESSION_REF,
2276
+ lines: { type: "integer", minimum: 1, maximum: 400, description: "How many lines, default 80." }
2277
+ },
2278
+ required: ["session"],
2279
+ additionalProperties: false
2280
+ }
2281
+ },
2282
+ {
2283
+ name: "session_changes",
2284
+ description: "The uncommitted git changes in the worktree a tile's agent is working in: files with lines added and removed, and the patch (all files, trimmed, or one file in full).",
2285
+ inputSchema: {
2286
+ type: "object",
2287
+ properties: {
2288
+ session: SESSION_REF,
2289
+ file: { type: "string", description: "Only this file's patch (a path from the file list)." }
2290
+ },
2291
+ required: ["session"],
2292
+ additionalProperties: false
2293
+ }
2294
+ },
2295
+ {
2296
+ name: "send_prompt",
2297
+ description: "Send a prompt to the Claude Code agent in a tile, as if the user typed it there and pressed Enter. Only works on tiles running Claude Code that are not waiting on a permission prompt or question. A busy agent queues it. Use wait_for afterwards to get its answer.",
2298
+ inputSchema: {
2299
+ type: "object",
2300
+ properties: {
2301
+ session: SESSION_REF,
2302
+ text: { type: "string", description: "The prompt. Write it as a complete instruction; that agent cannot see this conversation." }
2303
+ },
2304
+ required: ["session", "text"],
2305
+ additionalProperties: false
2306
+ }
2307
+ },
2308
+ {
2309
+ name: "create_session",
2310
+ description: "Start a new tile running Claude Code in the first empty slot of a project, optionally with a first prompt. Give `branch` to run it in a git worktree for that branch: an existing worktree that has the branch checked out is reused; otherwise a new worktree is added (checking out the branch if it exists, or creating it from `base`). One agent per worktree: parallel work gets its own branch. The user sees the new tile in the ring.",
2311
+ inputSchema: {
2312
+ type: "object",
2313
+ properties: {
2314
+ project: { type: "string", description: "Project name or id; default the project the user is viewing." },
2315
+ cwd: { type: "string", description: "Working directory, or with `branch` the repository to add the worktree to; default the project root. A relative path is resolved against the root." },
2316
+ branch: { type: "string", description: 'Run in a worktree for this branch, e.g. "feature/CHV-3193-login".' },
2317
+ base: { type: "string", description: "With a new `branch`: what to branch from (branch, tag or commit); default the repository's current HEAD." },
2318
+ worktree_path: { type: "string", description: "With `branch`: where to put a new worktree. Default: beside the existing worktrees, or <parent>/<repo>.worktrees/<branch>." },
2319
+ name: { type: "string", description: 'A short tile name, e.g. "api tests"; defaults to the branch.' },
2320
+ prompt: { type: "string", description: "First prompt, sent once Claude Code is ready." }
2321
+ },
2322
+ additionalProperties: false
2323
+ }
2324
+ },
2325
+ {
2326
+ name: "wait_for",
2327
+ description: "Wait until the given tiles finish their current work (or need the user, or exit), then return each one's status and last message. Use after send_prompt or create_session.",
2328
+ inputSchema: {
2329
+ type: "object",
2330
+ properties: {
2331
+ sessions: { type: "array", items: SESSION_REF, minItems: 1 },
2332
+ timeout_seconds: { type: "integer", minimum: 5, maximum: 900, description: "Default 300." }
2333
+ },
2334
+ required: ["sessions"],
2335
+ additionalProperties: false
2336
+ }
2337
+ }
2338
+ ];
2339
+ var MAX_LAST_MESSAGE = 600;
2340
+ var MAX_PATCH_CHARS = 16e3;
2341
+ var READY_TIMEOUT_MS = 3e4;
2342
+ var READY_SETTLE_MS = 1500;
2343
+ var PROMPT_GRACE_MS = 15e3;
2344
+ var clip = (s, n) => s.length > n ? `${s.slice(0, n)}\u2026 (${s.length - n} more characters)` : s;
2345
+ async function isDirectory(p) {
2346
+ try {
2347
+ return (await stat4(p)).isDirectory();
2348
+ } catch {
2349
+ return false;
2350
+ }
2351
+ }
2352
+ var workdir = (s) => s.agentCwd ?? s.cwd;
2353
+ var OrchestratorTools = class {
2354
+ constructor(d) {
2355
+ this.d = d;
2356
+ }
2357
+ get now() {
2358
+ return (this.d.now ?? Date.now)();
2359
+ }
2360
+ get git() {
2361
+ return this.d.git ?? realGit;
2362
+ }
2363
+ sleep(ms) {
2364
+ return (this.d.sleep ?? ((t) => new Promise((r) => setTimeout(r, t))))(ms);
2365
+ }
2366
+ async call(name, args, signal) {
2367
+ switch (name) {
2368
+ case "list_sessions":
2369
+ return this.listSessions(str(args["project"]));
2370
+ case "list_worktrees":
2371
+ return this.listWorktrees(str(args["project"]));
2372
+ case "find_work":
2373
+ return this.findWork(String(args["query"] ?? ""));
2374
+ case "session_history":
2375
+ return this.sessionHistory(this.resolve(args["session"]), num(args["turns"]) ?? 12, str(args["search"]));
2376
+ case "read_session":
2377
+ return this.readSession(this.resolve(args["session"]), num(args["lines"]) ?? 80);
2378
+ case "session_changes":
2379
+ return this.changes(this.resolve(args["session"]), str(args["file"]));
2380
+ case "send_prompt":
2381
+ return this.sendPrompt(this.resolve(args["session"]), String(args["text"] ?? ""));
2382
+ case "create_session":
2383
+ return this.createSession(args, signal);
2384
+ case "wait_for":
2385
+ return this.waitFor(args, signal);
2386
+ }
2387
+ throw new ToolError(`unknown tool ${name}`);
2388
+ }
2389
+ /** "<project>/<slot>", a session id, or a slot in the viewed project. */
2390
+ resolve(ref) {
2391
+ const r = String(ref ?? "").trim();
2392
+ if (!r) throw new ToolError("session is required");
2393
+ const byId = this.d.pm.findSession(r);
2394
+ if (byId) return byId;
2395
+ const at = r.lastIndexOf("/");
2396
+ const projectRef = at >= 0 ? r.slice(0, at) : null;
2397
+ const slot = Number(at >= 0 ? r.slice(at + 1) : r);
2398
+ const project = projectRef !== null ? this.d.pm.findProject(projectRef) : this.d.pm.list().find((p) => p.id === this.d.pm.activeProjectId);
2399
+ if (!project) throw new ToolError(`no project ${projectRef ?? "(none is being viewed)"}; see list_sessions`);
2400
+ if (!Number.isInteger(slot)) throw new ToolError(`cannot read "${r}" as a session; use an id or "<project>/<slot>"`);
2401
+ const info = project.sessions.find((s2) => s2.slot === slot);
2402
+ const s = info && this.d.pm.findSession(info.id);
2403
+ if (!s) throw new ToolError(`slot ${slot} in ${project.name} is empty`);
2404
+ return s;
2405
+ }
2406
+ ref(s) {
2407
+ const project = this.d.pm.list().find((p) => p.id === s.projectId);
2408
+ return `${project?.name ?? "project"}/${s.slot}`;
2409
+ }
2410
+ label(s) {
2411
+ return `${this.ref(s)}${s.name ? ` (${s.name})` : ""}`;
2412
+ }
2413
+ waiting(s) {
2414
+ return this.d.inbox.list().filter((i) => i.sessionId === s.id && i.kind !== "reply");
2415
+ }
2416
+ allSessions() {
2417
+ return this.d.pm.list().flatMap((p) => p.sessions).map((i) => this.d.pm.findSession(i.id)).filter((s) => !!s);
2418
+ }
2419
+ /** Every tile with its repository and worktree, in one pass of git calls. */
2420
+ async placeAll(sessions = this.allSessions()) {
2421
+ const memo = /* @__PURE__ */ new Map();
2422
+ const place = (dir) => {
2423
+ const k = normal(dir);
2424
+ if (!memo.has(k)) memo.set(k, this.git.place(dir));
2425
+ return memo.get(k);
2426
+ };
2427
+ return Promise.all(sessions.map(async (s) => ({ s, ref: this.ref(s), place: await place(workdir(s)) })));
2428
+ }
2429
+ /** Other live tiles whose agents are in the same worktree as `p`. */
2430
+ sharing(p, all) {
2431
+ if (!p.place) return [];
2432
+ return all.filter((o) => o.s.id !== p.s.id && o.place && o.s.tracker.status !== "exited" && samePath(o.place.root, p.place.root));
2433
+ }
2434
+ async listSessions(only) {
2435
+ let projects = this.d.pm.list();
2436
+ if (only) {
2437
+ const p = this.d.pm.findProject(only);
2438
+ if (!p) throw new ToolError(`no project ${only}; projects: ${projects.map((x) => x.name).join(", ")}`);
2439
+ projects = [p];
2440
+ }
2441
+ const placed = await this.placeAll();
2442
+ const byId = new Map(placed.map((p) => [p.s.id, p]));
2443
+ const talks = new Map(await Promise.all(placed.map(async (p) => [p.s.id, await this.history(p.s)])));
2444
+ const out = projects.map((p) => ({
2445
+ project: p.name,
2446
+ id: p.id,
2447
+ root: p.root,
2448
+ viewing: p.id === this.d.pm.activeProjectId,
2449
+ sessions: p.sessions.map((info) => {
2450
+ const pl = byId.get(info.id);
2451
+ const s = pl?.s;
2452
+ const waiting = s ? this.waiting(s) : [];
2453
+ const shared = pl ? this.sharing(pl, placed).map((o) => o.ref) : [];
2454
+ const agentDir = s?.agentCwd && !samePath(s.agentCwd, info.cwd) ? s.agentCwd : null;
2455
+ return {
2456
+ ref: `${p.name}/${info.slot}`,
2457
+ id: info.id,
2458
+ slot: info.slot,
2459
+ name: info.name ?? info.title ?? null,
2460
+ status: info.status,
2461
+ cwd: info.cwd,
2462
+ ...agentDir ? { agentCwd: agentDir } : {},
2463
+ git: pl?.place ? gitSummary(pl.place) : null,
2464
+ ...shared.length ? { sameWorktreeAs: shared } : {},
2465
+ agent: s?.claude ? "claude" : null,
2466
+ ...conversationSummary(talks.get(info.id) ?? null),
2467
+ ...waiting.length ? { waitingOnUser: waiting.map(summary) } : {},
2468
+ ...s?.lastMessage ? { lastMessage: clip(s.lastMessage, MAX_LAST_MESSAGE) } : {}
2469
+ };
2470
+ })
2471
+ }));
2472
+ return JSON.stringify({ projects: out }, null, 2);
2473
+ }
2474
+ async listWorktrees(only) {
2475
+ let projects = this.d.pm.list();
2476
+ if (only) {
2477
+ const p = this.d.pm.findProject(only);
2478
+ if (!p) throw new ToolError(`no project ${only}; projects: ${projects.map((x) => x.name).join(", ")}`);
2479
+ projects = [p];
2480
+ }
2481
+ const placed = await this.placeAll();
2482
+ const repos = /* @__PURE__ */ new Map();
2483
+ const add2 = (place, dir, project) => {
2484
+ if (!place) return;
2485
+ const k = normal(place.commonDir);
2486
+ const r = repos.get(k) ?? { dir, projects: /* @__PURE__ */ new Set() };
2487
+ if (project) r.projects.add(project);
2488
+ repos.set(k, r);
2489
+ };
2490
+ const roots = await Promise.all(projects.map(async (p) => ({ p, place: await this.git.place(p.root) })));
2491
+ for (const { p, place } of roots) add2(place, p.root, p.name);
2492
+ const wanted = new Set(projects.map((p) => p.id));
2493
+ for (const pl of placed) if (wanted.has(pl.s.projectId)) add2(pl.place, workdir(pl.s));
2494
+ if (repos.size === 0) return "No git repositories: none of these projects or tiles is inside one.";
2495
+ const out = await Promise.all([...repos.entries()].map(async ([commonDir, r]) => {
2496
+ const trees = await this.git.worktrees(r.dir);
2497
+ return {
2498
+ repo: repoName(commonDir),
2499
+ ...r.projects.size ? { projects: [...r.projects] } : {},
2500
+ // git lists the main worktree first; in a bare-repo layout that entry
2501
+ // is the bare repository itself, and every checkout is a linked one.
2502
+ worktrees: trees.map((w, i) => ({ w, main: i === 0 && !w.bare })).filter(({ w }) => !w.bare).map(({ w, main: main2 }) => {
2503
+ const tiles = placed.filter((pl) => pl.place && samePath(pl.place.root, w.path));
2504
+ return {
2505
+ path: w.path,
2506
+ branch: w.branch ?? (w.detached ? "(detached)" : null),
2507
+ main: main2,
2508
+ tiles: tiles.map((t) => `${t.ref} ${t.s.tracker.status}${t.s.claude ? " claude" : ""}`),
2509
+ ...w.locked ? { locked: true } : {},
2510
+ ...w.prunable ? { prunable: true } : {}
2511
+ };
2512
+ })
2513
+ };
2514
+ }));
2515
+ return JSON.stringify({ repos: out }, null, 2);
2516
+ }
2517
+ /** The tile's conversation, from the transcript its hooks named, or found by id. */
2518
+ async history(s) {
2519
+ const t = this.d.transcripts ?? {
2520
+ read: readTranscript,
2521
+ find: (id) => findTranscript(defaultTranscriptDir(), id)
2522
+ };
2523
+ const file = s.transcript ?? (s.claude ? await t.find(s.claude.id) : null);
2524
+ return file ? t.read(file) : null;
2525
+ }
2526
+ async sessionHistory(s, count, search) {
2527
+ const talk = await this.history(s);
2528
+ if (!talk) {
2529
+ return `${this.label(s)}: no conversation to read${s.claude ? " (its transcript was not found)" : " \u2014 it is not running Claude Code"}.`;
2530
+ }
2531
+ const n = Math.max(1, Math.min(60, Math.floor(count)));
2532
+ let turns = talk.turns;
2533
+ if (search) {
2534
+ const ws = words(search);
2535
+ turns = turns.filter((t) => ws.some((w) => turnText(t).toLowerCase().includes(w)));
2536
+ if (!turns.length) return `${this.label(s)}: nothing in its conversation mentions "${search}".`;
2537
+ }
2538
+ const shown = turns.slice(-n);
2539
+ const head2 = `${this.label(s)}${talk.title ? ` \u2014 "${talk.title}"` : ""}: ${shown.length} of ${turns.length} ${search ? "matching " : ""}turn(s)${talk.partial ? " (a very long conversation: only its start and end were read)" : ""}`;
2540
+ const body = shown.map((t) => {
2541
+ const who = t.role === "user" ? "PROMPT" : "AGENT";
2542
+ const files = t.files?.length ? `
2543
+ (edited: ${t.files.join(", ")})` : "";
2544
+ return `[${who}${t.at ? ` ${t.at.slice(0, 16).replace("T", " ")}` : ""}]
2545
+ ${clip(t.text, t.role === "user" ? 800 : 1500)}${files}`;
2546
+ });
2547
+ return `${head2}
2548
+
2549
+ ${body.join("\n\n")}`;
2550
+ }
2551
+ /**
2552
+ * Ranks tiles against what the user said. Each word counts for more the
2553
+ * fewer tiles mention it — "change" is everywhere, "reporting" is not — and
2554
+ * what a tile was asked, titled or edited counts for more than what its
2555
+ * agent happened to say, as do its recent turns over its old ones.
2556
+ */
2557
+ async findWork(query) {
2558
+ const ws = words(query);
2559
+ if (!ws.length) throw new ToolError('say what the work is about, e.g. "reporting box"');
2560
+ const placed = await this.placeAll();
2561
+ const docs = await Promise.all(placed.map(async (p) => {
2562
+ const talk = await this.history(p.s);
2563
+ const fields = [
2564
+ { why: "name", text: [p.s.name, p.s.title].filter(Boolean).join(" "), weight: 4 },
2565
+ { why: "branch", text: [p.place?.branch, p.place?.root].filter(Boolean).join(" "), weight: 4 },
2566
+ { why: "title", text: talk?.title ?? "", weight: 4 },
2567
+ { why: "last message", text: p.s.lastMessage ?? "", weight: 1 }
2568
+ ];
2569
+ const turns = talk?.turns ?? [];
2570
+ turns.forEach((t, i) => {
2571
+ const recent = i >= turns.length - 10 ? 2 : 1;
2572
+ if (t.role === "user") fields.push({ why: "prompt", text: t.text, weight: 3 * recent });
2573
+ else fields.push({ why: "agent said", text: t.text, weight: recent });
2574
+ if (t.files?.length) fields.push({ why: "edited", text: t.files.join(" "), weight: 3 * recent });
2575
+ });
2576
+ return { p, fields };
2577
+ }));
2578
+ const df = new Map(ws.map((w) => [w, docs.filter((d) => d.fields.some((f) => f.text.toLowerCase().includes(w))).length]));
2579
+ const ranked = docs.map(({ p, fields }) => {
2580
+ let score = 0;
2581
+ const why = /* @__PURE__ */ new Set();
2582
+ let best = null;
2583
+ let confident = false;
2584
+ for (const f of fields) {
2585
+ const low = f.text.toLowerCase();
2586
+ const hit = ws.filter((w) => low.includes(w));
2587
+ if (!hit.length) continue;
2588
+ const s = f.weight * hit.reduce((n, w) => n + 1 / df.get(w), 0) * (hit.length === ws.length ? 2 : 1);
2589
+ score += s;
2590
+ why.add(f.why);
2591
+ if (!best || s > best.score) best = { score: s, text: snippet(f.text, hit[0]) };
2592
+ if (hit.length === ws.length || STRONG.has(f.why) && hit.length >= ws.length / 2) confident = true;
2593
+ }
2594
+ return { p, score, confident, why: [...why], snippet: best?.text ?? "" };
2595
+ }).filter((r) => r.score > 0).sort((a, b) => b.score - a.score);
2596
+ const top = ranked.slice(0, 5);
2597
+ const lines = top.map((r) => `- ${this.label(r.p.s)} \u2014 ${r.p.s.tracker.status}${r.p.place?.branch ? `, on ${r.p.place.branch}` : ""} (score ${r.score.toFixed(1)}; matched ${r.why.join(", ")})
2598
+ "${r.snippet}"`);
2599
+ const sure = top.filter((r) => r.confident);
2600
+ if (!sure.length) {
2601
+ return `No tile clearly matches "${query}". Ask the user which tile, or offer a new one in its own worktree.` + (lines.length ? `
2602
+
2603
+ Only passing mentions:
2604
+ ${lines.join("\n")}` : "");
2605
+ }
2606
+ const close = sure.length > 1 && sure[1].score >= sure[0].score * 0.75;
2607
+ const verdict = close ? "Two or more tiles match about equally: ask the user which one before sending anything." : `Best match: ${this.label(sure[0].p.s)}. Confirm with session_history if unsure.`;
2608
+ return `${verdict}
2609
+
2610
+ ${lines.join("\n")}`;
2611
+ }
2612
+ readSession(s, lines) {
2613
+ const n = Math.max(1, Math.min(400, Math.floor(lines)));
2614
+ return `${this.label(s)} \u2014 ${s.tracker.status}, ${workdir(s)}
2615
+
2616
+ ${s.recentText(n) || "(nothing on screen)"}`;
2617
+ }
2618
+ async changes(s, file) {
2619
+ const r = await (this.d.diff ?? gitDiff)(workdir(s));
2620
+ if ("error" in r) return `${this.label(s)}: ${r.error}`;
2621
+ if (r.files.length === 0) return `${this.label(s)}: no uncommitted changes in ${r.cwd}`;
2622
+ const list = r.files.map((f) => `${f.path} +${f.added} -${f.removed}${f.note ? ` (${f.note})` : ""}`);
2623
+ const head2 = `${this.label(s)}: ${r.files.length} changed file(s) in ${r.cwd}${r.truncated ? " (patch truncated)" : ""}
2624
+ ${list.join("\n")}`;
2625
+ if (file) {
2626
+ const f = r.files.find((x) => x.path === file || x.path.endsWith(`/${file}`));
2627
+ if (!f) throw new ToolError(`${file} has no changes; changed: ${r.files.map((x) => x.path).join(", ")}`);
2628
+ return `${head2}
2629
+
2630
+ --- ${f.path}
2631
+ ${clip(f.patch || f.note || "", MAX_PATCH_CHARS * 2)}`;
2632
+ }
2633
+ let budget = MAX_PATCH_CHARS;
2634
+ const patches = [];
2635
+ for (const f of r.files) {
2636
+ if (!f.patch || budget <= 0) continue;
2637
+ const p = clip(f.patch, budget);
2638
+ budget -= p.length;
2639
+ patches.push(`--- ${f.path}
2640
+ ${p}`);
2641
+ }
2642
+ const rest = budget <= 0 ? "\n\n(more patches left out; ask for one file with `file`)" : "";
2643
+ return `${head2}
2644
+
2645
+ ${patches.join("\n\n")}${rest}`;
2646
+ }
2647
+ /** Why this tile cannot take a prompt now, or null when it can. */
2648
+ refusal(s) {
2649
+ if (s.tracker.status === "exited") return `${this.label(s)} has exited`;
2650
+ if (!s.claude) {
2651
+ return `${this.label(s)} is not running Claude Code (or tring's hooks are not installed, so it cannot tell). send_prompt only talks to agents; use create_session to start one.`;
2652
+ }
2653
+ const waiting = this.waiting(s);
2654
+ if (waiting.length) {
2655
+ return `${this.label(s)} is waiting on the user (${waiting.map(summary).join("; ")}). Ask the user to answer it in the inbox first; typing now would land in that dialog.`;
2656
+ }
2657
+ return null;
2658
+ }
2659
+ deliver(s, text2) {
2660
+ s.prompted();
2661
+ (this.d.type ?? typePrompt)(s, text2);
2662
+ }
2663
+ /** A warning for the agent when another agent is busy in the same worktree. */
2664
+ async crowding(s) {
2665
+ const placed = await this.placeAll();
2666
+ const me = placed.find((p) => p.s.id === s.id);
2667
+ const busy = me ? this.sharing(me, placed).filter((o) => o.s.claude && o.s.tracker.status === "busy") : [];
2668
+ if (!busy.length || !me?.place) return "";
2669
+ return ` Warning: ${busy.map((o) => o.ref).join(", ")} ${busy.length === 1 ? "is" : "are"} also working in ${me.place.root}; two agents in one worktree edit the same files. Prefer a worktree per task.`;
2670
+ }
2671
+ async sendPrompt(s, raw) {
2672
+ const text2 = cleanPrompt(raw);
2673
+ if (!text2) throw new ToolError("text is empty");
2674
+ const why = this.refusal(s);
2675
+ if (why) throw new ToolError(why);
2676
+ const busy = s.tracker.status === "busy";
2677
+ const warning = await this.crowding(s);
2678
+ this.deliver(s, text2);
2679
+ return `Sent to ${this.label(s)}${busy ? " (it was busy, so Claude Code queues it)" : ""}.${warning} Use wait_for with "${s.id}" for the answer.`;
2680
+ }
2681
+ /**
2682
+ * The worktree for `branch`: the one it is already checked out in, or a new
2683
+ * one. Returns the directory to start in, and what was done, in words.
2684
+ */
2685
+ async worktreeFor(repoDir, args) {
2686
+ const branch = str(args["branch"]);
2687
+ const git3 = this.git;
2688
+ const place = await git3.place(repoDir);
2689
+ if (!place) throw new ToolError(`${repoDir} is not inside a git repository, so there is no worktree to make`);
2690
+ const bad = await git3.checkBranch(repoDir, branch);
2691
+ if (bad) throw new ToolError(bad);
2692
+ const trees = await git3.worktrees(repoDir);
2693
+ const there = trees.find((w) => w.branch === branch && !w.prunable);
2694
+ if (there) {
2695
+ const inside2 = (await this.placeAll()).filter((p) => p.place && samePath(p.place.root, there.path) && p.s.tracker.status !== "exited");
2696
+ const crowd = inside2.length ? ` Warning: ${inside2.map((p) => p.ref).join(", ")} ${inside2.length === 1 ? "is" : "are"} already in that worktree; one agent per worktree, so make sure they are not both working, or use a new branch.` : "";
2697
+ return { dir: there.path, note: `Reused the existing worktree ${there.path}, which has ${branch} checked out.${crowd}` };
2698
+ }
2699
+ const base2 = str(args["base"]);
2700
+ if (base2?.startsWith("-")) throw new ToolError(`"${base2}" is not a usable base`);
2701
+ const exists = await git3.branchExists(repoDir, branch);
2702
+ const wanted = str(args["worktree_path"]);
2703
+ const dir = wanted ? path11.resolve(repoDir, wanted) : defaultWorktreePath(place.commonDir, trees, branch);
2704
+ if (await (this.d.isDir ?? isDirectory)(dir)) throw new ToolError(`${dir} already exists; pick another worktree_path`);
2705
+ const err = await git3.addWorktree(repoDir, { path: dir, branch, create: !exists, ...base2 && !exists ? { base: base2 } : {} });
2706
+ if (err) throw new ToolError(`git worktree add failed: ${err}`);
2707
+ const what = exists ? `checked out the existing branch ${branch}` : `created ${branch} from ${base2 ?? "the current HEAD"}`;
2708
+ return { dir, note: `Added the worktree ${dir} and ${what}.` };
2709
+ }
2710
+ async createSession(args, signal) {
2711
+ const projectRef = str(args["project"]);
2712
+ const project = projectRef ? this.d.pm.findProject(projectRef) : this.d.pm.list().find((p) => p.id === this.d.pm.activeProjectId) ?? this.d.pm.list()[0];
2713
+ if (!project) throw new ToolError(projectRef ? `no project ${projectRef}; see list_sessions` : "there are no projects yet");
2714
+ const cwdArg = str(args["cwd"]);
2715
+ let cwd = cwdArg ? path11.resolve(project.root, cwdArg) : project.root;
2716
+ if (!await (this.d.isDir ?? isDirectory)(cwd)) throw new ToolError(`${cwd} is not a directory`);
2717
+ const branch = str(args["branch"]);
2718
+ let note = "";
2719
+ if (branch) {
2720
+ const wt = await this.worktreeFor(cwd, args);
2721
+ cwd = wt.dir;
2722
+ note = ` ${wt.note}`;
2723
+ }
2724
+ let s;
2725
+ try {
2726
+ s = this.d.pm.create(project.id, { cwd, command: "claude", name: str(args["name"]) ?? branch ?? null });
2727
+ } catch (err) {
2728
+ throw new ToolError(`${err.message}.${note}`);
2729
+ }
2730
+ if (!s) throw new ToolError(`could not start a session.${note}`);
2731
+ const started = `Started ${this.label(s)} (id ${s.id}) running claude in ${cwd}.${note}`;
2732
+ const prompt = cleanPrompt(String(args["prompt"] ?? ""));
2733
+ if (!prompt) return started;
2734
+ const ready = await this.ready(s, signal);
2735
+ if (!ready) {
2736
+ return `${started} The first prompt was NOT sent: Claude Code did not report it was ready within ${READY_TIMEOUT_MS / 1e3}s (are tring's hooks installed? is the folder trusted?). Check with read_session, then use send_prompt.`;
2737
+ }
2738
+ this.deliver(s, prompt);
2739
+ return `${started} First prompt sent. Use wait_for with "${s.id}" for the answer.`;
2740
+ }
2741
+ /** Claude has started (SessionStart hook) and drawn its prompt. */
2742
+ async ready(s, signal) {
2743
+ const until = this.now + READY_TIMEOUT_MS;
2744
+ let since = null;
2745
+ while (this.now < until && !signal?.aborted) {
2746
+ if (s.tracker.status === "exited") return false;
2747
+ if (s.claude && s.tracker.status !== "busy") {
2748
+ since ??= this.now;
2749
+ if (this.now - since >= READY_SETTLE_MS) return true;
2750
+ } else {
2751
+ since = null;
2752
+ }
2753
+ await this.sleep(250);
2754
+ }
2755
+ return false;
2756
+ }
2757
+ async waitFor(args, signal) {
2758
+ const refs = Array.isArray(args["sessions"]) ? args["sessions"] : [args["sessions"]];
2759
+ const sessions = refs.map((r) => this.resolve(r));
2760
+ const timeout = Math.max(5, Math.min(900, num(args["timeout_seconds"]) ?? 300)) * 1e3;
2761
+ const until = this.now + timeout;
2762
+ while (!signal?.aborted) {
2763
+ if (sessions.every((s) => this.state(s) !== "working") || this.now >= until) break;
2764
+ await this.sleep(1e3);
2765
+ }
2766
+ const timedOut = sessions.some((s) => this.state(s) === "working");
2767
+ const lines = sessions.map((s) => {
2768
+ const st = this.state(s);
2769
+ const waiting = this.waiting(s);
2770
+ const said = s.lastMessage && s.stoppedAt >= s.promptedAt ? `
2771
+ ${clip(s.lastMessage, 4e3)}` : "";
2772
+ const why = st === "needs-user" ? ` \u2014 waiting on the user: ${waiting.map(summary).join("; ")}` : "";
2773
+ return `## ${this.label(s)} \u2014 ${st === "working" ? "still working" : st}${why}${said}`;
2774
+ });
2775
+ return (timedOut ? `Timed out after ${timeout / 1e3}s.
2776
+
2777
+ ` : "") + lines.join("\n\n");
2778
+ }
2779
+ state(s) {
2780
+ if (s.tracker.status === "exited") return "exited";
2781
+ if (this.waiting(s).length) return "needs-user";
2782
+ if (s.tracker.status === "busy") return "working";
2783
+ if (s.promptedAt > s.stoppedAt && this.now - s.promptedAt < PROMPT_GRACE_MS) return "working";
2784
+ return "finished";
2785
+ }
2786
+ };
2787
+ function conversationSummary(t) {
2788
+ if (!t) return {};
2789
+ const prompts = t.turns.filter((x) => x.role === "user").map((x) => clip(x.text.replace(/\s+/g, " "), 200));
2790
+ if (!t.title && !prompts.length) return {};
2791
+ return {
2792
+ conversation: {
2793
+ ...t.title ? { title: t.title } : {},
2794
+ ...prompts.length ? { firstPrompt: prompts[0] } : {},
2795
+ ...prompts.length > 1 ? { recentPrompts: prompts.slice(-3) } : {}
2796
+ }
2797
+ };
2798
+ }
2799
+ var STRONG = /* @__PURE__ */ new Set(["name", "branch", "title", "prompt", "edited"]);
2800
+ var STOP = /* @__PURE__ */ new Set([
2801
+ "the",
2802
+ "and",
2803
+ "for",
2804
+ "with",
2805
+ "that",
2806
+ "this",
2807
+ "from",
2808
+ "into",
2809
+ "onto",
2810
+ "then",
2811
+ "than",
2812
+ "please",
2813
+ "can",
2814
+ "could",
2815
+ "would",
2816
+ "should",
2817
+ "you",
2818
+ "your",
2819
+ "our",
2820
+ "its",
2821
+ "are",
2822
+ "was",
2823
+ "were",
2824
+ "has",
2825
+ "have",
2826
+ "had",
2827
+ "not",
2828
+ "but",
2829
+ "all",
2830
+ "any",
2831
+ "some",
2832
+ "one",
2833
+ "out",
2834
+ "make",
2835
+ "change",
2836
+ "update",
2837
+ "fix",
2838
+ "add",
2839
+ "set",
2840
+ "get",
2841
+ "put",
2842
+ "use",
2843
+ "now",
2844
+ "also",
2845
+ "just",
2846
+ "like",
2847
+ "want",
2848
+ "need",
2849
+ "tile",
2850
+ "terminal",
2851
+ "session",
2852
+ "agent",
2853
+ "work",
2854
+ "working",
2855
+ "thing",
2856
+ "there"
2857
+ ]);
2858
+ function words(query) {
2859
+ const out = query.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 3 && !STOP.has(w)).map((w) => w.length > 5 ? w.replace(/(ing|ed|es|s)$/, "") : w);
2860
+ return [...new Set(out)];
2861
+ }
2862
+ function turnText(t) {
2863
+ return `${t.text} ${t.files?.join(" ") ?? ""}`;
2864
+ }
2865
+ function snippet(text2, word) {
2866
+ const flat = text2.replace(/\s+/g, " ");
2867
+ const i = flat.toLowerCase().indexOf(word);
2868
+ const from = Math.max(0, i - 60);
2869
+ return `${from > 0 ? "\u2026" : ""}${flat.slice(from, from + 160)}${from + 160 < flat.length ? "\u2026" : ""}`;
2870
+ }
2871
+ function gitSummary(p) {
2872
+ return {
2873
+ repo: repoName(p.commonDir),
2874
+ branch: p.branch ?? (p.detached ? "(detached)" : null),
2875
+ worktree: p.root,
2876
+ linkedWorktree: p.linked
2877
+ };
2878
+ }
2879
+ function summary(i) {
2880
+ if (i.kind === "question") return `question: ${clip(i.questions?.map((q) => q.question).join(" / ") ?? "", 200)}`;
2881
+ const input = i.input ?? {};
2882
+ const what = String(input["command"] ?? input["file_path"] ?? input["url"] ?? "");
2883
+ return `permission for ${i.tool ?? "a tool"}${what ? `: ${clip(what, 200)}` : ""}`;
2884
+ }
2885
+ var str = (v) => typeof v === "string" && v.trim() ? v.trim() : void 0;
2886
+ var num = (v) => {
2887
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
2888
+ return Number.isFinite(n) ? n : void 0;
2889
+ };
2890
+
1833
2891
  // src/http.ts
1834
2892
  var MIME = {
1835
2893
  ".html": "text/html; charset=utf-8",
@@ -1902,14 +2960,14 @@ function createHandler(opts) {
1902
2960
  let usage = null;
1903
2961
  const homeDir = () => process.env["HOME"] ?? os5.homedir();
1904
2962
  const within = (root, dir) => {
1905
- const rel = path8.relative(path8.resolve(root), dir);
1906
- return rel === "" || !rel.startsWith("..") && !path8.isAbsolute(rel);
2963
+ const rel = path12.relative(path12.resolve(root), dir);
2964
+ return rel === "" || !rel.startsWith("..") && !path12.isAbsolute(rel);
1907
2965
  };
1908
2966
  const real = async (p) => {
1909
2967
  try {
1910
2968
  return await realpath(p);
1911
2969
  } catch {
1912
- return path8.resolve(p);
2970
+ return path12.resolve(p);
1913
2971
  }
1914
2972
  };
1915
2973
  const browsable = async (dir) => {
@@ -1938,8 +2996,10 @@ function createHandler(opts) {
1938
2996
  }
1939
2997
  const hook = url.pathname.match(/^\/api\/sessions\/([^/]+)\/hook$/);
1940
2998
  if (hook && req.method === "POST") {
1941
- const s = pm.findSession(decodeURIComponent(hook[1]));
1942
- if (!s) return json(res, 404, { error: "no such session" });
2999
+ const id = decodeURIComponent(hook[1]);
3000
+ const agent = opts.agentSession?.(id);
3001
+ const s = pm.findSession(id);
3002
+ if (!s && !agent) return json(res, 404, { error: "no such session" });
1943
3003
  const raw = await readBody(req);
1944
3004
  if (raw === null) return tooLarge(req, res, "body too large");
1945
3005
  let body;
@@ -1950,6 +3010,12 @@ function createHandler(opts) {
1950
3010
  }
1951
3011
  if (typeof body.event !== "string") return json(res, 400, { error: "event is required" });
1952
3012
  const payload = body.payload && typeof body.payload === "object" ? body.payload : {};
3013
+ if (agent) {
3014
+ const conv = body.event === "SessionStart" ? claudeConversation({ id: payload.session_id, cwd: payload.cwd }) : null;
3015
+ if (conv) agent.setClaude(conv);
3016
+ return json(res, 200, { output: null });
3017
+ }
3018
+ if (!s) return json(res, 404, { error: "no such session" });
1953
3019
  if (!opts.inbox) {
1954
3020
  if (body.event === "Stop" || body.event === "Notification") s.hook();
1955
3021
  return json(res, 200, { output: null });
@@ -1969,6 +3035,36 @@ function createHandler(opts) {
1969
3035
  if (gone.signal.aborted) return;
1970
3036
  return json(res, 200, { output });
1971
3037
  }
3038
+ if (url.pathname === "/api/orchestrator/tools" && req.method === "GET") {
3039
+ return json(res, 200, { tools: TOOLS });
3040
+ }
3041
+ if (url.pathname === "/api/orchestrator/call" && req.method === "POST") {
3042
+ const tools = opts.tools;
3043
+ if (!tools) return json(res, 503, { error: "the orchestrator agent is not available" });
3044
+ const raw = await readBody(req);
3045
+ if (raw === null) return tooLarge(req, res, "body too large");
3046
+ let body;
3047
+ try {
3048
+ body = JSON.parse(raw || "{}");
3049
+ } catch {
3050
+ return json(res, 400, { error: "malformed body" });
3051
+ }
3052
+ if (typeof body.name !== "string") return json(res, 400, { error: "name is required" });
3053
+ const args = body.arguments && typeof body.arguments === "object" ? body.arguments : {};
3054
+ const gone = new AbortController();
3055
+ res.on("close", () => {
3056
+ if (!res.writableFinished) gone.abort();
3057
+ });
3058
+ try {
3059
+ const text2 = await tools.call(body.name, args, gone.signal);
3060
+ if (gone.signal.aborted) return;
3061
+ return json(res, 200, { text: text2, isError: false });
3062
+ } catch (err) {
3063
+ if (gone.signal.aborted) return;
3064
+ if (err instanceof ToolError) return json(res, 200, { text: err.message, isError: true });
3065
+ return json(res, 200, { text: `tring could not do that: ${err.message}`, isError: true });
3066
+ }
3067
+ }
1972
3068
  if (url.pathname === "/api/hooks" && req.method === "GET") {
1973
3069
  return json(res, 200, await hooksStatus(opts.claudeSettingsPath));
1974
3070
  }
@@ -2005,12 +3101,12 @@ function createHandler(opts) {
2005
3101
  }
2006
3102
  if (url.pathname === "/api/fs" && req.method === "GET") {
2007
3103
  const raw = url.searchParams.get("path")?.trim();
2008
- const dir = raw ? path8.resolve(raw) : homeDir();
3104
+ const dir = raw ? path12.resolve(raw) : homeDir();
2009
3105
  if (!await browsable(dir)) return json(res, 403, { error: "outside the browsable roots" });
2010
3106
  try {
2011
- const found = await readdir3(dir, { withFileTypes: true });
2012
- const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path8.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
2013
- const parent = path8.dirname(dir);
3107
+ const found = await readdir4(dir, { withFileTypes: true });
3108
+ const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path12.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
3109
+ const parent = path12.dirname(dir);
2014
3110
  const up = parent !== dir && await browsable(parent) ? parent : null;
2015
3111
  return json(res, 200, { path: dir, parent: up, entries });
2016
3112
  } catch {
@@ -2057,15 +3153,15 @@ function createHandler(opts) {
2057
3153
  }
2058
3154
  async function serveStatic(res, pathname) {
2059
3155
  const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
2060
- const file = path8.resolve(webRoot, rel);
2061
- if (file !== webRoot && !file.startsWith(webRoot + path8.sep)) {
3156
+ const file = path12.resolve(webRoot, rel);
3157
+ if (file !== webRoot && !file.startsWith(webRoot + path12.sep)) {
2062
3158
  text(res, 403, "forbidden");
2063
3159
  return;
2064
3160
  }
2065
3161
  try {
2066
- const info = await stat3(file);
3162
+ const info = await stat5(file);
2067
3163
  if (!info.isFile()) throw new Error("not a file");
2068
- head(res, 200, MIME[path8.extname(file)] ?? "application/octet-stream");
3164
+ head(res, 200, MIME[path12.extname(file)] ?? "application/octet-stream");
2069
3165
  createReadStream(file).pipe(res);
2070
3166
  } catch {
2071
3167
  if (rel === "index.html") {
@@ -2079,7 +3175,6 @@ function createHandler(opts) {
2079
3175
  }
2080
3176
 
2081
3177
  // src/ws.ts
2082
- var PASTE_SETTLE_MS = 60;
2083
3178
  var Hub = class {
2084
3179
  constructor(opts) {
2085
3180
  this.opts = opts;
@@ -2098,12 +3193,17 @@ var Hub = class {
2098
3193
  };
2099
3194
  if (opts.inbox) opts.inbox.onChange = () => this.broadcastInbox();
2100
3195
  if (opts.auto) opts.auto.onChange = () => this.broadcastAuto();
2101
- pm.onSessionData = (s, data) => {
3196
+ const output = (s, data) => {
2102
3197
  const frame = encodeOutput(s.id, Buffer.from(data, "utf8"));
2103
3198
  for (const c of this.clients) {
2104
3199
  if (c.authed && c.focusedId === s.id) c.ws.send(frame, { binary: true });
2105
3200
  }
2106
3201
  };
3202
+ pm.onSessionData = output;
3203
+ if (opts.agent) {
3204
+ opts.agent.onData = output;
3205
+ opts.agent.onChange = () => this.broadcastAgent();
3206
+ }
2107
3207
  this.timer = setInterval(() => this.pumpSnapshots(), opts.snapshotMs ?? 250);
2108
3208
  this.timer.unref?.();
2109
3209
  }
@@ -2155,6 +3255,7 @@ var Hub = class {
2155
3255
  this.sendSnapshots(c);
2156
3256
  if (this.opts.inbox) this.send(c, { type: "inbox", items: this.opts.inbox.list() });
2157
3257
  if (this.opts.auto) this.send(c, this.autoMessage(this.opts.auto));
3258
+ if (this.opts.agent) this.send(c, { type: "agent", agent: this.opts.agent.info() });
2158
3259
  return;
2159
3260
  }
2160
3261
  if (!c.authed) return this.send(c, { type: "error", message: "expected hello" });
@@ -2193,18 +3294,25 @@ var Hub = class {
2193
3294
  case "focus": {
2194
3295
  c.focusedId = msg.id;
2195
3296
  if (!msg.id) break;
2196
- const s = pm.findSession(msg.id);
3297
+ const s = this.find(msg.id);
2197
3298
  if (!s) break;
2198
3299
  s.resize(msg.cols, msg.rows);
2199
3300
  this.send(c, { type: "screen", id: s.id, ansi: s.serialize() });
2200
3301
  break;
2201
3302
  }
2202
3303
  case "input": {
2203
- pm.findSession(msg.id)?.write(msg.data);
3304
+ this.find(msg.id)?.write(msg.data);
2204
3305
  break;
2205
3306
  }
2206
3307
  case "resize": {
2207
- if (c.focusedId) pm.findSession(c.focusedId)?.resize(msg.cols, msg.rows);
3308
+ if (c.focusedId) this.find(c.focusedId)?.resize(msg.cols, msg.rows);
3309
+ break;
3310
+ }
3311
+ case "agent": {
3312
+ const agent = this.opts.agent;
3313
+ if (!agent) break;
3314
+ if (typeof msg.enabled === "boolean") void agent.setEnabled(msg.enabled);
3315
+ else if (msg.restart === "resume" || msg.restart === "fresh") void agent.restart(msg.restart === "fresh");
2208
3316
  break;
2209
3317
  }
2210
3318
  case "kill":
@@ -2246,11 +3354,10 @@ var Hub = class {
2246
3354
  const item = inbox?.get(msg.itemId);
2247
3355
  if (!inbox || !item || item.kind !== "reply") break;
2248
3356
  const s = pm.findSession(item.sessionId);
2249
- const text2 = String(msg.text ?? "").replace(/\x1b\[20[01]~/g, "").trimEnd();
3357
+ const text2 = cleanPrompt(msg.text);
2250
3358
  if (!s || s.tracker.status === "busy" || s.tracker.status === "exited" || !text2) break;
2251
3359
  inbox.answer(item.id, { decision: "allow" });
2252
- s.write(`\x1B[200~${text2}\x1B[201~`);
2253
- setTimeout(() => s.write("\r"), PASTE_SETTLE_MS).unref?.();
3360
+ typePrompt(s, text2);
2254
3361
  break;
2255
3362
  }
2256
3363
  }
@@ -2310,6 +3417,13 @@ var Hub = class {
2310
3417
  broadcastAuto() {
2311
3418
  if (this.opts.auto) this.broadcast(this.autoMessage(this.opts.auto));
2312
3419
  }
3420
+ /** A tile, or the orchestrator agent's own terminal. */
3421
+ find(id) {
3422
+ return this.opts.pm.findSession(id) ?? this.opts.agent?.find(id);
3423
+ }
3424
+ broadcastAgent() {
3425
+ if (this.opts.agent) this.broadcast({ type: "agent", agent: this.opts.agent.info() });
3426
+ }
2313
3427
  broadcastInbox() {
2314
3428
  if (this.opts.inbox) this.broadcast({ type: "inbox", items: this.opts.inbox.list() });
2315
3429
  }
@@ -2459,25 +3573,25 @@ import {
2459
3573
  readdirSync
2460
3574
  } from "node:fs";
2461
3575
  import { createRequire as createRequire4 } from "node:module";
2462
- import path9 from "node:path";
3576
+ import path13 from "node:path";
2463
3577
  var EXEC = 73;
2464
3578
  function nodePtyRoot() {
2465
3579
  try {
2466
- return path9.dirname(createRequire4(import.meta.url).resolve("node-pty/package.json"));
3580
+ return path13.dirname(createRequire4(import.meta.url).resolve("node-pty/package.json"));
2467
3581
  } catch {
2468
3582
  return null;
2469
3583
  }
2470
3584
  }
2471
3585
  function spawnHelperPaths(root) {
2472
- const found = [path9.join(root, "build", "Release", "spawn-helper")];
3586
+ const found = [path13.join(root, "build", "Release", "spawn-helper")];
2473
3587
  let prebuilds;
2474
3588
  try {
2475
- prebuilds = readdirSync(path9.join(root, "prebuilds"), { withFileTypes: true });
3589
+ prebuilds = readdirSync(path13.join(root, "prebuilds"), { withFileTypes: true });
2476
3590
  } catch {
2477
3591
  return found;
2478
3592
  }
2479
3593
  for (const entry of prebuilds) {
2480
- if (entry.isDirectory()) found.push(path9.join(root, "prebuilds", entry.name, "spawn-helper"));
3594
+ if (entry.isDirectory()) found.push(path13.join(root, "prebuilds", entry.name, "spawn-helper"));
2481
3595
  }
2482
3596
  return found;
2483
3597
  }
@@ -2506,7 +3620,7 @@ function fixSpawnHelper(root = nodePtyRoot()) {
2506
3620
  import { spawn as spawn4 } from "node:child_process";
2507
3621
  import { mkdir as mkdir5, readFile as readFile6, writeFile as writeFile5 } from "node:fs/promises";
2508
3622
  import os7 from "node:os";
2509
- import path10 from "node:path";
3623
+ import path14 from "node:path";
2510
3624
  var BASH_ALWAYS_ASK = [
2511
3625
  /\brm\s+(-[a-zA-Z]*[rRf]|--recursive|--force)/,
2512
3626
  /\bsudo\b|\bdoas\b|\bsu\s/,
@@ -2530,8 +3644,8 @@ var BASH_ALWAYS_ASK = [
2530
3644
  var PATH_ALWAYS_ASK = /(^|\/)(\.env[^/]*|\.git\/|\.ssh\/|\.aws\/|id_rsa|id_ed25519|credentials[^/]*|\.npmrc|\.netrc|secrets?\.[a-z]+)$|(^|\/)\.git\//;
2531
3645
  var FILE_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
2532
3646
  var inside = (cwd, p) => {
2533
- const rel = path10.relative(path10.resolve(cwd), path10.resolve(cwd, p));
2534
- return rel === "" || !rel.startsWith("..") && !path10.isAbsolute(rel);
3647
+ const rel = path14.relative(path14.resolve(cwd), path14.resolve(cwd, p));
3648
+ return rel === "" || !rel.startsWith("..") && !path14.isAbsolute(rel);
2535
3649
  };
2536
3650
  function rule(item, cwd) {
2537
3651
  if (item.kind !== "permission") return { verdict: "ask", reason: "only permission prompts are auto-answered" };
@@ -2544,7 +3658,7 @@ function rule(item, cwd) {
2544
3658
  const p = String(input["file_path"] ?? input["notebook_path"] ?? "");
2545
3659
  if (!p) return { verdict: "ask", reason: "no file path given" };
2546
3660
  if (!inside(cwd, p)) return { verdict: "ask", reason: "outside the session directory" };
2547
- if (PATH_ALWAYS_ASK.test(path10.resolve(cwd, p))) return { verdict: "ask", reason: "a secrets or git file" };
3661
+ if (PATH_ALWAYS_ASK.test(path14.resolve(cwd, p))) return { verdict: "ask", reason: "a secrets or git file" };
2548
3662
  return { verdict: "classify" };
2549
3663
  }
2550
3664
  if (tool === "Bash") {
@@ -2665,7 +3779,7 @@ var AutoAnswerer = class {
2665
3779
  this.on = on;
2666
3780
  this.onChange?.();
2667
3781
  if (!this.opts.statePath) return;
2668
- await mkdir5(path10.dirname(this.opts.statePath), { recursive: true });
3782
+ await mkdir5(path14.dirname(this.opts.statePath), { recursive: true });
2669
3783
  await writeFile5(this.opts.statePath, JSON.stringify({ autoAnswer: on }, null, 2) + "\n", "utf8");
2670
3784
  }
2671
3785
  /**
@@ -2711,22 +3825,391 @@ var AutoAnswerer = class {
2711
3825
 
2712
3826
  // src/hook-shim.ts
2713
3827
  import { chmod, mkdir as mkdir6, writeFile as writeFile6 } from "node:fs/promises";
2714
- import path11 from "node:path";
3828
+ import path15 from "node:path";
2715
3829
  async function writeHookShim(dir, node, script) {
2716
3830
  await mkdir6(dir, { recursive: true });
2717
3831
  const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
2718
- await writeFile6(path11.join(dir, "tring-hook"), `#!/bin/sh
3832
+ await writeFile6(path15.join(dir, "tring-hook"), `#!/bin/sh
2719
3833
  exec ${q(node)} ${q(script)} "$@"
2720
3834
  `, "utf8");
2721
- await chmod(path11.join(dir, "tring-hook"), 493);
2722
- await writeFile6(path11.join(dir, "tring-hook.cmd"), `@"${node}" "${script}" %*\r
3835
+ await chmod(path15.join(dir, "tring-hook"), 493);
3836
+ await writeFile6(path15.join(dir, "tring-hook.cmd"), `@"${node}" "${script}" %*\r
2723
3837
  `, "utf8");
2724
3838
  }
2725
3839
  function prependPath(current, dir) {
2726
- const parts = (current ?? "").split(path11.delimiter).filter((p) => p && p !== dir);
2727
- return [dir, ...parts].join(path11.delimiter);
3840
+ const parts = (current ?? "").split(path15.delimiter).filter((p) => p && p !== dir);
3841
+ return [dir, ...parts].join(path15.delimiter);
2728
3842
  }
2729
3843
 
3844
+ // src/autostart.ts
3845
+ import { execFile as execFile3 } from "node:child_process";
3846
+ import { mkdir as mkdir7, readFile as readFile7, rename as rename2, rm as rm2, writeFile as writeFile7 } from "node:fs/promises";
3847
+ import os8 from "node:os";
3848
+ import path16 from "node:path";
3849
+ var MARKER = "written by tring autostart";
3850
+ var LABEL = "chat.tring.daemon";
3851
+ function autostartFile(e) {
3852
+ if (e.platform === "darwin") return path16.join(e.home, "Library", "LaunchAgents", `${LABEL}.plist`);
3853
+ if (e.platform === "win32") {
3854
+ const appData = e.env["APPDATA"] ?? path16.join(e.home, "AppData", "Roaming");
3855
+ return path16.win32.join(appData, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "tring.cmd");
3856
+ }
3857
+ const config = e.env["XDG_CONFIG_HOME"] ?? path16.join(e.home, ".config");
3858
+ return path16.join(config, "systemd", "user", "tring.service");
3859
+ }
3860
+ var sdQuote = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
3861
+ var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
3862
+ var cmdQuote = (s) => {
3863
+ if (/["%\r\n]/.test(s)) throw new Error(`cannot put ${JSON.stringify(s)} in a .cmd file`);
3864
+ return `"${s}"`;
3865
+ };
3866
+ function autostartContent(e, flags) {
3867
+ const argv = [e.node, e.script, "--no-open", ...flags];
3868
+ const PATH = e.env["PATH"] ?? "";
3869
+ if (e.platform === "darwin") {
3870
+ return `<?xml version="1.0" encoding="UTF-8"?>
3871
+ <!-- ${MARKER} -->
3872
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3873
+ <plist version="1.0">
3874
+ <dict>
3875
+ <key>Label</key><string>${LABEL}</string>
3876
+ <key>ProgramArguments</key>
3877
+ <array>
3878
+ ${argv.map((a) => ` <string>${xml(a)}</string>`).join("\n")}
3879
+ </array>
3880
+ <key>EnvironmentVariables</key>
3881
+ <dict><key>PATH</key><string>${xml(PATH)}</string></dict>
3882
+ <key>WorkingDirectory</key><string>${xml(e.home)}</string>
3883
+ <key>RunAtLoad</key><true/>
3884
+ <key>KeepAlive</key><true/>
3885
+ </dict>
3886
+ </plist>
3887
+ `;
3888
+ }
3889
+ if (e.platform === "win32") {
3890
+ return [
3891
+ "@echo off",
3892
+ `rem ${MARKER}`,
3893
+ `set ${cmdQuote(`PATH=${PATH}`)}`,
3894
+ `cd /d ${cmdQuote(e.home)}`,
3895
+ `start "tring" /min ${argv.map(cmdQuote).join(" ")}`,
3896
+ ""
3897
+ ].join("\r\n");
3898
+ }
3899
+ return `# ${MARKER}
3900
+ [Unit]
3901
+ Description=tring terminal deck daemon
3902
+ After=graphical-session.target
3903
+
3904
+ [Service]
3905
+ Type=simple
3906
+ Environment=${sdQuote(`PATH=${PATH}`)}
3907
+ WorkingDirectory=${e.home}
3908
+ ExecStart=${argv.map(sdQuote).join(" ")}
3909
+ Restart=always
3910
+ RestartSec=2
3911
+
3912
+ [Install]
3913
+ WantedBy=default.target
3914
+ `;
3915
+ }
3916
+ var defaultRun = (cmd, args) => new Promise((resolve) => execFile3(cmd, args, (err) => resolve(!err)));
3917
+ async function autostartStatus(e) {
3918
+ const file = autostartFile(e);
3919
+ try {
3920
+ const text2 = await readFile7(file, "utf8");
3921
+ return { file, present: true, ours: text2.includes(MARKER) };
3922
+ } catch {
3923
+ return { file, present: false, ours: false };
3924
+ }
3925
+ }
3926
+ var ForeignAutostart = class extends Error {
3927
+ };
3928
+ async function autostartOn(e, flags = []) {
3929
+ const st = await autostartStatus(e);
3930
+ if (st.present && !st.ours) {
3931
+ throw new ForeignAutostart(`${st.file} already exists and tring did not write it, so it was left alone.
3932
+ If it already starts tring at login there is nothing to do; otherwise move it aside and run this again.`);
3933
+ }
3934
+ await mkdir7(path16.dirname(st.file), { recursive: true });
3935
+ const tmp = `${st.file}.tring-${process.pid}`;
3936
+ await writeFile7(tmp, autostartContent(e, flags), "utf8");
3937
+ await rename2(tmp, st.file);
3938
+ const run3 = e.run ?? defaultRun;
3939
+ if (e.platform === "linux") {
3940
+ await run3("systemctl", ["--user", "daemon-reload"]);
3941
+ if (!await run3("systemctl", ["--user", "enable", "tring.service"])) {
3942
+ throw new Error(`wrote ${st.file}, but systemctl --user enable tring.service failed`);
3943
+ }
3944
+ }
3945
+ return { ...st, present: true, ours: true };
3946
+ }
3947
+ async function autostartOff(e) {
3948
+ const st = await autostartStatus(e);
3949
+ if (!st.present) return false;
3950
+ if (!st.ours) throw new ForeignAutostart(`${st.file} was not written by tring, so it was left alone.`);
3951
+ const run3 = e.run ?? defaultRun;
3952
+ if (e.platform === "linux") await run3("systemctl", ["--user", "disable", "tring.service"]);
3953
+ if (e.platform === "darwin") await run3("launchctl", ["bootout", `gui/${os8.userInfo().uid}/${LABEL}`]);
3954
+ await rm2(st.file, { force: true });
3955
+ if (e.platform === "linux") await run3("systemctl", ["--user", "daemon-reload"]);
3956
+ return true;
3957
+ }
3958
+
3959
+ // src/orchestrator-agent.ts
3960
+ import { randomUUID as randomUUID4 } from "node:crypto";
3961
+ import { chmod as chmod2, mkdir as mkdir8, readFile as readFile8, writeFile as writeFile8, access } from "node:fs/promises";
3962
+ import path17 from "node:path";
3963
+ var PRE_ALLOWED = ["list_sessions", "list_worktrees", "find_work", "session_history", "read_session", "session_changes", "send_prompt", "wait_for"].map((t) => `mcp__tring__${t}`);
3964
+ var RESUME_FAIL_MS = 1e4;
3965
+ var OrchestratorAgent = class {
3966
+ constructor(opts) {
3967
+ this.opts = opts;
3968
+ }
3969
+ on = false;
3970
+ conversation = null;
3971
+ current = null;
3972
+ startedAt = 0;
3973
+ error = null;
3974
+ timer = null;
3975
+ onChange = null;
3976
+ onData = null;
3977
+ get enabled() {
3978
+ return this.on;
3979
+ }
3980
+ get session() {
3981
+ return this.current;
3982
+ }
3983
+ /** The agent's session, if `id` is it. */
3984
+ find(id) {
3985
+ return this.current && this.current.id === id ? this.current : void 0;
3986
+ }
3987
+ info() {
3988
+ return {
3989
+ enabled: this.on,
3990
+ id: this.current?.id ?? null,
3991
+ status: this.current?.tracker.status ?? null,
3992
+ error: this.error
3993
+ };
3994
+ }
3995
+ async load() {
3996
+ try {
3997
+ const raw = JSON.parse(await readFile8(this.opts.statePath, "utf8"));
3998
+ this.on = raw.enabled === true;
3999
+ this.conversation = claudeConversation(raw.claude);
4000
+ } catch {
4001
+ this.on = false;
4002
+ }
4003
+ if (this.on) await this.start();
4004
+ }
4005
+ async setEnabled(on) {
4006
+ if (on === this.on) return;
4007
+ this.on = on;
4008
+ if (on) await this.start();
4009
+ else this.stop();
4010
+ await this.save();
4011
+ this.onChange?.();
4012
+ }
4013
+ /** A fresh conversation, or the same one again after Claude was quit. */
4014
+ async restart(fresh) {
4015
+ if (!this.on) return;
4016
+ if (fresh) this.conversation = null;
4017
+ this.stop();
4018
+ await this.start();
4019
+ await this.save();
4020
+ this.onChange?.();
4021
+ }
4022
+ dispose() {
4023
+ this.stop();
4024
+ }
4025
+ stop() {
4026
+ if (this.timer) clearInterval(this.timer);
4027
+ this.timer = null;
4028
+ this.current?.dispose();
4029
+ this.current = null;
4030
+ }
4031
+ async start() {
4032
+ if (this.current) return;
4033
+ this.error = null;
4034
+ if (!this.opts.mcpScript) {
4035
+ this.error = "the tring MCP relay is missing from this install, so the agent would have no tools";
4036
+ this.onChange?.();
4037
+ return;
4038
+ }
4039
+ try {
4040
+ await this.writeWorkspace();
4041
+ } catch (err) {
4042
+ this.error = `cannot write ${this.opts.dir}: ${err.message}`;
4043
+ this.onChange?.();
4044
+ return;
4045
+ }
4046
+ const resume = this.conversation ? ` --resume ${this.conversation.id}` : "";
4047
+ const command = `claude --mcp-config tring-mcp.json${resume}`;
4048
+ const s = (this.opts.spawn ?? ((o) => new Session(o)))({
4049
+ id: randomUUID4(),
4050
+ projectId: "",
4051
+ projectName: "orchestrator",
4052
+ slot: 0,
4053
+ cwd: this.opts.dir,
4054
+ command,
4055
+ name: "Orchestrator",
4056
+ url: this.opts.url,
4057
+ token: this.opts.token,
4058
+ scrollback: this.opts.scrollback,
4059
+ idleMs: this.opts.idleMs,
4060
+ ...this.opts.shell ? { shell: this.opts.shell } : {},
4061
+ autorun: true
4062
+ });
4063
+ this.current = s;
4064
+ this.startedAt = Date.now();
4065
+ this.timer = setInterval(() => s.tick(Date.now()), 500);
4066
+ this.timer.unref?.();
4067
+ s.onData = (data) => this.onData?.(s, data);
4068
+ s.onStatusChange = () => this.onChange?.();
4069
+ s.onClaudeChange = () => {
4070
+ if (s.claude) this.conversation = s.claude;
4071
+ void this.save();
4072
+ };
4073
+ s.onExit = () => {
4074
+ if (resume && Date.now() - this.startedAt < RESUME_FAIL_MS && this.current === s) {
4075
+ this.conversation = null;
4076
+ this.stop();
4077
+ void this.start().then(() => this.save()).then(() => this.onChange?.());
4078
+ return;
4079
+ }
4080
+ this.onChange?.();
4081
+ };
4082
+ this.onChange?.();
4083
+ }
4084
+ async save() {
4085
+ try {
4086
+ await mkdir8(path17.dirname(this.opts.statePath), { recursive: true });
4087
+ const saved = { enabled: this.on, claude: this.conversation };
4088
+ await writeFile8(this.opts.statePath, JSON.stringify(saved, null, 2) + "\n", "utf8");
4089
+ } catch {
4090
+ }
4091
+ }
4092
+ /**
4093
+ * Rewritten on every start, so an upgrade brings new instructions and a
4094
+ * moved Node with it. CLAUDE.md is the user's: written once, and it only
4095
+ * imports TRING.md, so anything they add there survives.
4096
+ */
4097
+ async writeWorkspace() {
4098
+ const dir = this.opts.dir;
4099
+ await mkdir8(path17.join(dir, ".claude"), { recursive: true });
4100
+ const tokenFile = path17.join(dir, ".token");
4101
+ if (this.opts.token) {
4102
+ await writeFile8(tokenFile, `${this.opts.token}
4103
+ `, { mode: 384 });
4104
+ await chmod2(tokenFile, 384).catch(() => {
4105
+ });
4106
+ }
4107
+ const script = this.opts.mcpScript;
4108
+ const nodeArgs = script.endsWith(".ts") ? ["--experimental-strip-types", "--no-warnings"] : [];
4109
+ const mcp = {
4110
+ mcpServers: {
4111
+ tring: {
4112
+ type: "stdio",
4113
+ command: this.opts.node,
4114
+ args: [...nodeArgs, script, "--url", this.opts.url, ...this.opts.token ? ["--token-file", tokenFile] : []]
4115
+ }
4116
+ }
4117
+ };
4118
+ await writeFile8(path17.join(dir, "tring-mcp.json"), JSON.stringify(mcp, null, 2) + "\n", "utf8");
4119
+ await writeFile8(path17.join(dir, ".claude", "settings.json"), JSON.stringify({
4120
+ permissions: { allow: PRE_ALLOWED }
4121
+ }, null, 2) + "\n", "utf8");
4122
+ await writeFile8(path17.join(dir, "TRING.md"), INSTRUCTIONS, "utf8");
4123
+ const claudeMd = path17.join(dir, "CLAUDE.md");
4124
+ try {
4125
+ await access(claudeMd);
4126
+ } catch {
4127
+ await writeFile8(claudeMd, "@TRING.md\n\n# Your own instructions for the orchestrator go below.\n", "utf8");
4128
+ }
4129
+ }
4130
+ };
4131
+ var INSTRUCTIONS = `# You are the tring orchestrator
4132
+
4133
+ The user runs many terminal tiles in tring, most of them Claude Code agents,
4134
+ each in its own slot of a project. You sit in the centre of tring's
4135
+ orchestrator mode: the user talks to you instead of typing into each tile, and
4136
+ you get the work done through the agents in those tiles.
4137
+
4138
+ ## Your tools (the \`tring\` MCP server)
4139
+
4140
+ - \`list_sessions\` \u2014 every project and tile: status (busy = working, done =
4141
+ finished and waiting, idle, exited), the directory its agent works in, its
4142
+ repository, worktree and branch, whether it runs Claude Code, what it is
4143
+ waiting on, and what its agent last said. \`sameWorktreeAs\` marks tiles
4144
+ sharing a worktree. Start here whenever you need to know what is going on.
4145
+ - \`list_worktrees\` \u2014 every worktree of each repository, its branch, and
4146
+ which tiles are in it. Free worktrees are the ones with no tiles.
4147
+ - \`find_work\` \u2014 which tiles have been working on a topic, ranked: by name,
4148
+ branch, conversation title, the prompts they were given, what their agent
4149
+ said and the files they edited.
4150
+ - \`session_history\` \u2014 a tile's conversation: prompts, answers, edited files.
4151
+ - \`read_session\` \u2014 the last lines of a tile's terminal.
4152
+ - \`session_changes\` \u2014 the uncommitted git changes in a tile's worktree.
4153
+ - \`send_prompt\` \u2014 give an agent an instruction, as if the user typed it.
4154
+ - \`create_session\` \u2014 start a new Claude Code tile, optionally with a first
4155
+ prompt, and with \`branch\` in its own git worktree. The user approves each one.
4156
+ - \`wait_for\` \u2014 wait until tiles finish, then read what they said.
4157
+
4158
+ Refer to tiles the way the user does: by project and slot (\`tring.chat/3\`),
4159
+ or by name. A bare slot number means the project the user is looking at.
4160
+
4161
+ ## How to work
4162
+
4163
+ - Delegate. You coordinate; the agents in the tiles do the coding, in their
4164
+ own repositories. Do not edit project files yourself unless the user asks.
4165
+ - The agents cannot see this conversation. Every prompt you send must stand
4166
+ on its own: the goal, the context they need, and what "done" looks like.
4167
+ - Pick the tile whose directory and branch fit the task. If none fits, or the
4168
+ work should run in parallel, offer to start a new tile.
4169
+ - After sending work, use \`wait_for\` and report back what each agent did, in
4170
+ a few lines. Quote them when it matters; never claim work an agent has not
4171
+ reported.
4172
+ - Permission prompts and questions from the agents are the user's to answer
4173
+ in tring's inbox, beside you. If a tile is waiting on one, say so; do not
4174
+ try to answer it by typing into that tile (send_prompt refuses anyway).
4175
+ - Keep replies short and scannable. The user is juggling many sessions.
4176
+
4177
+ ## Which tile? Route by what each one has been doing
4178
+
4179
+ The user talks about work, not slots: "make the reporting box green". Send it
4180
+ to the agent that has been working on that, which already has the context.
4181
+
4182
+ 1. Call \`find_work\` with the user's words. \`list_sessions\` also shows each
4183
+ tile's conversation title and recent prompts.
4184
+ 2. One clear best match: confirm with \`session_history\` (\`search\` for the
4185
+ topic) when the match is thin, then send it there and tell the user which
4186
+ tile you chose and why, in one line.
4187
+ 3. Several match about equally, or none does: do not guess. Ask the user,
4188
+ naming the candidates (slot, name, branch), or offer to start a new tile
4189
+ in its own worktree for it.
4190
+ 4. A clear match that is busy, waiting on the user, or exited: say so, and ask
4191
+ whether to queue it there or start a new tile.
4192
+
4193
+ ## Git worktrees
4194
+
4195
+ The user works in git worktrees: one branch, one worktree, one agent. Treat
4196
+ that as a rule, not a preference.
4197
+
4198
+ - Know where each agent is before you give it work: its \`git.branch\` and
4199
+ \`git.worktree\` in \`list_sessions\`, not just the tile's name. An agent can
4200
+ move into a worktree after its tile started; the tools follow it there.
4201
+ - Never give two agents work in the same worktree at once; they would edit the
4202
+ same files. If \`sameWorktreeAs\` shows a clash, tell the user.
4203
+ - New parallel work gets its own worktree: \`create_session\` with a
4204
+ \`branch\` (and \`base\` when it should not start from the current HEAD).
4205
+ If a worktree already has that branch, it is reused, not duplicated.
4206
+ - Name branches the way the user's existing branches are named (look at
4207
+ \`list_worktrees\`), e.g. with their ticket number when they use one.
4208
+ - Say which branch and worktree each piece of work is on when you report back.
4209
+ - Do not remove worktrees, delete branches, merge or push unless the user asks;
4210
+ when they do, have the agent in that worktree do it.
4211
+ `;
4212
+
2730
4213
  // src/index.ts
2731
4214
  function resolveAuth(args) {
2732
4215
  if (args.insecureNoToken) return { token: null, persisted: false };
@@ -2762,8 +4245,38 @@ async function hooksCommand(argv) {
2762
4245
  }
2763
4246
  return true;
2764
4247
  }
4248
+ async function autostartCommand(argv) {
4249
+ if (argv[0] !== "autostart") return false;
4250
+ const script = fileURLToPath(import.meta.url);
4251
+ if (script.endsWith(".ts")) {
4252
+ throw new UsageError("autostart needs an installed tring (npm i -g tring-chat); a source checkout has no script to start");
4253
+ }
4254
+ const env = { platform: process.platform, home: os9.homedir(), env: process.env, node: process.execPath, script };
4255
+ const verb = argv[1] ?? "status";
4256
+ try {
4257
+ if (verb === "on") {
4258
+ parseArgs(argv.slice(2));
4259
+ const st = await autostartOn(env, argv.slice(2));
4260
+ console.log(`tring will start at login: ${st.file}`);
4261
+ if (process.platform === "linux") console.log(" start it now: systemctl --user start tring");
4262
+ } else if (verb === "off") {
4263
+ console.log(await autostartOff(env) ? "tring will no longer start at login" : "autostart was not on");
4264
+ } else if (verb === "status") {
4265
+ const st = await autostartStatus(env);
4266
+ console.log(!st.present ? `autostart is off (${st.file} does not exist)
4267
+ run: tring autostart on` : st.ours ? `autostart is on: ${st.file}` : `${st.file} exists but was not written by tring; tring leaves it alone`);
4268
+ } else {
4269
+ throw new UsageError(`unknown autostart command ${verb}; use on, off or status`);
4270
+ }
4271
+ } catch (err) {
4272
+ if (err instanceof ForeignAutostart) throw new UsageError(err.message);
4273
+ throw err;
4274
+ }
4275
+ return true;
4276
+ }
2765
4277
  async function main() {
2766
4278
  if (await hooksCommand(process.argv.slice(2))) return;
4279
+ if (await autostartCommand(process.argv.slice(2))) return;
2767
4280
  const args = parseArgs(process.argv.slice(2));
2768
4281
  let auth;
2769
4282
  try {
@@ -2785,15 +4298,15 @@ async function main() {
2785
4298
  const tls = args.tlsCert && args.tlsKey ? loadTls(args.tlsCert, args.tlsKey) : null;
2786
4299
  const url = `${tls ? "https" : "http"}://${args.host}:${args.port}`;
2787
4300
  const cleartextOffBox = !tls && !isLoopbackBind(args.host);
2788
- const here = path12.dirname(fileURLToPath(import.meta.url));
4301
+ const here = path18.dirname(fileURLToPath(import.meta.url));
2789
4302
  const webRoot = [
2790
- path12.resolve(here, "web"),
2791
- path12.resolve(here, "../../web/dist")
2792
- ].find((p) => existsSync2(p)) ?? path12.resolve(here, "web");
4303
+ path18.resolve(here, "web"),
4304
+ path18.resolve(here, "../../web/dist")
4305
+ ].find((p) => existsSync2(p)) ?? path18.resolve(here, "web");
2793
4306
  for (const file of fixSpawnHelper()) console.log(`made ${file} executable`);
2794
- const hookScript = [path12.resolve(here, "tring-hook.js"), path12.resolve(here, "hook-cli.ts")].find((p) => existsSync2(p));
4307
+ const hookScript = [path18.resolve(here, "tring-hook.js"), path18.resolve(here, "hook-cli.ts")].find((p) => existsSync2(p));
2795
4308
  if (hookScript) {
2796
- const binDir = path12.join(path12.dirname(defaultTokenPath()), "bin");
4309
+ const binDir = path18.join(path18.dirname(defaultTokenPath()), "bin");
2797
4310
  try {
2798
4311
  await writeHookShim(binDir, process.execPath, hookScript);
2799
4312
  process.env["PATH"] = prependPath(process.env["PATH"], binDir);
@@ -2811,11 +4324,11 @@ async function main() {
2811
4324
  ...args.shell ? { shell: args.shell } : {}
2812
4325
  });
2813
4326
  const sameOrigin = createOriginCheck({ host: args.host, allow: args.allowOrigin });
2814
- const uploads = new UploadStore(path12.join(path12.dirname(pm.statePath), "uploads"));
4327
+ const uploads = new UploadStore(path18.join(path18.dirname(pm.statePath), "uploads"));
2815
4328
  const inbox = new Inbox();
2816
4329
  const auto = new AutoAnswerer({
2817
4330
  inbox,
2818
- statePath: path12.join(path12.dirname(pm.statePath), "orchestrator.json"),
4331
+ statePath: path18.join(path18.dirname(pm.statePath), "orchestrator.json"),
2819
4332
  context: (id) => {
2820
4333
  const s = pm.findSession(id);
2821
4334
  if (!s) return null;
@@ -2824,6 +4337,19 @@ async function main() {
2824
4337
  }
2825
4338
  });
2826
4339
  await auto.load();
4340
+ const configDir = path18.dirname(pm.statePath);
4341
+ const agent = new OrchestratorAgent({
4342
+ dir: path18.join(configDir, "orchestrator"),
4343
+ statePath: path18.join(configDir, "orchestrator-agent.json"),
4344
+ url,
4345
+ token,
4346
+ scrollback: args.scrollback,
4347
+ idleMs: args.idleMs,
4348
+ ...args.shell ? { shell: args.shell } : {},
4349
+ mcpScript: [path18.resolve(here, "tring-mcp.js"), path18.resolve(here, "mcp-cli.ts")].find((p) => existsSync2(p)) ?? null,
4350
+ node: process.execPath
4351
+ });
4352
+ const tools = new OrchestratorTools({ pm, inbox });
2827
4353
  const handle = createHandler({
2828
4354
  pm,
2829
4355
  webRoot,
@@ -2834,7 +4360,9 @@ async function main() {
2834
4360
  inbox,
2835
4361
  onPermission: (item) => {
2836
4362
  void auto.offer(item);
2837
- }
4363
+ },
4364
+ tools,
4365
+ agentSession: (id) => agent.find(id)
2838
4366
  });
2839
4367
  const listener = (req, res) => {
2840
4368
  void handle(req, res).catch(() => {
@@ -2843,8 +4371,9 @@ async function main() {
2843
4371
  };
2844
4372
  const server = tls ? createSecureServer(tls, listener) : createServer(listener);
2845
4373
  const wss = new WebSocketServer({ server, verifyClient: upgradeGuard(sameOrigin) });
2846
- const hub = new Hub({ pm, token, inbox, auto });
4374
+ const hub = new Hub({ pm, token, inbox, auto, agent });
2847
4375
  hub.attach(wss);
4376
+ await agent.load();
2848
4377
  const authUrl = token ? `${url}/?token=${encodeURIComponent(token)}` : url;
2849
4378
  server.listen(args.port, args.host, () => {
2850
4379
  console.log(`tring listening on ${url}`);
@@ -2856,7 +4385,7 @@ async function main() {
2856
4385
  console.warn(`warning: ${url} is plain http \u2014 the token, every keystroke and all terminal output cross the network in clear. Use an encrypted overlay (Tailscale, WireGuard) or pass --tls-cert/--tls-key.`);
2857
4386
  }
2858
4387
  if (args.updateCheck) {
2859
- void checkForUpdate(path12.join(path12.dirname(pm.statePath), "update-check.json")).then((latest) => {
4388
+ void checkForUpdate(path18.join(path18.dirname(pm.statePath), "update-check.json")).then((latest) => {
2860
4389
  if (!latest) return;
2861
4390
  hub.setUpdate({ current: currentVersion(), latest });
2862
4391
  console.log(`update available: ${currentVersion()} -> ${latest} (npm i -g tring-chat)`);
@@ -2872,6 +4401,7 @@ async function main() {
2872
4401
  });
2873
4402
  const shutdown = async () => {
2874
4403
  hub.dispose();
4404
+ agent.dispose();
2875
4405
  await uploads.dispose();
2876
4406
  await pm.dispose();
2877
4407
  server.close(() => process.exit(0));