tring-chat 0.1.0
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/LICENSE +21 -0
- package/README.md +325 -0
- package/dist/tring.js +1504 -0
- package/dist/web/assets/index-BftoNEAK.js +66 -0
- package/dist/web/assets/index-CNNs5rrz.css +32 -0
- package/dist/web/assets/inter-cyrillic-400-normal-HOLc17fK.woff +0 -0
- package/dist/web/assets/inter-cyrillic-400-normal-obahsSVq.woff2 +0 -0
- package/dist/web/assets/inter-cyrillic-600-normal-4D_pXhcN.woff +0 -0
- package/dist/web/assets/inter-cyrillic-600-normal-CWCymEST.woff2 +0 -0
- package/dist/web/assets/inter-cyrillic-ext-400-normal-BQZuk6qB.woff2 +0 -0
- package/dist/web/assets/inter-cyrillic-ext-400-normal-DQukG94-.woff +0 -0
- package/dist/web/assets/inter-cyrillic-ext-600-normal-Bcila6Z-.woff +0 -0
- package/dist/web/assets/inter-cyrillic-ext-600-normal-Dfes3d0z.woff2 +0 -0
- package/dist/web/assets/inter-greek-400-normal-B4URO6DV.woff2 +0 -0
- package/dist/web/assets/inter-greek-400-normal-q2sYcFCs.woff +0 -0
- package/dist/web/assets/inter-greek-600-normal-BZpKdvQh.woff +0 -0
- package/dist/web/assets/inter-greek-600-normal-plRanbMR.woff2 +0 -0
- package/dist/web/assets/inter-greek-ext-400-normal-DGGRlc-M.woff2 +0 -0
- package/dist/web/assets/inter-greek-ext-400-normal-KugGGMne.woff +0 -0
- package/dist/web/assets/inter-greek-ext-600-normal-B8X0CLgF.woff +0 -0
- package/dist/web/assets/inter-greek-ext-600-normal-DRtmH8MT.woff2 +0 -0
- package/dist/web/assets/inter-latin-400-normal-C38fXH4l.woff2 +0 -0
- package/dist/web/assets/inter-latin-400-normal-CyCys3Eg.woff +0 -0
- package/dist/web/assets/inter-latin-600-normal-CiBQ2DWP.woff +0 -0
- package/dist/web/assets/inter-latin-600-normal-LgqL8muc.woff2 +0 -0
- package/dist/web/assets/inter-latin-ext-400-normal-77YHD8bZ.woff +0 -0
- package/dist/web/assets/inter-latin-ext-400-normal-C1nco2VV.woff2 +0 -0
- package/dist/web/assets/inter-latin-ext-600-normal-CIVaiw4L.woff +0 -0
- package/dist/web/assets/inter-latin-ext-600-normal-D2bJ5OIk.woff2 +0 -0
- package/dist/web/assets/inter-vietnamese-400-normal-Bbgyi5SW.woff +0 -0
- package/dist/web/assets/inter-vietnamese-400-normal-DMkecbls.woff2 +0 -0
- package/dist/web/assets/inter-vietnamese-600-normal-BuLX-rYi.woff +0 -0
- package/dist/web/assets/inter-vietnamese-600-normal-Cc8MFFhd.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
- package/dist/web/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
- package/dist/web/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
- package/dist/web/index.html +19 -0
- package/package.json +52 -0
package/dist/tring.js
ADDED
|
@@ -0,0 +1,1504 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
5
|
+
import { createServer } from "node:http";
|
|
6
|
+
import path5 from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { WebSocketServer } from "ws";
|
|
9
|
+
|
|
10
|
+
// ../shared/src/protocol.ts
|
|
11
|
+
var DEFAULT_PORT = 7331;
|
|
12
|
+
var DEFAULT_HOST = "127.0.0.1";
|
|
13
|
+
var DEFAULT_SCROLLBACK = 5e3;
|
|
14
|
+
function encodeOutput(id, data) {
|
|
15
|
+
const head = new TextEncoder().encode(id + "\0");
|
|
16
|
+
const out = new Uint8Array(head.length + data.length);
|
|
17
|
+
out.set(head, 0);
|
|
18
|
+
out.set(data, head.length);
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ../shared/src/status.ts
|
|
23
|
+
var SUSTAINED_MS = 1500;
|
|
24
|
+
var SUSTAINED_BYTES = 2048;
|
|
25
|
+
var BURST_GAP_MS = SUSTAINED_MS;
|
|
26
|
+
var DEFAULT_IDLE_MS = 3e3;
|
|
27
|
+
var NOTABLE_BUSY_MS = 1e4;
|
|
28
|
+
var ActivityTracker = class {
|
|
29
|
+
status = "idle";
|
|
30
|
+
since;
|
|
31
|
+
exitCode = null;
|
|
32
|
+
/**
|
|
33
|
+
* Whether the current `done` is worth interrupting someone for. True when an
|
|
34
|
+
* explicit signal said so, or when the session had been working long enough
|
|
35
|
+
* that falling quiet is meaningful.
|
|
36
|
+
*/
|
|
37
|
+
notable = false;
|
|
38
|
+
idleMs;
|
|
39
|
+
busyStartedAt = null;
|
|
40
|
+
burstStart = null;
|
|
41
|
+
burstBytes = 0;
|
|
42
|
+
lastOutput = null;
|
|
43
|
+
constructor(now, idleMs = DEFAULT_IDLE_MS) {
|
|
44
|
+
this.since = now;
|
|
45
|
+
this.idleMs = idleMs;
|
|
46
|
+
}
|
|
47
|
+
/** PTY produced `bytes` of output. */
|
|
48
|
+
output(bytes, now) {
|
|
49
|
+
if (this.status === "exited") return;
|
|
50
|
+
if (this.lastOutput !== null && now - this.lastOutput > BURST_GAP_MS) {
|
|
51
|
+
this.resetBurst();
|
|
52
|
+
}
|
|
53
|
+
this.lastOutput = now;
|
|
54
|
+
if (this.status !== "idle") return;
|
|
55
|
+
if (this.burstStart === null) this.burstStart = now;
|
|
56
|
+
this.burstBytes += bytes;
|
|
57
|
+
if (now - this.burstStart >= SUSTAINED_MS || this.burstBytes >= SUSTAINED_BYTES) {
|
|
58
|
+
this.transition("busy", now);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** User typed into this session. Only the focused session receives input. */
|
|
62
|
+
input(now) {
|
|
63
|
+
this.resetBurst();
|
|
64
|
+
if (this.status === "done") this.transition("idle", now);
|
|
65
|
+
}
|
|
66
|
+
/** OSC 133;C — a command started. */
|
|
67
|
+
commandStart(now) {
|
|
68
|
+
if (this.status === "idle") this.transition("busy", now);
|
|
69
|
+
}
|
|
70
|
+
/** OSC 133;D — a command ended. */
|
|
71
|
+
commandEnd(now) {
|
|
72
|
+
this.finish(now);
|
|
73
|
+
}
|
|
74
|
+
/** BEL (0x07). */
|
|
75
|
+
bell(now) {
|
|
76
|
+
this.finish(now);
|
|
77
|
+
}
|
|
78
|
+
/** POST /api/sessions/:id/done, e.g. the Claude Code Stop hook. */
|
|
79
|
+
hook(now) {
|
|
80
|
+
this.finish(now);
|
|
81
|
+
}
|
|
82
|
+
/** Explicit "mark seen" from the picker. */
|
|
83
|
+
ack(now) {
|
|
84
|
+
if (this.status === "done") this.transition("idle", now);
|
|
85
|
+
}
|
|
86
|
+
exit(code, now) {
|
|
87
|
+
this.exitCode = code;
|
|
88
|
+
this.transition("exited", now);
|
|
89
|
+
}
|
|
90
|
+
/** Called on a timer; detects the quiet period that ends a busy session. */
|
|
91
|
+
tick(now) {
|
|
92
|
+
if (this.status !== "busy") return;
|
|
93
|
+
if (this.lastOutput === null) return;
|
|
94
|
+
if (now - this.lastOutput < this.idleMs) return;
|
|
95
|
+
this.notable = this.busyStartedAt !== null && now - this.busyStartedAt >= NOTABLE_BUSY_MS;
|
|
96
|
+
this.transition("done", now);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* `done` is only ever entered from `busy` (spec §4.2): if nothing happened,
|
|
100
|
+
* there is nothing to report. This means an explicit signal that arrives
|
|
101
|
+
* while idle — a Stop hook after a reply too short to register as sustained
|
|
102
|
+
* output, or OSC 133;D after `echo hi` — is deliberately ignored. Those are
|
|
103
|
+
* the cases where a green tile would be noise, not news.
|
|
104
|
+
*/
|
|
105
|
+
finish(now) {
|
|
106
|
+
if (this.status !== "busy") return;
|
|
107
|
+
this.notable = true;
|
|
108
|
+
this.transition("done", now);
|
|
109
|
+
}
|
|
110
|
+
transition(status, now) {
|
|
111
|
+
if (this.status === status) return;
|
|
112
|
+
if (status === "busy") this.busyStartedAt = now;
|
|
113
|
+
if (status === "idle" || status === "busy") this.notable = false;
|
|
114
|
+
this.status = status;
|
|
115
|
+
this.since = now;
|
|
116
|
+
this.resetBurst();
|
|
117
|
+
}
|
|
118
|
+
resetBurst() {
|
|
119
|
+
this.burstStart = null;
|
|
120
|
+
this.burstBytes = 0;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
// src/project-manager.ts
|
|
125
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
126
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
127
|
+
import os from "node:os";
|
|
128
|
+
import path from "node:path";
|
|
129
|
+
|
|
130
|
+
// src/session-manager.ts
|
|
131
|
+
import { randomUUID } from "node:crypto";
|
|
132
|
+
|
|
133
|
+
// src/session.ts
|
|
134
|
+
import { readlinkSync } from "node:fs";
|
|
135
|
+
import { createRequire } from "node:module";
|
|
136
|
+
import { spawn } from "node-pty";
|
|
137
|
+
|
|
138
|
+
// src/snapshot.ts
|
|
139
|
+
function snapshot(term) {
|
|
140
|
+
const buf = term.buffer.active;
|
|
141
|
+
const rows = [];
|
|
142
|
+
for (let y = 0; y < term.rows; y++) {
|
|
143
|
+
const line = buf.getLine(buf.viewportY + y);
|
|
144
|
+
const out = [];
|
|
145
|
+
if (line) {
|
|
146
|
+
let run = null;
|
|
147
|
+
for (let x = 0; x < term.cols; x++) {
|
|
148
|
+
const cell = line.getCell(x);
|
|
149
|
+
if (!cell) break;
|
|
150
|
+
if (cell.getWidth() === 0) continue;
|
|
151
|
+
const text = cell.getChars() || " ";
|
|
152
|
+
const fg = cell.isFgDefault() ? -1 : cell.getFgColor();
|
|
153
|
+
const bg = cell.isBgDefault() ? -1 : cell.getBgColor();
|
|
154
|
+
const bold = cell.isBold() !== 0;
|
|
155
|
+
if (run && run.fg === fg && run.bg === bg && run.bold === bold) {
|
|
156
|
+
run.text += text;
|
|
157
|
+
} else {
|
|
158
|
+
run = { text, fg, bg, bold };
|
|
159
|
+
out.push(run);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
while (out.length > 0) {
|
|
163
|
+
const last = out[out.length - 1];
|
|
164
|
+
if (last.fg !== -1 || last.bg !== -1 || last.bold) break;
|
|
165
|
+
last.text = last.text.replace(/\s+$/, "");
|
|
166
|
+
if (last.text !== "") break;
|
|
167
|
+
out.pop();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
rows.push(out);
|
|
171
|
+
}
|
|
172
|
+
return { cols: term.cols, rows };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/shell.ts
|
|
176
|
+
function base(shell) {
|
|
177
|
+
const name = shell.split(/[\\/]/).pop() ?? shell;
|
|
178
|
+
return name.toLowerCase().replace(/\.exe$/, "");
|
|
179
|
+
}
|
|
180
|
+
function defaultShell() {
|
|
181
|
+
const override = process.env["TRING_SHELL"];
|
|
182
|
+
if (override) return override;
|
|
183
|
+
if (process.platform === "win32") {
|
|
184
|
+
return "powershell.exe";
|
|
185
|
+
}
|
|
186
|
+
return process.env["SHELL"] ?? "/bin/bash";
|
|
187
|
+
}
|
|
188
|
+
function commandArgs(shell, command) {
|
|
189
|
+
switch (base(shell)) {
|
|
190
|
+
case "powershell":
|
|
191
|
+
case "pwsh":
|
|
192
|
+
return ["-NoLogo", "-Command", command];
|
|
193
|
+
case "cmd":
|
|
194
|
+
return ["/c", command];
|
|
195
|
+
case "wsl":
|
|
196
|
+
return ["-e", "bash", "-lc", command];
|
|
197
|
+
default:
|
|
198
|
+
return ["-c", command];
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function usesPosixCd(shell) {
|
|
202
|
+
const b = base(shell);
|
|
203
|
+
return b !== "cmd" && b !== "powershell" && b !== "pwsh";
|
|
204
|
+
}
|
|
205
|
+
function shQuote(p) {
|
|
206
|
+
return `'${p.replace(/'/g, `'\\''`)}'`;
|
|
207
|
+
}
|
|
208
|
+
function interactiveArgs(shell) {
|
|
209
|
+
switch (base(shell)) {
|
|
210
|
+
case "powershell":
|
|
211
|
+
case "pwsh":
|
|
212
|
+
return ["-NoLogo"];
|
|
213
|
+
default:
|
|
214
|
+
return [];
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// src/session.ts
|
|
219
|
+
var require2 = createRequire(import.meta.url);
|
|
220
|
+
var { Terminal } = require2("@xterm/headless");
|
|
221
|
+
var { SerializeAddon } = require2("@xterm/addon-serialize");
|
|
222
|
+
var CWD_POLL_MS = 2e3;
|
|
223
|
+
var CWD_ENFORCE_MS = 400;
|
|
224
|
+
var Session = class {
|
|
225
|
+
id;
|
|
226
|
+
projectId;
|
|
227
|
+
slot;
|
|
228
|
+
command;
|
|
229
|
+
name;
|
|
230
|
+
color;
|
|
231
|
+
title = null;
|
|
232
|
+
tracker;
|
|
233
|
+
onData = null;
|
|
234
|
+
onStatusChange = null;
|
|
235
|
+
onExit = null;
|
|
236
|
+
pty;
|
|
237
|
+
term;
|
|
238
|
+
serializer;
|
|
239
|
+
lastSnapshot = null;
|
|
240
|
+
disposed = false;
|
|
241
|
+
spawnCwd;
|
|
242
|
+
liveCwd = null;
|
|
243
|
+
lastCwdPoll = 0;
|
|
244
|
+
enforceTimer = null;
|
|
245
|
+
hasInput = false;
|
|
246
|
+
/** Fires when the shell moves, so the new location gets persisted. */
|
|
247
|
+
onCwdChange = null;
|
|
248
|
+
/**
|
|
249
|
+
* Where the shell *is*, not where it started. A session spawned in a project
|
|
250
|
+
* root that the developer then `cd`s out of must come back to where they
|
|
251
|
+
* were working, not to the root.
|
|
252
|
+
*/
|
|
253
|
+
get cwd() {
|
|
254
|
+
return this.liveCwd ?? this.spawnCwd;
|
|
255
|
+
}
|
|
256
|
+
constructor(opts) {
|
|
257
|
+
this.id = opts.id;
|
|
258
|
+
this.projectId = opts.projectId;
|
|
259
|
+
this.slot = opts.slot;
|
|
260
|
+
this.spawnCwd = opts.cwd;
|
|
261
|
+
this.command = opts.command ?? null;
|
|
262
|
+
this.name = opts.name ?? null;
|
|
263
|
+
this.color = opts.color ?? null;
|
|
264
|
+
this.tracker = new ActivityTracker(Date.now(), opts.idleMs ?? DEFAULT_IDLE_MS);
|
|
265
|
+
const shell = opts.shell ?? defaultShell();
|
|
266
|
+
const env = {};
|
|
267
|
+
for (const [k, v] of Object.entries(process.env)) if (v !== void 0) env[k] = v;
|
|
268
|
+
env["TRING_SESSION_ID"] = this.id;
|
|
269
|
+
env["TRING_SLOT"] = String(this.slot);
|
|
270
|
+
env["TRING_PROJECT"] = opts.projectName;
|
|
271
|
+
env["TRING_URL"] = opts.url;
|
|
272
|
+
const autorun = opts.autorun ?? true;
|
|
273
|
+
const args = this.command && autorun ? commandArgs(shell, this.command) : interactiveArgs(shell);
|
|
274
|
+
this.pty = spawn(shell, args, {
|
|
275
|
+
name: "xterm-256color",
|
|
276
|
+
cols: 120,
|
|
277
|
+
rows: 36,
|
|
278
|
+
cwd: this.spawnCwd,
|
|
279
|
+
env
|
|
280
|
+
});
|
|
281
|
+
this.term = new Terminal({
|
|
282
|
+
cols: 120,
|
|
283
|
+
rows: 36,
|
|
284
|
+
scrollback: opts.scrollback ?? DEFAULT_SCROLLBACK,
|
|
285
|
+
allowProposedApi: true
|
|
286
|
+
});
|
|
287
|
+
this.serializer = new SerializeAddon();
|
|
288
|
+
this.term.loadAddon(this.serializer);
|
|
289
|
+
this.term.onBell(() => this.signal((t, now) => t.bell(now)));
|
|
290
|
+
this.term.onTitleChange((title) => {
|
|
291
|
+
this.title = title;
|
|
292
|
+
this.onStatusChange?.();
|
|
293
|
+
});
|
|
294
|
+
this.term.parser.registerOscHandler(7, (data) => {
|
|
295
|
+
try {
|
|
296
|
+
const url = new URL(data);
|
|
297
|
+
if (url.protocol === "file:") this.setCwd(decodeURIComponent(url.pathname));
|
|
298
|
+
} catch {
|
|
299
|
+
}
|
|
300
|
+
return true;
|
|
301
|
+
});
|
|
302
|
+
this.term.parser.registerOscHandler(133, (data) => {
|
|
303
|
+
const kind = data.split(";")[0];
|
|
304
|
+
if (kind === "C") this.signal((t, now) => t.commandStart(now));
|
|
305
|
+
else if (kind === "D") this.signal((t, now) => t.commandEnd(now));
|
|
306
|
+
return true;
|
|
307
|
+
});
|
|
308
|
+
this.pty.onData((chunk) => {
|
|
309
|
+
this.signal((t, now) => t.output(Buffer.byteLength(chunk), now));
|
|
310
|
+
this.term.write(chunk);
|
|
311
|
+
this.onData?.(chunk);
|
|
312
|
+
});
|
|
313
|
+
if (!(this.command && autorun) && usesPosixCd(shell)) {
|
|
314
|
+
this.enforceTimer = setTimeout(() => this.enforceCwd(), CWD_ENFORCE_MS);
|
|
315
|
+
this.enforceTimer.unref?.();
|
|
316
|
+
}
|
|
317
|
+
this.pty.onExit(({ exitCode }) => {
|
|
318
|
+
this.signal((t, now) => t.exit(exitCode, now));
|
|
319
|
+
this.onExit?.(exitCode);
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
write(data) {
|
|
323
|
+
if (this.disposed) return;
|
|
324
|
+
this.hasInput = true;
|
|
325
|
+
this.signal((t, now) => t.input(now));
|
|
326
|
+
this.pty.write(data);
|
|
327
|
+
}
|
|
328
|
+
resize(cols, rows) {
|
|
329
|
+
if (this.disposed || cols < 1 || rows < 1) return;
|
|
330
|
+
this.pty.resize(cols, rows);
|
|
331
|
+
this.term.resize(cols, rows);
|
|
332
|
+
}
|
|
333
|
+
/** Full buffer including scrollback, for replay on focus or reconnect. */
|
|
334
|
+
serialize() {
|
|
335
|
+
return this.serializer.serialize({ scrollback: this.term.options.scrollback ?? 0 });
|
|
336
|
+
}
|
|
337
|
+
/** Returns null when the visible buffer has not changed since last time. */
|
|
338
|
+
/**
|
|
339
|
+
* The current screen, ignoring the change gate below.
|
|
340
|
+
*
|
|
341
|
+
* A client that has just attached has never seen this session, however long
|
|
342
|
+
* it has been quiet — and a shell sitting at its prompt never changes again,
|
|
343
|
+
* so waiting for the gate to open means a black tile forever.
|
|
344
|
+
*/
|
|
345
|
+
snapshotNow() {
|
|
346
|
+
return snapshot(this.term);
|
|
347
|
+
}
|
|
348
|
+
/** Only when the screen actually changed, which is what keeps 16 tiles cheap. */
|
|
349
|
+
takeSnapshot() {
|
|
350
|
+
const shot = snapshot(this.term);
|
|
351
|
+
const key = JSON.stringify(shot.rows);
|
|
352
|
+
if (key === this.lastSnapshot) return null;
|
|
353
|
+
this.lastSnapshot = key;
|
|
354
|
+
return shot;
|
|
355
|
+
}
|
|
356
|
+
ack() {
|
|
357
|
+
this.signal((t, now) => t.ack(now));
|
|
358
|
+
}
|
|
359
|
+
hook() {
|
|
360
|
+
this.signal((t, now) => t.hook(now));
|
|
361
|
+
}
|
|
362
|
+
tick(now) {
|
|
363
|
+
this.signal((t) => t.tick(now));
|
|
364
|
+
if (now - this.lastCwdPoll >= CWD_POLL_MS) {
|
|
365
|
+
this.lastCwdPoll = now;
|
|
366
|
+
this.pollCwd();
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Reads the shell's real working directory from /proc, which needs no
|
|
371
|
+
* cooperation from the shell at all — the common case on Linux and WSL,
|
|
372
|
+
* where a stock bash emits no OSC 7. Elsewhere OSC 7 is the only source.
|
|
373
|
+
*/
|
|
374
|
+
pollCwd() {
|
|
375
|
+
if (process.platform !== "linux" || this.disposed) return;
|
|
376
|
+
try {
|
|
377
|
+
this.setCwd(readlinkSync(`/proc/${this.pty.pid}/cwd`));
|
|
378
|
+
} catch {
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/** Runs once, only if the shell is not where it was asked to be. */
|
|
382
|
+
enforceCwd() {
|
|
383
|
+
if (this.disposed || this.hasInput || process.platform !== "linux") return;
|
|
384
|
+
let actual;
|
|
385
|
+
try {
|
|
386
|
+
actual = readlinkSync(`/proc/${this.pty.pid}/cwd`);
|
|
387
|
+
} catch {
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
if (actual === this.spawnCwd) return;
|
|
391
|
+
this.pty.write(`cd -- ${shQuote(this.spawnCwd)}
|
|
392
|
+
`);
|
|
393
|
+
}
|
|
394
|
+
setCwd(next) {
|
|
395
|
+
if (!next || next === this.cwd) return;
|
|
396
|
+
this.liveCwd = next;
|
|
397
|
+
this.onCwdChange?.();
|
|
398
|
+
}
|
|
399
|
+
kill() {
|
|
400
|
+
if (this.disposed) return;
|
|
401
|
+
try {
|
|
402
|
+
this.pty.kill();
|
|
403
|
+
} catch {
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
dispose() {
|
|
407
|
+
this.disposed = true;
|
|
408
|
+
if (this.enforceTimer) clearTimeout(this.enforceTimer);
|
|
409
|
+
this.enforceTimer = null;
|
|
410
|
+
this.kill();
|
|
411
|
+
this.term.dispose();
|
|
412
|
+
}
|
|
413
|
+
info() {
|
|
414
|
+
return {
|
|
415
|
+
id: this.id,
|
|
416
|
+
projectId: this.projectId,
|
|
417
|
+
slot: this.slot,
|
|
418
|
+
name: this.name,
|
|
419
|
+
title: this.title,
|
|
420
|
+
cwd: this.cwd,
|
|
421
|
+
command: this.command,
|
|
422
|
+
color: this.color,
|
|
423
|
+
status: this.tracker.status,
|
|
424
|
+
since: this.tracker.since,
|
|
425
|
+
exitCode: this.tracker.exitCode
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
/** Runs a tracker mutation and fires onStatusChange only on a real change. */
|
|
429
|
+
signal(fn) {
|
|
430
|
+
const before = this.tracker.status;
|
|
431
|
+
fn(this.tracker, Date.now());
|
|
432
|
+
if (this.tracker.status !== before) this.onStatusChange?.();
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
// src/session-manager.ts
|
|
437
|
+
var SLOT_COUNT = 16;
|
|
438
|
+
var HEX = /^#[0-9a-f]{6}$/i;
|
|
439
|
+
var SessionManager = class {
|
|
440
|
+
constructor(opts) {
|
|
441
|
+
this.opts = opts;
|
|
442
|
+
}
|
|
443
|
+
bySlot = /* @__PURE__ */ new Map();
|
|
444
|
+
byId = /* @__PURE__ */ new Map();
|
|
445
|
+
onSessionData = null;
|
|
446
|
+
onSessionStatus = null;
|
|
447
|
+
onSessionExit = null;
|
|
448
|
+
onStructureChange = null;
|
|
449
|
+
create(spec = {}) {
|
|
450
|
+
const slot = spec.slot ?? this.firstEmptySlot();
|
|
451
|
+
if (slot === null) throw new Error("all 16 slots are full");
|
|
452
|
+
if (slot < 1 || slot > SLOT_COUNT) throw new Error(`slot ${slot} out of range`);
|
|
453
|
+
if (this.bySlot.has(slot)) throw new Error(`slot ${slot} is occupied`);
|
|
454
|
+
const session = new Session({
|
|
455
|
+
// Globally unique across every project, which is what lets the HTTP API
|
|
456
|
+
// and the Claude Code Stop hook address a session without knowing its
|
|
457
|
+
// project (spec §4.5).
|
|
458
|
+
id: randomUUID(),
|
|
459
|
+
projectId: this.opts.projectId,
|
|
460
|
+
projectName: this.opts.projectName,
|
|
461
|
+
slot,
|
|
462
|
+
cwd: spec.cwd ?? this.opts.root,
|
|
463
|
+
command: spec.command ?? null,
|
|
464
|
+
name: spec.name ?? null,
|
|
465
|
+
color: HEX.test(spec.color ?? "") ? spec.color : null,
|
|
466
|
+
url: this.opts.url,
|
|
467
|
+
scrollback: this.opts.scrollback,
|
|
468
|
+
idleMs: this.opts.idleMs,
|
|
469
|
+
...this.opts.shell ? { shell: this.opts.shell } : {},
|
|
470
|
+
autorun: spec.autorun
|
|
471
|
+
});
|
|
472
|
+
session.onData = (data) => this.onSessionData?.(session, data);
|
|
473
|
+
session.onStatusChange = () => this.onSessionStatus?.(session);
|
|
474
|
+
session.onExit = (code) => this.onSessionExit?.(session, code);
|
|
475
|
+
session.onCwdChange = () => this.onStructureChange?.();
|
|
476
|
+
this.bySlot.set(slot, session);
|
|
477
|
+
this.byId.set(session.id, session);
|
|
478
|
+
this.onStructureChange?.();
|
|
479
|
+
return session;
|
|
480
|
+
}
|
|
481
|
+
get(id) {
|
|
482
|
+
return this.byId.get(id);
|
|
483
|
+
}
|
|
484
|
+
at(slot) {
|
|
485
|
+
return this.bySlot.get(slot);
|
|
486
|
+
}
|
|
487
|
+
list() {
|
|
488
|
+
return [...this.bySlot.entries()].sort((a, b) => a[0] - b[0]).map(([, s]) => s);
|
|
489
|
+
}
|
|
490
|
+
rename(id, name) {
|
|
491
|
+
const s = this.byId.get(id);
|
|
492
|
+
if (!s) return;
|
|
493
|
+
s.name = name;
|
|
494
|
+
this.onStructureChange?.();
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* The tint ends up in a CSS custom property in the browser, and arrives from
|
|
498
|
+
* a socket, so anything but a plain hex value clears the colour rather than
|
|
499
|
+
* being passed along. Every path that sets a colour routes through here.
|
|
500
|
+
*/
|
|
501
|
+
setColor(id, color) {
|
|
502
|
+
const s = this.byId.get(id);
|
|
503
|
+
if (!s) return;
|
|
504
|
+
s.color = color !== null && HEX.test(color) ? color : null;
|
|
505
|
+
this.onStructureChange?.();
|
|
506
|
+
}
|
|
507
|
+
kill(id) {
|
|
508
|
+
const s = this.byId.get(id);
|
|
509
|
+
if (!s) return;
|
|
510
|
+
s.dispose();
|
|
511
|
+
this.bySlot.delete(s.slot);
|
|
512
|
+
this.byId.delete(id);
|
|
513
|
+
this.onStructureChange?.();
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Explicit user-initiated respawn of a dead tile. Unlike daemon restore this
|
|
517
|
+
* *does* re-run the recorded command, because the user asked for it.
|
|
518
|
+
*/
|
|
519
|
+
respawn(id) {
|
|
520
|
+
const old = this.byId.get(id);
|
|
521
|
+
if (!old) return void 0;
|
|
522
|
+
const spec = {
|
|
523
|
+
slot: old.slot,
|
|
524
|
+
cwd: old.cwd,
|
|
525
|
+
command: old.command,
|
|
526
|
+
name: old.name,
|
|
527
|
+
color: old.color,
|
|
528
|
+
autorun: true
|
|
529
|
+
};
|
|
530
|
+
this.kill(id);
|
|
531
|
+
return this.create(spec);
|
|
532
|
+
}
|
|
533
|
+
tick(now) {
|
|
534
|
+
for (const s of this.bySlot.values()) s.tick(now);
|
|
535
|
+
}
|
|
536
|
+
disposeAll() {
|
|
537
|
+
for (const s of this.bySlot.values()) s.dispose();
|
|
538
|
+
this.bySlot.clear();
|
|
539
|
+
this.byId.clear();
|
|
540
|
+
}
|
|
541
|
+
firstEmptySlot() {
|
|
542
|
+
for (let slot = 1; slot <= SLOT_COUNT; slot++) if (!this.bySlot.has(slot)) return slot;
|
|
543
|
+
return null;
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
// src/project-manager.ts
|
|
548
|
+
function defaultStatePath() {
|
|
549
|
+
const base2 = process.env["XDG_CONFIG_HOME"] ?? path.join(os.homedir(), ".config");
|
|
550
|
+
return path.join(base2, "tring", "projects.json");
|
|
551
|
+
}
|
|
552
|
+
var ProjectManager = class _ProjectManager {
|
|
553
|
+
constructor(opts) {
|
|
554
|
+
this.opts = opts;
|
|
555
|
+
}
|
|
556
|
+
entries = /* @__PURE__ */ new Map();
|
|
557
|
+
activeId = null;
|
|
558
|
+
timer = null;
|
|
559
|
+
writing = Promise.resolve();
|
|
560
|
+
onChange = null;
|
|
561
|
+
onSessionData = null;
|
|
562
|
+
onSessionStatus = null;
|
|
563
|
+
onSessionExit = null;
|
|
564
|
+
static async open(opts) {
|
|
565
|
+
const pm = new _ProjectManager(opts);
|
|
566
|
+
await pm.load();
|
|
567
|
+
pm.timer = setInterval(() => pm.tick(), opts.tickMs ?? 500);
|
|
568
|
+
pm.timer.unref?.();
|
|
569
|
+
return pm;
|
|
570
|
+
}
|
|
571
|
+
get statePath() {
|
|
572
|
+
return this.opts.statePath ?? defaultStatePath();
|
|
573
|
+
}
|
|
574
|
+
get activeProjectId() {
|
|
575
|
+
return this.activeId;
|
|
576
|
+
}
|
|
577
|
+
list() {
|
|
578
|
+
return [...this.entries.values()].map((e) => ({
|
|
579
|
+
id: e.id,
|
|
580
|
+
name: e.name,
|
|
581
|
+
root: e.root,
|
|
582
|
+
// A project that has never been activated has nothing running, so it
|
|
583
|
+
// truthfully reports no sessions and a zero done-count.
|
|
584
|
+
sessions: e.manager?.list().map((s) => s.info()) ?? []
|
|
585
|
+
}));
|
|
586
|
+
}
|
|
587
|
+
createProject(name, root) {
|
|
588
|
+
const id = randomUUID2();
|
|
589
|
+
this.entries.set(id, { id, name, root, manager: null, pending: [] });
|
|
590
|
+
this.activate(id);
|
|
591
|
+
return id;
|
|
592
|
+
}
|
|
593
|
+
renameProject(id, name) {
|
|
594
|
+
const e = this.entries.get(id);
|
|
595
|
+
if (!e) return;
|
|
596
|
+
e.name = name;
|
|
597
|
+
this.changed();
|
|
598
|
+
}
|
|
599
|
+
deleteProject(id) {
|
|
600
|
+
const e = this.entries.get(id);
|
|
601
|
+
if (!e) return;
|
|
602
|
+
e.manager?.disposeAll();
|
|
603
|
+
this.entries.delete(id);
|
|
604
|
+
if (this.activeId === id) {
|
|
605
|
+
const next = this.entries.keys().next();
|
|
606
|
+
this.activeId = next.done ? null : next.value;
|
|
607
|
+
if (this.activeId) this.activate(this.activeId);
|
|
608
|
+
}
|
|
609
|
+
this.changed();
|
|
610
|
+
}
|
|
611
|
+
activate(id) {
|
|
612
|
+
const e = this.entries.get(id);
|
|
613
|
+
if (!e) return null;
|
|
614
|
+
this.activeId = id;
|
|
615
|
+
if (!e.manager) {
|
|
616
|
+
e.manager = this.spawnManager(e);
|
|
617
|
+
for (const rec of e.pending) {
|
|
618
|
+
e.manager.create({ ...rec, autorun: false });
|
|
619
|
+
}
|
|
620
|
+
e.pending = [];
|
|
621
|
+
}
|
|
622
|
+
this.changed();
|
|
623
|
+
return e.manager;
|
|
624
|
+
}
|
|
625
|
+
managerFor(id) {
|
|
626
|
+
return this.entries.get(id)?.manager ?? null;
|
|
627
|
+
}
|
|
628
|
+
activeManager() {
|
|
629
|
+
return this.activeId ? this.managerFor(this.activeId) : null;
|
|
630
|
+
}
|
|
631
|
+
create(projectId, spec) {
|
|
632
|
+
const id = projectId ?? this.activeId;
|
|
633
|
+
if (!id) return null;
|
|
634
|
+
const mgr = this.managerFor(id) ?? this.activate(id);
|
|
635
|
+
return mgr ? mgr.create(spec) : null;
|
|
636
|
+
}
|
|
637
|
+
/** Session lookup by globally unique id, across every live project. */
|
|
638
|
+
findSession(sessionId) {
|
|
639
|
+
for (const e of this.entries.values()) {
|
|
640
|
+
const s = e.manager?.get(sessionId);
|
|
641
|
+
if (s) return s;
|
|
642
|
+
}
|
|
643
|
+
return void 0;
|
|
644
|
+
}
|
|
645
|
+
findManager(sessionId) {
|
|
646
|
+
for (const e of this.entries.values()) {
|
|
647
|
+
if (e.manager?.get(sessionId)) return e.manager;
|
|
648
|
+
}
|
|
649
|
+
return void 0;
|
|
650
|
+
}
|
|
651
|
+
async dispose() {
|
|
652
|
+
if (this.timer) clearInterval(this.timer);
|
|
653
|
+
this.timer = null;
|
|
654
|
+
for (const e of this.entries.values()) e.manager?.disposeAll();
|
|
655
|
+
await this.writing;
|
|
656
|
+
}
|
|
657
|
+
spawnManager(e) {
|
|
658
|
+
const mgr = new SessionManager({
|
|
659
|
+
projectId: e.id,
|
|
660
|
+
projectName: e.name,
|
|
661
|
+
root: e.root,
|
|
662
|
+
url: this.opts.url,
|
|
663
|
+
scrollback: this.opts.scrollback,
|
|
664
|
+
idleMs: this.opts.idleMs,
|
|
665
|
+
...this.opts.shell ? { shell: this.opts.shell } : {}
|
|
666
|
+
});
|
|
667
|
+
mgr.onSessionData = (s, d) => this.onSessionData?.(s, d);
|
|
668
|
+
mgr.onSessionStatus = (s) => this.onSessionStatus?.(s);
|
|
669
|
+
mgr.onSessionExit = (s, c) => {
|
|
670
|
+
this.onSessionExit?.(s, c);
|
|
671
|
+
this.changed();
|
|
672
|
+
};
|
|
673
|
+
mgr.onStructureChange = () => this.changed();
|
|
674
|
+
return mgr;
|
|
675
|
+
}
|
|
676
|
+
tick() {
|
|
677
|
+
const now = Date.now();
|
|
678
|
+
for (const e of this.entries.values()) e.manager?.tick(now);
|
|
679
|
+
}
|
|
680
|
+
changed() {
|
|
681
|
+
this.onChange?.();
|
|
682
|
+
void this.save();
|
|
683
|
+
}
|
|
684
|
+
snapshotState() {
|
|
685
|
+
return {
|
|
686
|
+
version: 1,
|
|
687
|
+
activeProjectId: this.activeId,
|
|
688
|
+
projects: [...this.entries.values()].map((e) => ({
|
|
689
|
+
id: e.id,
|
|
690
|
+
name: e.name,
|
|
691
|
+
root: e.root,
|
|
692
|
+
sessions: e.manager ? e.manager.list().map((s) => ({
|
|
693
|
+
slot: s.slot,
|
|
694
|
+
name: s.name,
|
|
695
|
+
cwd: s.cwd,
|
|
696
|
+
command: s.command,
|
|
697
|
+
color: s.color
|
|
698
|
+
})) : e.pending
|
|
699
|
+
}))
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
save() {
|
|
703
|
+
const state = this.snapshotState();
|
|
704
|
+
this.writing = this.writing.then(async () => {
|
|
705
|
+
await mkdir(path.dirname(this.statePath), { recursive: true });
|
|
706
|
+
await writeFile(this.statePath, JSON.stringify(state, null, 2), "utf8");
|
|
707
|
+
}).catch(() => {
|
|
708
|
+
});
|
|
709
|
+
return this.writing;
|
|
710
|
+
}
|
|
711
|
+
async load() {
|
|
712
|
+
let parsed;
|
|
713
|
+
try {
|
|
714
|
+
parsed = JSON.parse(await readFile(this.statePath, "utf8"));
|
|
715
|
+
} catch {
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.projects)) return;
|
|
719
|
+
for (const p of parsed.projects) {
|
|
720
|
+
this.entries.set(p.id, {
|
|
721
|
+
id: p.id,
|
|
722
|
+
name: p.name,
|
|
723
|
+
root: p.root,
|
|
724
|
+
manager: null,
|
|
725
|
+
pending: Array.isArray(p.sessions) ? p.sessions : []
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
const active = parsed.activeProjectId;
|
|
729
|
+
if (active && this.entries.has(active)) this.activate(active);
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
// src/http.ts
|
|
734
|
+
import { createReadStream } from "node:fs";
|
|
735
|
+
import { readdir as readdir2, stat as stat2 } from "node:fs/promises";
|
|
736
|
+
import os3 from "node:os";
|
|
737
|
+
import path3 from "node:path";
|
|
738
|
+
|
|
739
|
+
// src/usage.ts
|
|
740
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
741
|
+
import { readdir, readFile as readFile2, stat } from "node:fs/promises";
|
|
742
|
+
import os2 from "node:os";
|
|
743
|
+
import path2 from "node:path";
|
|
744
|
+
var WINDOW_MS = 5 * 36e5;
|
|
745
|
+
var WEEK_MS = 7 * 24 * 36e5;
|
|
746
|
+
var PRICES = [
|
|
747
|
+
["claude-fable-5", 10, 50],
|
|
748
|
+
["claude-mythos-5", 10, 50],
|
|
749
|
+
["claude-opus-", 5, 25],
|
|
750
|
+
["claude-sonnet-4-6", 3, 15],
|
|
751
|
+
["claude-sonnet-", 2, 10],
|
|
752
|
+
["claude-haiku-", 1, 5]
|
|
753
|
+
];
|
|
754
|
+
function defaultTranscriptDir() {
|
|
755
|
+
const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path2.join(os2.homedir(), ".claude");
|
|
756
|
+
return path2.join(base2, "projects");
|
|
757
|
+
}
|
|
758
|
+
var empty = () => ({ tokens: 0, cacheReadTokens: 0, cost: 0, messages: 0 });
|
|
759
|
+
function add(b, e) {
|
|
760
|
+
b.tokens += e.tokens;
|
|
761
|
+
b.cacheReadTokens += e.cacheReadTokens;
|
|
762
|
+
b.cost += e.cost;
|
|
763
|
+
b.messages += 1;
|
|
764
|
+
}
|
|
765
|
+
function priceOf(model) {
|
|
766
|
+
for (const [prefix, input, output] of PRICES) if (model.startsWith(prefix)) return [input, output];
|
|
767
|
+
return [0, 0];
|
|
768
|
+
}
|
|
769
|
+
async function scanUsage(dir, now) {
|
|
770
|
+
const seen = /* @__PURE__ */ new Set();
|
|
771
|
+
const entries = [];
|
|
772
|
+
const weekAgo = now - WEEK_MS;
|
|
773
|
+
for (const file of await transcripts(dir, weekAgo)) {
|
|
774
|
+
let text;
|
|
775
|
+
try {
|
|
776
|
+
text = await readFile2(file, "utf8");
|
|
777
|
+
} catch {
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
780
|
+
for (const line of text.split("\n")) {
|
|
781
|
+
if (!line.includes('"usage"')) continue;
|
|
782
|
+
let rec;
|
|
783
|
+
try {
|
|
784
|
+
rec = JSON.parse(line);
|
|
785
|
+
} catch {
|
|
786
|
+
continue;
|
|
787
|
+
}
|
|
788
|
+
const entry = toEntry(rec, seen);
|
|
789
|
+
if (entry && entry.at >= weekAgo) entries.push(entry);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
const report = {
|
|
793
|
+
limits: [],
|
|
794
|
+
limitsError: null,
|
|
795
|
+
window: { ...empty(), startedAt: null, resetsAt: null },
|
|
796
|
+
today: empty(),
|
|
797
|
+
week: empty(),
|
|
798
|
+
projects: [],
|
|
799
|
+
scannedAt: now
|
|
800
|
+
};
|
|
801
|
+
entries.sort((a, b) => a.at - b.at);
|
|
802
|
+
const blockStart = liveBlockStart(entries, now);
|
|
803
|
+
const dayStart = new Date(now).setHours(0, 0, 0, 0);
|
|
804
|
+
const byProject = /* @__PURE__ */ new Map();
|
|
805
|
+
for (const e of entries) {
|
|
806
|
+
add(report.week, e);
|
|
807
|
+
if (e.at >= dayStart) add(report.today, e);
|
|
808
|
+
if (blockStart !== null && e.at >= blockStart) add(report.window, e);
|
|
809
|
+
const p = byProject.get(e.project) ?? { name: e.project, tokens: 0, cost: 0 };
|
|
810
|
+
p.tokens += e.tokens;
|
|
811
|
+
p.cost += e.cost;
|
|
812
|
+
byProject.set(e.project, p);
|
|
813
|
+
}
|
|
814
|
+
if (blockStart !== null) {
|
|
815
|
+
report.window.startedAt = blockStart;
|
|
816
|
+
report.window.resetsAt = blockStart + WINDOW_MS;
|
|
817
|
+
}
|
|
818
|
+
report.projects = [...byProject.values()].sort((a, b) => b.tokens - a.tokens);
|
|
819
|
+
return report;
|
|
820
|
+
}
|
|
821
|
+
function toEntry(rec, seen) {
|
|
822
|
+
if (rec["type"] !== "assistant") return null;
|
|
823
|
+
const message = rec["message"];
|
|
824
|
+
const usage = message?.["usage"];
|
|
825
|
+
if (!usage) return null;
|
|
826
|
+
const id = String(message?.["id"] ?? rec["requestId"] ?? "");
|
|
827
|
+
if (!id || seen.has(id)) return null;
|
|
828
|
+
seen.add(id);
|
|
829
|
+
const at = Date.parse(String(rec["timestamp"] ?? ""));
|
|
830
|
+
if (Number.isNaN(at)) return null;
|
|
831
|
+
const input = usage["input_tokens"] ?? 0;
|
|
832
|
+
const output = usage["output_tokens"] ?? 0;
|
|
833
|
+
const creation = usage["cache_creation_input_tokens"] ?? 0;
|
|
834
|
+
const read = usage["cache_read_input_tokens"] ?? 0;
|
|
835
|
+
const [inPrice, outPrice] = priceOf(String(message?.["model"] ?? ""));
|
|
836
|
+
const cwd = String(rec["cwd"] ?? "");
|
|
837
|
+
return {
|
|
838
|
+
at,
|
|
839
|
+
project: cwd.split(/[/\\]/).filter(Boolean).pop() ?? "unknown",
|
|
840
|
+
tokens: input + output + creation,
|
|
841
|
+
cacheReadTokens: read,
|
|
842
|
+
cost: (input * inPrice + creation * inPrice * 1.25 + read * inPrice * 0.1 + output * outPrice) / 1e6
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
function liveBlockStart(entries, now) {
|
|
846
|
+
let start = null;
|
|
847
|
+
let prev = 0;
|
|
848
|
+
for (const e of entries) {
|
|
849
|
+
if (start === null || e.at - start >= WINDOW_MS || e.at - prev >= WINDOW_MS) start = e.at;
|
|
850
|
+
prev = e.at;
|
|
851
|
+
}
|
|
852
|
+
return start !== null && now - start < WINDOW_MS ? start : null;
|
|
853
|
+
}
|
|
854
|
+
async function transcripts(dir, since) {
|
|
855
|
+
let names;
|
|
856
|
+
try {
|
|
857
|
+
names = await readdir(dir, { recursive: true });
|
|
858
|
+
} catch {
|
|
859
|
+
return [];
|
|
860
|
+
}
|
|
861
|
+
const out = [];
|
|
862
|
+
for (const name of names) {
|
|
863
|
+
if (!name.endsWith(".jsonl")) continue;
|
|
864
|
+
const file = path2.join(dir, name);
|
|
865
|
+
try {
|
|
866
|
+
if ((await stat(file)).mtimeMs >= since) out.push(file);
|
|
867
|
+
} catch {
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
return out;
|
|
871
|
+
}
|
|
872
|
+
var LIMIT_LINE = /^Current ([^:]+):\s*(\d+)%\s*used(?:\s*·\s*resets\s*(.+?))?\s*$/;
|
|
873
|
+
function parseLimits(text) {
|
|
874
|
+
const out = [];
|
|
875
|
+
for (const line of text.split("\n")) {
|
|
876
|
+
const m = LIMIT_LINE.exec(line.trim());
|
|
877
|
+
if (!m) continue;
|
|
878
|
+
const label = m[1].trim();
|
|
879
|
+
out.push({
|
|
880
|
+
label: label.charAt(0).toUpperCase() + label.slice(1),
|
|
881
|
+
percent: Number(m[2]),
|
|
882
|
+
resets: m[3]?.trim() ?? null
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
return out;
|
|
886
|
+
}
|
|
887
|
+
function readLimits(timeoutMs = 3e4) {
|
|
888
|
+
const args = ["-p", "/usage", "--output-format", "json"];
|
|
889
|
+
const run = (cmd) => new Promise((resolve, reject) => {
|
|
890
|
+
const child = spawn2(cmd, args, { stdio: ["ignore", "pipe", "ignore"] });
|
|
891
|
+
let out = "";
|
|
892
|
+
let settled = false;
|
|
893
|
+
const timer = setTimeout(() => {
|
|
894
|
+
settled = true;
|
|
895
|
+
child.kill();
|
|
896
|
+
reject(new Error("timed out"));
|
|
897
|
+
}, timeoutMs);
|
|
898
|
+
child.stdout.setEncoding("utf8");
|
|
899
|
+
child.stdout.on("data", (chunk) => {
|
|
900
|
+
out += chunk;
|
|
901
|
+
});
|
|
902
|
+
child.on("error", (err) => {
|
|
903
|
+
clearTimeout(timer);
|
|
904
|
+
if (!settled) reject(err);
|
|
905
|
+
});
|
|
906
|
+
child.on("exit", (code) => {
|
|
907
|
+
clearTimeout(timer);
|
|
908
|
+
if (settled) return;
|
|
909
|
+
setTimeout(() => {
|
|
910
|
+
if (code !== 0) return reject(new Error(`claude exited ${code}`));
|
|
911
|
+
try {
|
|
912
|
+
resolve(parseLimits(JSON.parse(out).result ?? ""));
|
|
913
|
+
} catch {
|
|
914
|
+
reject(new Error("could not read Claude Code usage output"));
|
|
915
|
+
}
|
|
916
|
+
}, 50);
|
|
917
|
+
});
|
|
918
|
+
});
|
|
919
|
+
return run("claude").catch(
|
|
920
|
+
(err) => process.platform === "win32" && err.code === "ENOENT" ? run("claude.cmd") : Promise.reject(err)
|
|
921
|
+
);
|
|
922
|
+
}
|
|
923
|
+
async function collectUsage(dir, now) {
|
|
924
|
+
const [report, limits] = await Promise.all([
|
|
925
|
+
scanUsage(dir, now),
|
|
926
|
+
readLimits().then(
|
|
927
|
+
(l) => ({ limits: l, error: null }),
|
|
928
|
+
(e) => ({ limits: [], error: describe(e) })
|
|
929
|
+
)
|
|
930
|
+
]);
|
|
931
|
+
report.limits = limits.limits;
|
|
932
|
+
report.limitsError = limits.error;
|
|
933
|
+
return report;
|
|
934
|
+
}
|
|
935
|
+
function describe(err) {
|
|
936
|
+
if (err.code === "ENOENT") return "the `claude` command is not on this machine\u2019s PATH";
|
|
937
|
+
if (err.killed) return "`claude -p /usage` timed out";
|
|
938
|
+
return err.message || "could not run `claude -p /usage`";
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
// src/http.ts
|
|
942
|
+
var MIME = {
|
|
943
|
+
".html": "text/html; charset=utf-8",
|
|
944
|
+
".js": "text/javascript; charset=utf-8",
|
|
945
|
+
".css": "text/css; charset=utf-8",
|
|
946
|
+
".json": "application/json; charset=utf-8",
|
|
947
|
+
".svg": "image/svg+xml",
|
|
948
|
+
".woff2": "font/woff2",
|
|
949
|
+
".woff": "font/woff",
|
|
950
|
+
".png": "image/png",
|
|
951
|
+
".ico": "image/x-icon"
|
|
952
|
+
};
|
|
953
|
+
var json = (res, code, body) => {
|
|
954
|
+
const payload = JSON.stringify(body);
|
|
955
|
+
res.writeHead(code, { "content-type": "application/json; charset=utf-8" });
|
|
956
|
+
res.end(payload);
|
|
957
|
+
};
|
|
958
|
+
var readBody = (req) => new Promise((resolve) => {
|
|
959
|
+
let data = "";
|
|
960
|
+
req.on("data", (c) => {
|
|
961
|
+
data += c;
|
|
962
|
+
if (data.length > 1e6) req.destroy();
|
|
963
|
+
});
|
|
964
|
+
req.on("end", () => resolve(data));
|
|
965
|
+
});
|
|
966
|
+
var USAGE_CACHE_MS = 3e4;
|
|
967
|
+
function createHandler(opts) {
|
|
968
|
+
const { pm, webRoot, token } = opts;
|
|
969
|
+
let usage = null;
|
|
970
|
+
return async function handle(req, res) {
|
|
971
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
972
|
+
if (url.pathname.startsWith("/api/")) {
|
|
973
|
+
if (token && req.headers.authorization !== `Bearer ${token}`) {
|
|
974
|
+
return json(res, 401, { error: "unauthorized" });
|
|
975
|
+
}
|
|
976
|
+
return await api(req, res, url);
|
|
977
|
+
}
|
|
978
|
+
return await serveStatic(res, url.pathname);
|
|
979
|
+
};
|
|
980
|
+
async function api(req, res, url) {
|
|
981
|
+
const done = url.pathname.match(/^\/api\/sessions\/([^/]+)\/done$/);
|
|
982
|
+
if (done && req.method === "POST") {
|
|
983
|
+
const s = pm.findSession(decodeURIComponent(done[1]));
|
|
984
|
+
if (!s) return json(res, 404, { error: "no such session" });
|
|
985
|
+
s.hook();
|
|
986
|
+
return json(res, 200, { ok: true });
|
|
987
|
+
}
|
|
988
|
+
const status = url.pathname.match(/^\/api\/sessions\/([^/]+)\/status$/);
|
|
989
|
+
if (status && req.method === "POST") {
|
|
990
|
+
const s = pm.findSession(decodeURIComponent(status[1]));
|
|
991
|
+
if (!s) return json(res, 404, { error: "no such session" });
|
|
992
|
+
let body;
|
|
993
|
+
try {
|
|
994
|
+
body = JSON.parse(await readBody(req) || "{}");
|
|
995
|
+
} catch {
|
|
996
|
+
return json(res, 400, { error: "malformed body" });
|
|
997
|
+
}
|
|
998
|
+
if (body.status === "done") s.hook();
|
|
999
|
+
else if (body.status === "busy") s.tracker.commandStart(Date.now());
|
|
1000
|
+
else return json(res, 400, { error: 'status must be "busy" or "done"' });
|
|
1001
|
+
return json(res, 200, { ok: true });
|
|
1002
|
+
}
|
|
1003
|
+
if (url.pathname === "/api/fs" && req.method === "GET") {
|
|
1004
|
+
const raw = url.searchParams.get("path")?.trim();
|
|
1005
|
+
const dir = raw ? path3.resolve(raw) : process.env["HOME"] ?? os3.homedir();
|
|
1006
|
+
try {
|
|
1007
|
+
const found = await readdir2(dir, { withFileTypes: true });
|
|
1008
|
+
const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path3.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
|
|
1009
|
+
const parent = path3.dirname(dir);
|
|
1010
|
+
return json(res, 200, { path: dir, parent: parent === dir ? null : parent, entries });
|
|
1011
|
+
} catch {
|
|
1012
|
+
return json(res, 400, { error: `cannot read ${dir}` });
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
if (url.pathname === "/api/usage" && req.method === "GET") {
|
|
1016
|
+
const now = Date.now();
|
|
1017
|
+
if (!usage || now - usage.at > USAGE_CACHE_MS) {
|
|
1018
|
+
usage = { at: now, report: collectUsage(defaultTranscriptDir(), now) };
|
|
1019
|
+
}
|
|
1020
|
+
try {
|
|
1021
|
+
return json(res, 200, await usage.report);
|
|
1022
|
+
} catch {
|
|
1023
|
+
usage = null;
|
|
1024
|
+
return json(res, 500, { error: "cannot read Claude Code transcripts" });
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
if (url.pathname === "/api/sessions" && req.method === "GET") {
|
|
1028
|
+
const sessions = pm.list().flatMap(
|
|
1029
|
+
(p) => p.sessions.map((s) => ({ ...s, project: p.name }))
|
|
1030
|
+
);
|
|
1031
|
+
return json(res, 200, { sessions });
|
|
1032
|
+
}
|
|
1033
|
+
return json(res, 404, { error: "not found" });
|
|
1034
|
+
}
|
|
1035
|
+
async function serveStatic(res, pathname) {
|
|
1036
|
+
const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
|
|
1037
|
+
const file = path3.resolve(webRoot, rel);
|
|
1038
|
+
if (file !== webRoot && !file.startsWith(webRoot + path3.sep)) {
|
|
1039
|
+
res.writeHead(403).end("forbidden");
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
try {
|
|
1043
|
+
const info = await stat2(file);
|
|
1044
|
+
if (!info.isFile()) throw new Error("not a file");
|
|
1045
|
+
res.writeHead(200, { "content-type": MIME[path3.extname(file)] ?? "application/octet-stream" });
|
|
1046
|
+
createReadStream(file).pipe(res);
|
|
1047
|
+
} catch {
|
|
1048
|
+
if (rel === "index.html") {
|
|
1049
|
+
res.writeHead(200, { "content-type": MIME[".html"] });
|
|
1050
|
+
res.end('<!doctype html><meta charset="utf-8"><title>tring</title><body style="font:14px ui-monospace,monospace;background:#040c0a;color:#dceee7;padding:2rem"><p>Daemon is running. The web bundle is not built yet.</p><p style="color:#8aa79d">Run <code>npm run build -w @tring/web</code>.</p>');
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
res.writeHead(404).end("not found");
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// src/ws.ts
|
|
1059
|
+
var Hub = class {
|
|
1060
|
+
constructor(opts) {
|
|
1061
|
+
this.opts = opts;
|
|
1062
|
+
const pm = opts.pm;
|
|
1063
|
+
pm.onChange = () => this.broadcastState();
|
|
1064
|
+
pm.onSessionStatus = (s) => this.broadcastStatus(s);
|
|
1065
|
+
pm.onSessionExit = (s, code) => this.broadcast({ type: "exit", id: s.id, code });
|
|
1066
|
+
pm.onSessionData = (s, data) => {
|
|
1067
|
+
const frame = encodeOutput(s.id, Buffer.from(data, "utf8"));
|
|
1068
|
+
for (const c of this.clients) {
|
|
1069
|
+
if (c.authed && c.focusedId === s.id) c.ws.send(frame, { binary: true });
|
|
1070
|
+
}
|
|
1071
|
+
};
|
|
1072
|
+
this.timer = setInterval(() => this.pumpSnapshots(), opts.snapshotMs ?? 250);
|
|
1073
|
+
this.timer.unref?.();
|
|
1074
|
+
}
|
|
1075
|
+
clients = /* @__PURE__ */ new Set();
|
|
1076
|
+
timer;
|
|
1077
|
+
update = null;
|
|
1078
|
+
/** The registry check is async and must never delay startup, so the notice
|
|
1079
|
+
* arrives later and is pushed to whoever is already connected. */
|
|
1080
|
+
setUpdate(update) {
|
|
1081
|
+
this.update = update;
|
|
1082
|
+
this.broadcastState();
|
|
1083
|
+
}
|
|
1084
|
+
attach(wss) {
|
|
1085
|
+
wss.on("connection", (ws) => this.accept(ws));
|
|
1086
|
+
}
|
|
1087
|
+
dispose() {
|
|
1088
|
+
clearInterval(this.timer);
|
|
1089
|
+
}
|
|
1090
|
+
accept(ws) {
|
|
1091
|
+
const client = { ws, authed: false, projectId: null, focusedId: null };
|
|
1092
|
+
this.clients.add(client);
|
|
1093
|
+
ws.on("close", () => this.clients.delete(client));
|
|
1094
|
+
ws.on("message", (raw, isBinary) => {
|
|
1095
|
+
if (isBinary) return;
|
|
1096
|
+
let msg;
|
|
1097
|
+
try {
|
|
1098
|
+
msg = JSON.parse(String(raw));
|
|
1099
|
+
} catch {
|
|
1100
|
+
return this.send(client, { type: "error", message: "malformed message" });
|
|
1101
|
+
}
|
|
1102
|
+
try {
|
|
1103
|
+
this.handle(client, msg);
|
|
1104
|
+
} catch (err) {
|
|
1105
|
+
this.send(client, { type: "error", message: err.message });
|
|
1106
|
+
}
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
handle(c, msg) {
|
|
1110
|
+
const pm = this.opts.pm;
|
|
1111
|
+
if (msg.type === "hello") {
|
|
1112
|
+
if (this.opts.token && msg.token !== this.opts.token) {
|
|
1113
|
+
this.send(c, { type: "error", message: "unauthorized" });
|
|
1114
|
+
c.ws.close();
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
c.authed = true;
|
|
1118
|
+
c.projectId = pm.activeProjectId;
|
|
1119
|
+
this.sendState(c);
|
|
1120
|
+
this.sendSnapshots(c);
|
|
1121
|
+
return;
|
|
1122
|
+
}
|
|
1123
|
+
if (!c.authed) return this.send(c, { type: "error", message: "expected hello" });
|
|
1124
|
+
switch (msg.type) {
|
|
1125
|
+
case "activateProject": {
|
|
1126
|
+
pm.activate(msg.projectId);
|
|
1127
|
+
c.projectId = msg.projectId;
|
|
1128
|
+
c.focusedId = null;
|
|
1129
|
+
this.sendState(c);
|
|
1130
|
+
this.sendSnapshots(c);
|
|
1131
|
+
break;
|
|
1132
|
+
}
|
|
1133
|
+
case "createProject": {
|
|
1134
|
+
const id = pm.createProject(msg.name, msg.root);
|
|
1135
|
+
c.projectId = id;
|
|
1136
|
+
break;
|
|
1137
|
+
}
|
|
1138
|
+
case "renameProject":
|
|
1139
|
+
pm.renameProject(msg.projectId, msg.name);
|
|
1140
|
+
break;
|
|
1141
|
+
case "deleteProject":
|
|
1142
|
+
pm.deleteProject(msg.projectId);
|
|
1143
|
+
if (c.projectId === msg.projectId) {
|
|
1144
|
+
c.projectId = pm.activeProjectId;
|
|
1145
|
+
c.focusedId = null;
|
|
1146
|
+
}
|
|
1147
|
+
break;
|
|
1148
|
+
case "create":
|
|
1149
|
+
pm.create(msg.projectId ?? c.projectId ?? void 0, {
|
|
1150
|
+
slot: msg.slot,
|
|
1151
|
+
cwd: msg.cwd,
|
|
1152
|
+
command: msg.command ?? null,
|
|
1153
|
+
name: msg.name ?? null
|
|
1154
|
+
});
|
|
1155
|
+
break;
|
|
1156
|
+
case "focus": {
|
|
1157
|
+
c.focusedId = msg.id;
|
|
1158
|
+
if (!msg.id) break;
|
|
1159
|
+
const s = pm.findSession(msg.id);
|
|
1160
|
+
if (!s) break;
|
|
1161
|
+
s.resize(msg.cols, msg.rows);
|
|
1162
|
+
this.send(c, { type: "screen", id: s.id, ansi: s.serialize() });
|
|
1163
|
+
break;
|
|
1164
|
+
}
|
|
1165
|
+
case "input": {
|
|
1166
|
+
pm.findSession(msg.id)?.write(msg.data);
|
|
1167
|
+
break;
|
|
1168
|
+
}
|
|
1169
|
+
case "resize": {
|
|
1170
|
+
if (c.focusedId) pm.findSession(c.focusedId)?.resize(msg.cols, msg.rows);
|
|
1171
|
+
break;
|
|
1172
|
+
}
|
|
1173
|
+
case "kill":
|
|
1174
|
+
pm.findManager(msg.id)?.kill(msg.id);
|
|
1175
|
+
break;
|
|
1176
|
+
case "rename":
|
|
1177
|
+
pm.findManager(msg.id)?.rename(msg.id, msg.name);
|
|
1178
|
+
break;
|
|
1179
|
+
case "color":
|
|
1180
|
+
pm.findManager(msg.id)?.setColor(msg.id, msg.color);
|
|
1181
|
+
break;
|
|
1182
|
+
case "ack":
|
|
1183
|
+
pm.findSession(msg.id)?.ack();
|
|
1184
|
+
break;
|
|
1185
|
+
case "respawn":
|
|
1186
|
+
pm.findManager(msg.id)?.respawn(msg.id);
|
|
1187
|
+
break;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Every tile in the project this client has just started viewing, once.
|
|
1192
|
+
*
|
|
1193
|
+
* The pump below only emits on change, which is what keeps sixteen tiles
|
|
1194
|
+
* cheap — but it means a session that has gone quiet is never sent again.
|
|
1195
|
+
* Attaching is exactly when a viewer has seen nothing, so it gets the
|
|
1196
|
+
* screens as they stand rather than waiting for output that may never come.
|
|
1197
|
+
*/
|
|
1198
|
+
sendSnapshots(c) {
|
|
1199
|
+
if (!c.projectId) return;
|
|
1200
|
+
const mgr = this.opts.pm.managerFor(c.projectId);
|
|
1201
|
+
if (!mgr) return;
|
|
1202
|
+
for (const session of mgr.list()) {
|
|
1203
|
+
this.send(c, { type: "snapshot", id: session.id, snapshot: session.snapshotNow() });
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Snapshots go only to sockets whose viewed project owns the session. A
|
|
1208
|
+
* background project keeps its PTYs and its status tracking — that is what
|
|
1209
|
+
* the tab badge reads — but costs no pixels.
|
|
1210
|
+
*/
|
|
1211
|
+
pumpSnapshots() {
|
|
1212
|
+
const viewed = /* @__PURE__ */ new Set();
|
|
1213
|
+
for (const c of this.clients) if (c.authed && c.projectId) viewed.add(c.projectId);
|
|
1214
|
+
if (viewed.size === 0) return;
|
|
1215
|
+
for (const project of this.opts.pm.list()) {
|
|
1216
|
+
if (!viewed.has(project.id)) continue;
|
|
1217
|
+
const mgr = this.opts.pm.managerFor(project.id);
|
|
1218
|
+
if (!mgr) continue;
|
|
1219
|
+
for (const session of mgr.list()) {
|
|
1220
|
+
const shot = session.takeSnapshot();
|
|
1221
|
+
if (!shot) continue;
|
|
1222
|
+
const msg = { type: "snapshot", id: session.id, snapshot: shot };
|
|
1223
|
+
for (const c of this.clients) {
|
|
1224
|
+
if (c.authed && c.projectId === project.id) this.send(c, msg);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
broadcastStatus(s) {
|
|
1230
|
+
this.broadcast({
|
|
1231
|
+
type: "status",
|
|
1232
|
+
id: s.id,
|
|
1233
|
+
status: s.tracker.status,
|
|
1234
|
+
since: s.tracker.since,
|
|
1235
|
+
title: s.title,
|
|
1236
|
+
notable: s.tracker.notable
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
sendState(c) {
|
|
1240
|
+
this.send(c, {
|
|
1241
|
+
type: "state",
|
|
1242
|
+
projects: this.opts.pm.list(),
|
|
1243
|
+
activeProjectId: c.projectId ?? this.opts.pm.activeProjectId,
|
|
1244
|
+
update: this.update
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
1247
|
+
broadcastState() {
|
|
1248
|
+
for (const c of this.clients) if (c.authed) this.sendState(c);
|
|
1249
|
+
}
|
|
1250
|
+
broadcast(msg) {
|
|
1251
|
+
for (const c of this.clients) if (c.authed) this.send(c, msg);
|
|
1252
|
+
}
|
|
1253
|
+
send(c, msg) {
|
|
1254
|
+
if (c.ws.readyState === 1) c.ws.send(JSON.stringify(msg));
|
|
1255
|
+
}
|
|
1256
|
+
};
|
|
1257
|
+
|
|
1258
|
+
// src/open-window.ts
|
|
1259
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
1260
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
1261
|
+
import os4 from "node:os";
|
|
1262
|
+
function isWsl() {
|
|
1263
|
+
if (process.env["WSL_DISTRO_NAME"]) return true;
|
|
1264
|
+
try {
|
|
1265
|
+
return /microsoft/i.test(readFileSync("/proc/version", "utf8"));
|
|
1266
|
+
} catch {
|
|
1267
|
+
return false;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
function wslCandidates() {
|
|
1271
|
+
const user = process.env["WSL_USER"] ?? "";
|
|
1272
|
+
const roots = ["/mnt/c/Program Files", "/mnt/c/Program Files (x86)"];
|
|
1273
|
+
const paths = [
|
|
1274
|
+
...roots.map((r) => `${r}/Google/Chrome/Application/chrome.exe`),
|
|
1275
|
+
...roots.map((r) => `${r}/Microsoft/Edge/Application/msedge.exe`),
|
|
1276
|
+
...roots.map((r) => `${r}/BraveSoftware/Brave-Browser/Application/brave.exe`)
|
|
1277
|
+
];
|
|
1278
|
+
if (user) paths.push(`/mnt/c/Users/${user}/AppData/Local/Google/Chrome/Application/chrome.exe`);
|
|
1279
|
+
return paths;
|
|
1280
|
+
}
|
|
1281
|
+
function firstExisting(paths) {
|
|
1282
|
+
for (const p of paths) if (existsSync(p)) return p;
|
|
1283
|
+
return null;
|
|
1284
|
+
}
|
|
1285
|
+
function openWindow(url) {
|
|
1286
|
+
if (process.env["TRING_NO_OPEN"]) return false;
|
|
1287
|
+
const appFlag = `--app=${url}`;
|
|
1288
|
+
let command;
|
|
1289
|
+
let args;
|
|
1290
|
+
if (isWsl()) {
|
|
1291
|
+
const exe = firstExisting(wslCandidates());
|
|
1292
|
+
if (!exe) return false;
|
|
1293
|
+
command = exe;
|
|
1294
|
+
args = [appFlag];
|
|
1295
|
+
} else if (process.platform === "darwin") {
|
|
1296
|
+
command = "open";
|
|
1297
|
+
args = ["-na", "Google Chrome", "--args", appFlag];
|
|
1298
|
+
} else if (process.platform === "win32") {
|
|
1299
|
+
const local = process.env["LOCALAPPDATA"] ?? "";
|
|
1300
|
+
const exe = firstExisting([
|
|
1301
|
+
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
|
1302
|
+
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
|
1303
|
+
...local ? [`${local}\\Google\\Chrome\\Application\\chrome.exe`] : [],
|
|
1304
|
+
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
|
1305
|
+
"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe"
|
|
1306
|
+
]);
|
|
1307
|
+
if (!exe) return false;
|
|
1308
|
+
command = exe;
|
|
1309
|
+
args = [appFlag];
|
|
1310
|
+
} else {
|
|
1311
|
+
const exe = firstExisting([
|
|
1312
|
+
"/usr/bin/google-chrome",
|
|
1313
|
+
"/usr/bin/google-chrome-stable",
|
|
1314
|
+
"/usr/bin/chromium",
|
|
1315
|
+
"/usr/bin/chromium-browser",
|
|
1316
|
+
"/usr/bin/microsoft-edge"
|
|
1317
|
+
]);
|
|
1318
|
+
if (!exe) return false;
|
|
1319
|
+
command = exe;
|
|
1320
|
+
args = [appFlag];
|
|
1321
|
+
}
|
|
1322
|
+
try {
|
|
1323
|
+
const child = spawn3(command, args, { detached: true, stdio: "ignore" });
|
|
1324
|
+
child.on("error", () => {
|
|
1325
|
+
});
|
|
1326
|
+
child.unref();
|
|
1327
|
+
return true;
|
|
1328
|
+
} catch {
|
|
1329
|
+
return false;
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
function describeFallback(url) {
|
|
1333
|
+
return isWsl() || os4.platform() === "linux" ? `open ${url} in your browser` : `open ${url}`;
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// src/update-check.ts
|
|
1337
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
1338
|
+
import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "node:fs/promises";
|
|
1339
|
+
import path4 from "node:path";
|
|
1340
|
+
var require3 = createRequire2(import.meta.url);
|
|
1341
|
+
function currentVersion() {
|
|
1342
|
+
try {
|
|
1343
|
+
return require3("../package.json").version;
|
|
1344
|
+
} catch {
|
|
1345
|
+
return "0.0.0";
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
function isNewer(latest, current) {
|
|
1349
|
+
if (latest.includes("-")) return false;
|
|
1350
|
+
const parse = (v) => v.split("-")[0].split(".").map((n) => Number(n) || 0);
|
|
1351
|
+
const a = parse(latest);
|
|
1352
|
+
const b = parse(current);
|
|
1353
|
+
for (let i = 0; i < 3; i++) {
|
|
1354
|
+
const x = a[i] ?? 0;
|
|
1355
|
+
const y = b[i] ?? 0;
|
|
1356
|
+
if (x !== y) return x > y;
|
|
1357
|
+
}
|
|
1358
|
+
return false;
|
|
1359
|
+
}
|
|
1360
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
1361
|
+
async function checkForUpdate(cachePath) {
|
|
1362
|
+
const current = currentVersion();
|
|
1363
|
+
let cache = null;
|
|
1364
|
+
try {
|
|
1365
|
+
cache = JSON.parse(await readFile3(cachePath, "utf8"));
|
|
1366
|
+
} catch {
|
|
1367
|
+
cache = null;
|
|
1368
|
+
}
|
|
1369
|
+
if (cache && Date.now() - cache.checkedAt < DAY_MS) {
|
|
1370
|
+
return isNewer(cache.latest, current) ? cache.latest : null;
|
|
1371
|
+
}
|
|
1372
|
+
let latest;
|
|
1373
|
+
try {
|
|
1374
|
+
const res = await fetch("https://registry.npmjs.org/tring-chat/latest", {
|
|
1375
|
+
signal: AbortSignal.timeout(3e3),
|
|
1376
|
+
headers: { accept: "application/vnd.npm.install-v1+json" }
|
|
1377
|
+
});
|
|
1378
|
+
if (!res.ok) return null;
|
|
1379
|
+
latest = (await res.json()).version ?? "";
|
|
1380
|
+
if (!latest) return null;
|
|
1381
|
+
} catch {
|
|
1382
|
+
return null;
|
|
1383
|
+
}
|
|
1384
|
+
try {
|
|
1385
|
+
await mkdir2(path4.dirname(cachePath), { recursive: true });
|
|
1386
|
+
await writeFile2(cachePath, JSON.stringify({ checkedAt: Date.now(), latest }), "utf8");
|
|
1387
|
+
} catch {
|
|
1388
|
+
}
|
|
1389
|
+
return isNewer(latest, current) ? latest : null;
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
// src/index.ts
|
|
1393
|
+
function parseArgs(argv) {
|
|
1394
|
+
const args = {
|
|
1395
|
+
port: Number(process.env["TRING_PORT"] ?? DEFAULT_PORT),
|
|
1396
|
+
host: process.env["TRING_HOST"] ?? DEFAULT_HOST,
|
|
1397
|
+
token: process.env["TRING_TOKEN"] ?? null,
|
|
1398
|
+
scrollback: DEFAULT_SCROLLBACK,
|
|
1399
|
+
idleMs: DEFAULT_IDLE_MS,
|
|
1400
|
+
open: !process.env["TRING_NO_OPEN"],
|
|
1401
|
+
shell: process.env["TRING_SHELL"] ?? null,
|
|
1402
|
+
updateCheck: !process.env["TRING_NO_UPDATE_CHECK"]
|
|
1403
|
+
};
|
|
1404
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1405
|
+
const [flag, inline] = argv[i].split("=", 2);
|
|
1406
|
+
const value = inline ?? argv[++i];
|
|
1407
|
+
switch (flag) {
|
|
1408
|
+
case "--port":
|
|
1409
|
+
args.port = Number(value);
|
|
1410
|
+
break;
|
|
1411
|
+
case "--host":
|
|
1412
|
+
args.host = String(value);
|
|
1413
|
+
break;
|
|
1414
|
+
case "--token":
|
|
1415
|
+
args.token = String(value);
|
|
1416
|
+
break;
|
|
1417
|
+
case "--scrollback":
|
|
1418
|
+
args.scrollback = Number(value);
|
|
1419
|
+
break;
|
|
1420
|
+
case "--idle-ms":
|
|
1421
|
+
args.idleMs = Number(value);
|
|
1422
|
+
break;
|
|
1423
|
+
case "--shell":
|
|
1424
|
+
args.shell = String(value);
|
|
1425
|
+
break;
|
|
1426
|
+
case "--no-open":
|
|
1427
|
+
args.open = false;
|
|
1428
|
+
i--;
|
|
1429
|
+
break;
|
|
1430
|
+
case "--no-update-check":
|
|
1431
|
+
args.updateCheck = false;
|
|
1432
|
+
i--;
|
|
1433
|
+
break;
|
|
1434
|
+
case "--version":
|
|
1435
|
+
console.log(currentVersion());
|
|
1436
|
+
process.exit(0);
|
|
1437
|
+
case "--help":
|
|
1438
|
+
console.log(`tring \u2014 focus-centred terminal deck
|
|
1439
|
+
|
|
1440
|
+
--port <n> default ${DEFAULT_PORT}
|
|
1441
|
+
--host <addr> default ${DEFAULT_HOST}
|
|
1442
|
+
--token <secret> require bearer auth (use when binding off localhost)
|
|
1443
|
+
--scrollback <n> lines kept per session, default ${DEFAULT_SCROLLBACK}
|
|
1444
|
+
--idle-ms <n> quiet period before a session is done, default ${DEFAULT_IDLE_MS}
|
|
1445
|
+
--shell <path> shell to spawn; default $SHELL, or powershell.exe on
|
|
1446
|
+
Windows. Use --shell wsl.exe for WSL shells from Windows
|
|
1447
|
+
--no-open do not launch a browser window
|
|
1448
|
+
--no-update-check do not ask npm whether a newer tring exists
|
|
1449
|
+
--version print the version and exit`);
|
|
1450
|
+
process.exit(0);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
return args;
|
|
1454
|
+
}
|
|
1455
|
+
async function main() {
|
|
1456
|
+
const args = parseArgs(process.argv.slice(2));
|
|
1457
|
+
const url = `http://${args.host}:${args.port}`;
|
|
1458
|
+
const here = path5.dirname(fileURLToPath(import.meta.url));
|
|
1459
|
+
const webRoot = [
|
|
1460
|
+
path5.resolve(here, "web"),
|
|
1461
|
+
path5.resolve(here, "../../web/dist")
|
|
1462
|
+
].find((p) => existsSync2(p)) ?? path5.resolve(here, "web");
|
|
1463
|
+
const pm = await ProjectManager.open({
|
|
1464
|
+
url,
|
|
1465
|
+
scrollback: args.scrollback,
|
|
1466
|
+
idleMs: args.idleMs,
|
|
1467
|
+
...args.shell ? { shell: args.shell } : {}
|
|
1468
|
+
});
|
|
1469
|
+
const handle = createHandler({ pm, webRoot, token: args.token });
|
|
1470
|
+
const server = createServer((req, res) => {
|
|
1471
|
+
void handle(req, res).catch(() => {
|
|
1472
|
+
if (!res.headersSent) res.writeHead(500).end("internal error");
|
|
1473
|
+
});
|
|
1474
|
+
});
|
|
1475
|
+
const wss = new WebSocketServer({ server });
|
|
1476
|
+
const hub = new Hub({ pm, token: args.token });
|
|
1477
|
+
hub.attach(wss);
|
|
1478
|
+
server.listen(args.port, args.host, () => {
|
|
1479
|
+
console.log(`tring listening on ${url}`);
|
|
1480
|
+
if (!args.token && args.host !== "127.0.0.1" && args.host !== "localhost") {
|
|
1481
|
+
console.warn("warning: bound off localhost without --token");
|
|
1482
|
+
}
|
|
1483
|
+
if (args.updateCheck) {
|
|
1484
|
+
void checkForUpdate(path5.join(path5.dirname(pm.statePath), "update-check.json")).then((latest) => {
|
|
1485
|
+
if (!latest) return;
|
|
1486
|
+
hub.setUpdate({ current: currentVersion(), latest });
|
|
1487
|
+
console.log(`update available: ${currentVersion()} -> ${latest} (npm i -g tring-chat)`);
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
if (args.open) {
|
|
1491
|
+
const opened = openWindow(url);
|
|
1492
|
+
if (!opened) console.log(`no browser found \u2014 ${describeFallback(url)}`);
|
|
1493
|
+
}
|
|
1494
|
+
});
|
|
1495
|
+
const shutdown = async () => {
|
|
1496
|
+
hub.dispose();
|
|
1497
|
+
await pm.dispose();
|
|
1498
|
+
server.close(() => process.exit(0));
|
|
1499
|
+
setTimeout(() => process.exit(0), 1e3).unref();
|
|
1500
|
+
};
|
|
1501
|
+
process.on("SIGINT", () => void shutdown());
|
|
1502
|
+
process.on("SIGTERM", () => void shutdown());
|
|
1503
|
+
}
|
|
1504
|
+
void main();
|