tring-chat 0.1.18 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +28 -0
  2. package/dist/tring.js +290 -60
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -430,6 +430,34 @@ Two things are deliberate:
430
430
  Auto-executing whatever was there last time is how four dev servers end up fighting
431
431
  over a port.
432
432
 
433
+ ### Claude conversations come back too
434
+
435
+ A tile that was running Claude Code reopens the same conversation after a restart
436
+ of tring or of the machine: tring types `claude --resume <id>` into the tile's shell
437
+ once it has started. Claude waits for your next prompt, so nothing runs that was not
438
+ already running. Quitting Claude still leaves you in that shell.
439
+
440
+ tring learns which conversation each tile is running from Claude Code's
441
+ `SessionStart` and `SessionEnd` hooks, which `tring hooks install` adds (run it again
442
+ if you installed the hooks before this, then restart your `claude` sessions once).
443
+ Ending a conversation yourself (`/exit`, Ctrl+D, `/clear`) forgets it. Stopping tring
444
+ or shutting down does not, since that is the conversation you want back. A tile that
445
+ was resumed runs plain `claude --resume`, so flags you started it with (`--model`,
446
+ a permission mode) fall back to your settings.
447
+
448
+ To have tring itself running after a reboot:
449
+
450
+ ```sh
451
+ tring autostart on # flags after `on` are passed to the daemon, e.g. --allow-origin …
452
+ tring autostart status
453
+ tring autostart off
454
+ ```
455
+
456
+ This writes a systemd user unit on Linux, a LaunchAgent on macOS, or a `.cmd` in the
457
+ Startup folder on Windows, with the `PATH` you ran it from so the tiles find `claude`
458
+ and your tools. It is enabled for your next login, not started, since tring is usually
459
+ running already. A file at that path that tring did not write is left alone.
460
+
433
461
  ## Dropping files on a terminal
434
462
 
435
463
  Drag a screenshot, a spreadsheet or any other file onto the centre terminal and its path is typed into the prompt,
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 path14 from "node:path";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { WebSocketServer } from "ws";
10
11
 
@@ -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
 
@@ -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,8 @@ 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;
540
567
  tracker;
541
568
  onData = null;
542
569
  onStatusChange = null;
@@ -553,6 +580,8 @@ var Session = class {
553
580
  hasInput = false;
554
581
  /** Fires when the shell moves, so the new location gets persisted. */
555
582
  onCwdChange = null;
583
+ /** Fires when Claude starts, switches or ends a conversation here. */
584
+ onClaudeChange = null;
556
585
  /**
557
586
  * Where the shell *is*, not where it started. A session spawned in a project
558
587
  * root that the developer then `cd`s out of must come back to where they
@@ -573,6 +602,7 @@ var Session = class {
573
602
  const shell = opts.shell ?? defaultShell();
574
603
  const env = {};
575
604
  for (const [k, v] of Object.entries(process.env)) if (v !== void 0) env[k] = v;
605
+ for (const k of INHERITED_CLAUDE) delete env[k];
576
606
  env["TRING_SESSION_ID"] = this.id;
577
607
  env["TRING_SLOT"] = String(this.slot);
578
608
  env["TRING_PROJECT"] = opts.projectName;
@@ -621,8 +651,15 @@ var Session = class {
621
651
  this.term.write(chunk);
622
652
  this.onData?.(chunk);
623
653
  });
624
- if (!(this.command && autorun) && usesPosixCd(shell)) {
625
- this.enforceTimer = setTimeout(() => this.enforceCwd(), CWD_ENFORCE_MS);
654
+ const interactive = !(this.command && autorun);
655
+ const resume = interactive ? claudeConversation(opts.resume) : null;
656
+ this.claude = resume;
657
+ const posix = usesPosixCd(shell);
658
+ if (interactive && (posix || resume)) {
659
+ this.enforceTimer = setTimeout(() => {
660
+ if (posix) this.enforceCwd();
661
+ if (resume) this.typeResume(resume, posix);
662
+ }, CWD_ENFORCE_MS);
626
663
  this.enforceTimer.unref?.();
627
664
  }
628
665
  this.pty.onExit(({ exitCode }) => {
@@ -716,6 +753,27 @@ var Session = class {
716
753
  } catch {
717
754
  }
718
755
  }
756
+ /**
757
+ * Claude Code's hook payload is the only source of these, and it reports a
758
+ * conversation start (new, resumed, after /clear) and end. Null forgets it.
759
+ */
760
+ setClaude(conv) {
761
+ const next = conv ? claudeConversation(conv) : null;
762
+ if (conv && !next) return;
763
+ if (next?.id === this.claude?.id && next?.cwd === this.claude?.cwd) return;
764
+ this.claude = next;
765
+ this.onClaudeChange?.();
766
+ }
767
+ /**
768
+ * Typed straight to the PTY rather than through write(): it is tring's
769
+ * keystroke, not the user's, and must not count as them having taken over
770
+ * the shell. Skipped if they already have, since then the prompt is theirs.
771
+ */
772
+ typeResume(conv, posix) {
773
+ if (this.disposed || this.hasInput) return;
774
+ const cd = posix && conv.cwd && conv.cwd !== this.spawnCwd ? `cd -- ${shQuote(conv.cwd)} && ` : "";
775
+ this.pty.write(`${cd}claude --resume ${conv.id}\r`);
776
+ }
719
777
  /** Runs once, only if the shell is not where it was asked to be. */
720
778
  enforceCwd() {
721
779
  if (this.disposed || this.hasInput || process.platform !== "linux") return;
@@ -808,12 +866,14 @@ var SessionManager = class {
808
866
  scrollback: this.opts.scrollback,
809
867
  idleMs: this.opts.idleMs,
810
868
  ...this.opts.shell ? { shell: this.opts.shell } : {},
811
- autorun: spec.autorun
869
+ autorun: spec.autorun,
870
+ resume: spec.resume ?? null
812
871
  });
813
872
  session.onData = (data) => this.onSessionData?.(session, data);
814
873
  session.onStatusChange = () => this.onSessionStatus?.(session);
815
874
  session.onExit = (code) => this.onSessionExit?.(session, code);
816
875
  session.onCwdChange = () => this.structureChanged();
876
+ session.onClaudeChange = () => this.structureChanged();
817
877
  this.bySlot.set(slot, session);
818
878
  this.byId.set(session.id, session);
819
879
  this.structureChanged();
@@ -886,7 +946,10 @@ var SessionManager = class {
886
946
  command: old.command,
887
947
  name: old.name,
888
948
  color: old.color,
889
- autorun: true
949
+ autorun: true,
950
+ // A dead tile that was a shell running Claude comes back to the same
951
+ // conversation; one with its own command re-runs that instead.
952
+ resume: old.claude
890
953
  };
891
954
  this.quiet = true;
892
955
  try {
@@ -915,8 +978,8 @@ var SessionManager = class {
915
978
 
916
979
  // src/project-manager.ts
917
980
  function defaultStatePath() {
918
- const base2 = process.env["XDG_CONFIG_HOME"] ?? path3.join(os2.homedir(), ".config");
919
- return path3.join(base2, "tring", "projects.json");
981
+ const base2 = process.env["XDG_CONFIG_HOME"] ?? path4.join(os2.homedir(), ".config");
982
+ return path4.join(base2, "tring", "projects.json");
920
983
  }
921
984
  var ProjectManager = class _ProjectManager {
922
985
  constructor(opts) {
@@ -926,6 +989,13 @@ var ProjectManager = class _ProjectManager {
926
989
  activeId = null;
927
990
  timer = null;
928
991
  writing = Promise.resolve();
992
+ /**
993
+ * Set once shutdown starts. Stopping the daemon (or the machine) signals
994
+ * every shell and Claude in it as well, and what they do on the way out —
995
+ * exiting, ending their conversation — must not be saved as the state to
996
+ * come back to.
997
+ */
998
+ closing = false;
929
999
  onChange = null;
930
1000
  onSessionData = null;
931
1001
  onSessionStatus = null;
@@ -984,7 +1054,7 @@ var ProjectManager = class _ProjectManager {
984
1054
  if (!e.manager) {
985
1055
  e.manager = this.spawnManager(e);
986
1056
  for (const rec of e.pending) {
987
- e.manager.create({ ...rec, autorun: false });
1057
+ e.manager.create({ ...rec, autorun: false, resume: rec.claude ?? null });
988
1058
  }
989
1059
  e.pending = [];
990
1060
  }
@@ -1018,6 +1088,7 @@ var ProjectManager = class _ProjectManager {
1018
1088
  return void 0;
1019
1089
  }
1020
1090
  async dispose() {
1091
+ this.closing = true;
1021
1092
  if (this.timer) clearInterval(this.timer);
1022
1093
  this.timer = null;
1023
1094
  for (const e of this.entries.values()) e.manager?.disposeAll();
@@ -1048,6 +1119,7 @@ var ProjectManager = class _ProjectManager {
1048
1119
  for (const e of this.entries.values()) e.manager?.tick(now);
1049
1120
  }
1050
1121
  changed() {
1122
+ if (this.closing) return;
1051
1123
  this.onChange?.();
1052
1124
  void this.save();
1053
1125
  }
@@ -1064,7 +1136,8 @@ var ProjectManager = class _ProjectManager {
1064
1136
  name: s.name,
1065
1137
  cwd: s.cwd,
1066
1138
  command: s.command,
1067
- color: s.color
1139
+ color: s.color,
1140
+ ...s.claude ? { claude: s.claude } : {}
1068
1141
  })) : e.pending
1069
1142
  }))
1070
1143
  };
@@ -1072,7 +1145,7 @@ var ProjectManager = class _ProjectManager {
1072
1145
  save() {
1073
1146
  const state = this.snapshotState();
1074
1147
  this.writing = this.writing.then(async () => {
1075
- await mkdir2(path3.dirname(this.statePath), { recursive: true });
1148
+ await mkdir2(path4.dirname(this.statePath), { recursive: true });
1076
1149
  await writeFile2(this.statePath, JSON.stringify(state, null, 2), "utf8");
1077
1150
  }).catch(() => {
1078
1151
  });
@@ -1104,7 +1177,7 @@ var ProjectManager = class _ProjectManager {
1104
1177
  import { createReadStream } from "node:fs";
1105
1178
  import { readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";
1106
1179
  import os5 from "node:os";
1107
- import path8 from "node:path";
1180
+ import path9 from "node:path";
1108
1181
 
1109
1182
  // src/security.ts
1110
1183
  import { createHash, timingSafeEqual } from "node:crypto";
@@ -1180,7 +1253,7 @@ var SECURITY_HEADERS = Object.freeze({
1180
1253
  import { spawn as spawn2 } from "node:child_process";
1181
1254
  import { readdir, readFile as readFile3, stat } from "node:fs/promises";
1182
1255
  import os3 from "node:os";
1183
- import path4 from "node:path";
1256
+ import path5 from "node:path";
1184
1257
  var WINDOW_MS = 5 * 36e5;
1185
1258
  var WEEK_MS = 7 * 24 * 36e5;
1186
1259
  var PRICES = [
@@ -1192,8 +1265,8 @@ var PRICES = [
1192
1265
  ["claude-haiku-", 1, 5]
1193
1266
  ];
1194
1267
  function defaultTranscriptDir() {
1195
- const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path4.join(os3.homedir(), ".claude");
1196
- return path4.join(base2, "projects");
1268
+ const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path5.join(os3.homedir(), ".claude");
1269
+ return path5.join(base2, "projects");
1197
1270
  }
1198
1271
  var empty = () => ({ tokens: 0, cacheReadTokens: 0, cost: 0, messages: 0 });
1199
1272
  function add(b, e) {
@@ -1301,7 +1374,7 @@ async function transcripts(dir, since) {
1301
1374
  const out = [];
1302
1375
  for (const name of names) {
1303
1376
  if (!name.endsWith(".jsonl")) continue;
1304
- const file = path4.join(dir, name);
1377
+ const file = path5.join(dir, name);
1305
1378
  try {
1306
1379
  if ((await stat(file)).mtimeMs >= since) out.push(file);
1307
1380
  } catch {
@@ -1381,7 +1454,7 @@ function describe(err) {
1381
1454
  // src/uploads.ts
1382
1455
  import { randomBytes as randomBytes2 } from "node:crypto";
1383
1456
  import { mkdir as mkdir3, readdir as readdir2, rm, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
1384
- import path5 from "node:path";
1457
+ import path6 from "node:path";
1385
1458
  var MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
1386
1459
  var KEEP = 20;
1387
1460
  function sniffImage(bytes) {
@@ -1410,7 +1483,7 @@ var UploadStore = class {
1410
1483
  const ext = sniffImage(bytes);
1411
1484
  const tail = ext ?? "-" + (name.replace(/[^\w.-]+/g, "_").slice(-80) || "file");
1412
1485
  await mkdir3(this.dir, { recursive: true, mode: 448 });
1413
- const file = path5.join(this.dir, randomBytes2(8).toString("hex") + tail);
1486
+ const file = path6.join(this.dir, randomBytes2(8).toString("hex") + tail);
1414
1487
  await writeFile3(file, bytes, { mode: 384 });
1415
1488
  await this.prune();
1416
1489
  return file;
@@ -1429,7 +1502,7 @@ var UploadStore = class {
1429
1502
  const names = await readdir2(this.dir);
1430
1503
  if (names.length <= this.keep) return;
1431
1504
  const dated = await Promise.all(names.map(async (name) => {
1432
- const full = path5.join(this.dir, name);
1505
+ const full = path6.join(this.dir, name);
1433
1506
  return { full, at: (await stat2(full)).mtimeMs };
1434
1507
  }));
1435
1508
  dated.sort((a, b) => b.at - a.at);
@@ -1442,7 +1515,7 @@ var UploadStore = class {
1442
1515
  // src/git-diff.ts
1443
1516
  import { execFile } from "node:child_process";
1444
1517
  import { lstat, readFile as readFile4 } from "node:fs/promises";
1445
- import path6 from "node:path";
1518
+ import path7 from "node:path";
1446
1519
  import { promisify } from "node:util";
1447
1520
  var run = promisify(execFile);
1448
1521
  var MAX_PATCH_BYTES = 1 << 20;
@@ -1497,7 +1570,7 @@ function splitPatch(text2) {
1497
1570
  return out;
1498
1571
  }
1499
1572
  async function untracked(root, rel, budget) {
1500
- const full = path6.join(root, rel);
1573
+ const full = path7.join(root, rel);
1501
1574
  let bytes;
1502
1575
  try {
1503
1576
  const st = await lstat(full);
@@ -1677,6 +1750,7 @@ function hookOutput(event, input, s) {
1677
1750
  }
1678
1751
 
1679
1752
  // src/hook-route.ts
1753
+ var USER_ENDED = /* @__PURE__ */ new Set(["prompt_input_exit", "logout", "clear"]);
1680
1754
  function routeHook(req) {
1681
1755
  const { inbox, session, event, payload } = req;
1682
1756
  const tool = payload.tool_name;
@@ -1700,6 +1774,14 @@ function routeHook(req) {
1700
1774
  case "Notification":
1701
1775
  session.hook();
1702
1776
  return Promise.resolve(null);
1777
+ // New, resumed, after /clear or a compaction: whichever, it is now the
1778
+ // conversation this tile would reopen.
1779
+ case "SessionStart":
1780
+ if (payload.session_id) session.setClaude({ id: payload.session_id, cwd: payload.cwd ?? "" });
1781
+ return Promise.resolve(null);
1782
+ case "SessionEnd":
1783
+ if (payload.reason && USER_ENDED.has(payload.reason)) session.setClaude(null);
1784
+ return Promise.resolve(null);
1703
1785
  // The user typed into this session's own terminal: whatever its cards
1704
1786
  // were asking has been dealt with there.
1705
1787
  case "UserPromptSubmit":
@@ -1736,7 +1818,7 @@ function hold(req, fields) {
1736
1818
  // src/hooks-install.ts
1737
1819
  import { copyFile, mkdir as mkdir4, readFile as readFile5, rename, writeFile as writeFile4 } from "node:fs/promises";
1738
1820
  import os4 from "node:os";
1739
- import path7 from "node:path";
1821
+ import path8 from "node:path";
1740
1822
  var HOOK_COMMAND = "tring-hook";
1741
1823
  var HOOK_SPECS = [
1742
1824
  { event: "PermissionRequest", timeout: 3600 },
@@ -1745,11 +1827,14 @@ var HOOK_SPECS = [
1745
1827
  { event: "PostToolUseFailure", timeout: 10 },
1746
1828
  { event: "UserPromptSubmit", timeout: 10 },
1747
1829
  { event: "Notification", timeout: 10 },
1748
- { event: "Stop", timeout: 10 }
1830
+ { event: "Stop", timeout: 10 },
1831
+ // Which conversation each tile is running, so a restart can reopen it.
1832
+ { event: "SessionStart", timeout: 10 },
1833
+ { event: "SessionEnd", timeout: 10 }
1749
1834
  ];
1750
1835
  function defaultClaudeSettingsPath() {
1751
- const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path7.join(os4.homedir(), ".claude");
1752
- return path7.join(base2, "settings.json");
1836
+ const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path8.join(os4.homedir(), ".claude");
1837
+ return path8.join(base2, "settings.json");
1753
1838
  }
1754
1839
  var ours = (h) => typeof h.command === "string" && h.command.trim().startsWith(HOOK_COMMAND + " ");
1755
1840
  function withoutHooks(settings) {
@@ -1803,7 +1888,7 @@ async function read(file) {
1803
1888
  return parsed;
1804
1889
  }
1805
1890
  async function write(file, previous, settings) {
1806
- await mkdir4(path7.dirname(file), { recursive: true });
1891
+ await mkdir4(path8.dirname(file), { recursive: true });
1807
1892
  if (previous) await copyFile(file, `${file}.tring-backup`);
1808
1893
  const tmp = `${file}.tring-${process.pid}`;
1809
1894
  await writeFile4(tmp, JSON.stringify(settings, null, 2) + "\n", "utf8");
@@ -1902,14 +1987,14 @@ function createHandler(opts) {
1902
1987
  let usage = null;
1903
1988
  const homeDir = () => process.env["HOME"] ?? os5.homedir();
1904
1989
  const within = (root, dir) => {
1905
- const rel = path8.relative(path8.resolve(root), dir);
1906
- return rel === "" || !rel.startsWith("..") && !path8.isAbsolute(rel);
1990
+ const rel = path9.relative(path9.resolve(root), dir);
1991
+ return rel === "" || !rel.startsWith("..") && !path9.isAbsolute(rel);
1907
1992
  };
1908
1993
  const real = async (p) => {
1909
1994
  try {
1910
1995
  return await realpath(p);
1911
1996
  } catch {
1912
- return path8.resolve(p);
1997
+ return path9.resolve(p);
1913
1998
  }
1914
1999
  };
1915
2000
  const browsable = async (dir) => {
@@ -2005,12 +2090,12 @@ function createHandler(opts) {
2005
2090
  }
2006
2091
  if (url.pathname === "/api/fs" && req.method === "GET") {
2007
2092
  const raw = url.searchParams.get("path")?.trim();
2008
- const dir = raw ? path8.resolve(raw) : homeDir();
2093
+ const dir = raw ? path9.resolve(raw) : homeDir();
2009
2094
  if (!await browsable(dir)) return json(res, 403, { error: "outside the browsable roots" });
2010
2095
  try {
2011
2096
  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);
2097
+ const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path9.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
2098
+ const parent = path9.dirname(dir);
2014
2099
  const up = parent !== dir && await browsable(parent) ? parent : null;
2015
2100
  return json(res, 200, { path: dir, parent: up, entries });
2016
2101
  } catch {
@@ -2057,15 +2142,15 @@ function createHandler(opts) {
2057
2142
  }
2058
2143
  async function serveStatic(res, pathname) {
2059
2144
  const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
2060
- const file = path8.resolve(webRoot, rel);
2061
- if (file !== webRoot && !file.startsWith(webRoot + path8.sep)) {
2145
+ const file = path9.resolve(webRoot, rel);
2146
+ if (file !== webRoot && !file.startsWith(webRoot + path9.sep)) {
2062
2147
  text(res, 403, "forbidden");
2063
2148
  return;
2064
2149
  }
2065
2150
  try {
2066
2151
  const info = await stat3(file);
2067
2152
  if (!info.isFile()) throw new Error("not a file");
2068
- head(res, 200, MIME[path8.extname(file)] ?? "application/octet-stream");
2153
+ head(res, 200, MIME[path9.extname(file)] ?? "application/octet-stream");
2069
2154
  createReadStream(file).pipe(res);
2070
2155
  } catch {
2071
2156
  if (rel === "index.html") {
@@ -2459,25 +2544,25 @@ import {
2459
2544
  readdirSync
2460
2545
  } from "node:fs";
2461
2546
  import { createRequire as createRequire4 } from "node:module";
2462
- import path9 from "node:path";
2547
+ import path10 from "node:path";
2463
2548
  var EXEC = 73;
2464
2549
  function nodePtyRoot() {
2465
2550
  try {
2466
- return path9.dirname(createRequire4(import.meta.url).resolve("node-pty/package.json"));
2551
+ return path10.dirname(createRequire4(import.meta.url).resolve("node-pty/package.json"));
2467
2552
  } catch {
2468
2553
  return null;
2469
2554
  }
2470
2555
  }
2471
2556
  function spawnHelperPaths(root) {
2472
- const found = [path9.join(root, "build", "Release", "spawn-helper")];
2557
+ const found = [path10.join(root, "build", "Release", "spawn-helper")];
2473
2558
  let prebuilds;
2474
2559
  try {
2475
- prebuilds = readdirSync(path9.join(root, "prebuilds"), { withFileTypes: true });
2560
+ prebuilds = readdirSync(path10.join(root, "prebuilds"), { withFileTypes: true });
2476
2561
  } catch {
2477
2562
  return found;
2478
2563
  }
2479
2564
  for (const entry of prebuilds) {
2480
- if (entry.isDirectory()) found.push(path9.join(root, "prebuilds", entry.name, "spawn-helper"));
2565
+ if (entry.isDirectory()) found.push(path10.join(root, "prebuilds", entry.name, "spawn-helper"));
2481
2566
  }
2482
2567
  return found;
2483
2568
  }
@@ -2506,7 +2591,7 @@ function fixSpawnHelper(root = nodePtyRoot()) {
2506
2591
  import { spawn as spawn4 } from "node:child_process";
2507
2592
  import { mkdir as mkdir5, readFile as readFile6, writeFile as writeFile5 } from "node:fs/promises";
2508
2593
  import os7 from "node:os";
2509
- import path10 from "node:path";
2594
+ import path11 from "node:path";
2510
2595
  var BASH_ALWAYS_ASK = [
2511
2596
  /\brm\s+(-[a-zA-Z]*[rRf]|--recursive|--force)/,
2512
2597
  /\bsudo\b|\bdoas\b|\bsu\s/,
@@ -2530,8 +2615,8 @@ var BASH_ALWAYS_ASK = [
2530
2615
  var PATH_ALWAYS_ASK = /(^|\/)(\.env[^/]*|\.git\/|\.ssh\/|\.aws\/|id_rsa|id_ed25519|credentials[^/]*|\.npmrc|\.netrc|secrets?\.[a-z]+)$|(^|\/)\.git\//;
2531
2616
  var FILE_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
2532
2617
  var inside = (cwd, p) => {
2533
- const rel = path10.relative(path10.resolve(cwd), path10.resolve(cwd, p));
2534
- return rel === "" || !rel.startsWith("..") && !path10.isAbsolute(rel);
2618
+ const rel = path11.relative(path11.resolve(cwd), path11.resolve(cwd, p));
2619
+ return rel === "" || !rel.startsWith("..") && !path11.isAbsolute(rel);
2535
2620
  };
2536
2621
  function rule(item, cwd) {
2537
2622
  if (item.kind !== "permission") return { verdict: "ask", reason: "only permission prompts are auto-answered" };
@@ -2544,7 +2629,7 @@ function rule(item, cwd) {
2544
2629
  const p = String(input["file_path"] ?? input["notebook_path"] ?? "");
2545
2630
  if (!p) return { verdict: "ask", reason: "no file path given" };
2546
2631
  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" };
2632
+ if (PATH_ALWAYS_ASK.test(path11.resolve(cwd, p))) return { verdict: "ask", reason: "a secrets or git file" };
2548
2633
  return { verdict: "classify" };
2549
2634
  }
2550
2635
  if (tool === "Bash") {
@@ -2665,7 +2750,7 @@ var AutoAnswerer = class {
2665
2750
  this.on = on;
2666
2751
  this.onChange?.();
2667
2752
  if (!this.opts.statePath) return;
2668
- await mkdir5(path10.dirname(this.opts.statePath), { recursive: true });
2753
+ await mkdir5(path11.dirname(this.opts.statePath), { recursive: true });
2669
2754
  await writeFile5(this.opts.statePath, JSON.stringify({ autoAnswer: on }, null, 2) + "\n", "utf8");
2670
2755
  }
2671
2756
  /**
@@ -2711,20 +2796,135 @@ var AutoAnswerer = class {
2711
2796
 
2712
2797
  // src/hook-shim.ts
2713
2798
  import { chmod, mkdir as mkdir6, writeFile as writeFile6 } from "node:fs/promises";
2714
- import path11 from "node:path";
2799
+ import path12 from "node:path";
2715
2800
  async function writeHookShim(dir, node, script) {
2716
2801
  await mkdir6(dir, { recursive: true });
2717
2802
  const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
2718
- await writeFile6(path11.join(dir, "tring-hook"), `#!/bin/sh
2803
+ await writeFile6(path12.join(dir, "tring-hook"), `#!/bin/sh
2719
2804
  exec ${q(node)} ${q(script)} "$@"
2720
2805
  `, "utf8");
2721
- await chmod(path11.join(dir, "tring-hook"), 493);
2722
- await writeFile6(path11.join(dir, "tring-hook.cmd"), `@"${node}" "${script}" %*\r
2806
+ await chmod(path12.join(dir, "tring-hook"), 493);
2807
+ await writeFile6(path12.join(dir, "tring-hook.cmd"), `@"${node}" "${script}" %*\r
2723
2808
  `, "utf8");
2724
2809
  }
2725
2810
  function prependPath(current, dir) {
2726
- const parts = (current ?? "").split(path11.delimiter).filter((p) => p && p !== dir);
2727
- return [dir, ...parts].join(path11.delimiter);
2811
+ const parts = (current ?? "").split(path12.delimiter).filter((p) => p && p !== dir);
2812
+ return [dir, ...parts].join(path12.delimiter);
2813
+ }
2814
+
2815
+ // src/autostart.ts
2816
+ import { execFile as execFile2 } from "node:child_process";
2817
+ import { mkdir as mkdir7, readFile as readFile7, rename as rename2, rm as rm2, writeFile as writeFile7 } from "node:fs/promises";
2818
+ import os8 from "node:os";
2819
+ import path13 from "node:path";
2820
+ var MARKER = "written by tring autostart";
2821
+ var LABEL = "chat.tring.daemon";
2822
+ function autostartFile(e) {
2823
+ if (e.platform === "darwin") return path13.join(e.home, "Library", "LaunchAgents", `${LABEL}.plist`);
2824
+ if (e.platform === "win32") {
2825
+ const appData = e.env["APPDATA"] ?? path13.join(e.home, "AppData", "Roaming");
2826
+ return path13.win32.join(appData, "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "tring.cmd");
2827
+ }
2828
+ const config = e.env["XDG_CONFIG_HOME"] ?? path13.join(e.home, ".config");
2829
+ return path13.join(config, "systemd", "user", "tring.service");
2830
+ }
2831
+ var sdQuote = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
2832
+ var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2833
+ var cmdQuote = (s) => {
2834
+ if (/["%\r\n]/.test(s)) throw new Error(`cannot put ${JSON.stringify(s)} in a .cmd file`);
2835
+ return `"${s}"`;
2836
+ };
2837
+ function autostartContent(e, flags) {
2838
+ const argv = [e.node, e.script, "--no-open", ...flags];
2839
+ const PATH = e.env["PATH"] ?? "";
2840
+ if (e.platform === "darwin") {
2841
+ return `<?xml version="1.0" encoding="UTF-8"?>
2842
+ <!-- ${MARKER} -->
2843
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2844
+ <plist version="1.0">
2845
+ <dict>
2846
+ <key>Label</key><string>${LABEL}</string>
2847
+ <key>ProgramArguments</key>
2848
+ <array>
2849
+ ${argv.map((a) => ` <string>${xml(a)}</string>`).join("\n")}
2850
+ </array>
2851
+ <key>EnvironmentVariables</key>
2852
+ <dict><key>PATH</key><string>${xml(PATH)}</string></dict>
2853
+ <key>WorkingDirectory</key><string>${xml(e.home)}</string>
2854
+ <key>RunAtLoad</key><true/>
2855
+ <key>KeepAlive</key><true/>
2856
+ </dict>
2857
+ </plist>
2858
+ `;
2859
+ }
2860
+ if (e.platform === "win32") {
2861
+ return [
2862
+ "@echo off",
2863
+ `rem ${MARKER}`,
2864
+ `set ${cmdQuote(`PATH=${PATH}`)}`,
2865
+ `cd /d ${cmdQuote(e.home)}`,
2866
+ `start "tring" /min ${argv.map(cmdQuote).join(" ")}`,
2867
+ ""
2868
+ ].join("\r\n");
2869
+ }
2870
+ return `# ${MARKER}
2871
+ [Unit]
2872
+ Description=tring terminal deck daemon
2873
+ After=graphical-session.target
2874
+
2875
+ [Service]
2876
+ Type=simple
2877
+ Environment=${sdQuote(`PATH=${PATH}`)}
2878
+ WorkingDirectory=${e.home}
2879
+ ExecStart=${argv.map(sdQuote).join(" ")}
2880
+ Restart=always
2881
+ RestartSec=2
2882
+
2883
+ [Install]
2884
+ WantedBy=default.target
2885
+ `;
2886
+ }
2887
+ var defaultRun = (cmd, args) => new Promise((resolve) => execFile2(cmd, args, (err) => resolve(!err)));
2888
+ async function autostartStatus(e) {
2889
+ const file = autostartFile(e);
2890
+ try {
2891
+ const text2 = await readFile7(file, "utf8");
2892
+ return { file, present: true, ours: text2.includes(MARKER) };
2893
+ } catch {
2894
+ return { file, present: false, ours: false };
2895
+ }
2896
+ }
2897
+ var ForeignAutostart = class extends Error {
2898
+ };
2899
+ async function autostartOn(e, flags = []) {
2900
+ const st = await autostartStatus(e);
2901
+ if (st.present && !st.ours) {
2902
+ throw new ForeignAutostart(`${st.file} already exists and tring did not write it, so it was left alone.
2903
+ If it already starts tring at login there is nothing to do; otherwise move it aside and run this again.`);
2904
+ }
2905
+ await mkdir7(path13.dirname(st.file), { recursive: true });
2906
+ const tmp = `${st.file}.tring-${process.pid}`;
2907
+ await writeFile7(tmp, autostartContent(e, flags), "utf8");
2908
+ await rename2(tmp, st.file);
2909
+ const run2 = e.run ?? defaultRun;
2910
+ if (e.platform === "linux") {
2911
+ await run2("systemctl", ["--user", "daemon-reload"]);
2912
+ if (!await run2("systemctl", ["--user", "enable", "tring.service"])) {
2913
+ throw new Error(`wrote ${st.file}, but systemctl --user enable tring.service failed`);
2914
+ }
2915
+ }
2916
+ return { ...st, present: true, ours: true };
2917
+ }
2918
+ async function autostartOff(e) {
2919
+ const st = await autostartStatus(e);
2920
+ if (!st.present) return false;
2921
+ if (!st.ours) throw new ForeignAutostart(`${st.file} was not written by tring, so it was left alone.`);
2922
+ const run2 = e.run ?? defaultRun;
2923
+ if (e.platform === "linux") await run2("systemctl", ["--user", "disable", "tring.service"]);
2924
+ if (e.platform === "darwin") await run2("launchctl", ["bootout", `gui/${os8.userInfo().uid}/${LABEL}`]);
2925
+ await rm2(st.file, { force: true });
2926
+ if (e.platform === "linux") await run2("systemctl", ["--user", "daemon-reload"]);
2927
+ return true;
2728
2928
  }
2729
2929
 
2730
2930
  // src/index.ts
@@ -2762,8 +2962,38 @@ async function hooksCommand(argv) {
2762
2962
  }
2763
2963
  return true;
2764
2964
  }
2965
+ async function autostartCommand(argv) {
2966
+ if (argv[0] !== "autostart") return false;
2967
+ const script = fileURLToPath(import.meta.url);
2968
+ if (script.endsWith(".ts")) {
2969
+ throw new UsageError("autostart needs an installed tring (npm i -g tring-chat); a source checkout has no script to start");
2970
+ }
2971
+ const env = { platform: process.platform, home: os9.homedir(), env: process.env, node: process.execPath, script };
2972
+ const verb = argv[1] ?? "status";
2973
+ try {
2974
+ if (verb === "on") {
2975
+ parseArgs(argv.slice(2));
2976
+ const st = await autostartOn(env, argv.slice(2));
2977
+ console.log(`tring will start at login: ${st.file}`);
2978
+ if (process.platform === "linux") console.log(" start it now: systemctl --user start tring");
2979
+ } else if (verb === "off") {
2980
+ console.log(await autostartOff(env) ? "tring will no longer start at login" : "autostart was not on");
2981
+ } else if (verb === "status") {
2982
+ const st = await autostartStatus(env);
2983
+ console.log(!st.present ? `autostart is off (${st.file} does not exist)
2984
+ run: tring autostart on` : st.ours ? `autostart is on: ${st.file}` : `${st.file} exists but was not written by tring; tring leaves it alone`);
2985
+ } else {
2986
+ throw new UsageError(`unknown autostart command ${verb}; use on, off or status`);
2987
+ }
2988
+ } catch (err) {
2989
+ if (err instanceof ForeignAutostart) throw new UsageError(err.message);
2990
+ throw err;
2991
+ }
2992
+ return true;
2993
+ }
2765
2994
  async function main() {
2766
2995
  if (await hooksCommand(process.argv.slice(2))) return;
2996
+ if (await autostartCommand(process.argv.slice(2))) return;
2767
2997
  const args = parseArgs(process.argv.slice(2));
2768
2998
  let auth;
2769
2999
  try {
@@ -2785,15 +3015,15 @@ async function main() {
2785
3015
  const tls = args.tlsCert && args.tlsKey ? loadTls(args.tlsCert, args.tlsKey) : null;
2786
3016
  const url = `${tls ? "https" : "http"}://${args.host}:${args.port}`;
2787
3017
  const cleartextOffBox = !tls && !isLoopbackBind(args.host);
2788
- const here = path12.dirname(fileURLToPath(import.meta.url));
3018
+ const here = path14.dirname(fileURLToPath(import.meta.url));
2789
3019
  const webRoot = [
2790
- path12.resolve(here, "web"),
2791
- path12.resolve(here, "../../web/dist")
2792
- ].find((p) => existsSync2(p)) ?? path12.resolve(here, "web");
3020
+ path14.resolve(here, "web"),
3021
+ path14.resolve(here, "../../web/dist")
3022
+ ].find((p) => existsSync2(p)) ?? path14.resolve(here, "web");
2793
3023
  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));
3024
+ const hookScript = [path14.resolve(here, "tring-hook.js"), path14.resolve(here, "hook-cli.ts")].find((p) => existsSync2(p));
2795
3025
  if (hookScript) {
2796
- const binDir = path12.join(path12.dirname(defaultTokenPath()), "bin");
3026
+ const binDir = path14.join(path14.dirname(defaultTokenPath()), "bin");
2797
3027
  try {
2798
3028
  await writeHookShim(binDir, process.execPath, hookScript);
2799
3029
  process.env["PATH"] = prependPath(process.env["PATH"], binDir);
@@ -2811,11 +3041,11 @@ async function main() {
2811
3041
  ...args.shell ? { shell: args.shell } : {}
2812
3042
  });
2813
3043
  const sameOrigin = createOriginCheck({ host: args.host, allow: args.allowOrigin });
2814
- const uploads = new UploadStore(path12.join(path12.dirname(pm.statePath), "uploads"));
3044
+ const uploads = new UploadStore(path14.join(path14.dirname(pm.statePath), "uploads"));
2815
3045
  const inbox = new Inbox();
2816
3046
  const auto = new AutoAnswerer({
2817
3047
  inbox,
2818
- statePath: path12.join(path12.dirname(pm.statePath), "orchestrator.json"),
3048
+ statePath: path14.join(path14.dirname(pm.statePath), "orchestrator.json"),
2819
3049
  context: (id) => {
2820
3050
  const s = pm.findSession(id);
2821
3051
  if (!s) return null;
@@ -2856,7 +3086,7 @@ async function main() {
2856
3086
  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
3087
  }
2858
3088
  if (args.updateCheck) {
2859
- void checkForUpdate(path12.join(path12.dirname(pm.statePath), "update-check.json")).then((latest) => {
3089
+ void checkForUpdate(path14.join(path14.dirname(pm.statePath), "update-check.json")).then((latest) => {
2860
3090
  if (!latest) return;
2861
3091
  hub.setUpdate({ current: currentVersion(), latest });
2862
3092
  console.log(`update available: ${currentVersion()} -> ${latest} (npm i -g tring-chat)`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tring-chat",
3
- "version": "0.1.18",
3
+ "version": "0.1.19",
4
4
  "description": "Focus-centred terminal deck for agentic work \u2014 16 live terminals around one focus, green when an agent is done",
5
5
  "keywords": [
6
6
  "terminal",