@k-electron/k-bench 0.6.0 → 0.8.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/dist/js/src/server/claude.js +196 -14
- package/dist/js/src/server/config.js +1 -0
- package/dist/js/src/server/server.js +30 -1
- package/dist/js/src/server/service.js +3 -0
- package/dist/js/src/server/status-line-readings.js +114 -0
- package/dist/js/src/server/store.js +102 -0
- package/dist/js/src/server/tmux.js +31 -12
- package/dist/web/assets/index-DrJkxO72.css +1 -0
- package/dist/web/assets/index-P6BaRaZc.js +80 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/index-CWZyOJf0.css +0 -1
- package/dist/web/assets/index-CcDjRu2P.js +0 -74
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Launching Claude Code for a Claude Session (ADR-0005). k-bench starts it through its
|
|
3
3
|
* documented command-line flags and learns which conversation it is on, and whether it is
|
|
4
|
-
* Working, Waiting or Idle, through silent hooks,
|
|
5
|
-
*
|
|
4
|
+
* Working, Waiting or Idle, through silent hooks, and its Model, Context used and the owner's
|
|
5
|
+
* Usage limits through its status line, so everything k-bench knows about Claude Code is in this file: the flags it
|
|
6
|
+
* passes, the hooks, the status line wrapper, and the launcher script that runs it.
|
|
6
7
|
*/
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
7
10
|
import { DEFAULT_LAUNCH_OPTIONS, LAUNCH_CHOICES, } from "../shared/launch-options.js";
|
|
8
11
|
/**
|
|
9
12
|
* Reads Launch options from a request. A field left out is Default; a value that is not one
|
|
@@ -166,17 +169,196 @@ function launchHooks() {
|
|
|
166
169
|
return hooks;
|
|
167
170
|
}
|
|
168
171
|
/**
|
|
169
|
-
* The
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
|
|
174
|
-
|
|
172
|
+
* The tmux `wait-for` channel the status line wrapper signals once it has left a reading in
|
|
173
|
+
* the readings folder (see `TmuxDriver.watchReadings`). Named for the Usage limits, which
|
|
174
|
+
* its readings carried first: the wrappers of Claude Sessions launched before that changed
|
|
175
|
+
* still signal this name, and keep doing so until they restart.
|
|
176
|
+
*/
|
|
177
|
+
export const READINGS_CHANNEL = "kb-usage-changed";
|
|
178
|
+
/**
|
|
179
|
+
* The status line Claude Code would run in `folder` without k-bench: the one in the first of
|
|
180
|
+
* the local, project and user settings that sets one, as Claude Code ranks them. Null when
|
|
181
|
+
* none does, and "unreadable" when any of those files exists but can't be read or parsed, or
|
|
182
|
+
* its status line isn't a command: k-bench then can't tell which one Claude Code would run.
|
|
183
|
+
*/
|
|
184
|
+
function ownerStatusLine(folder, userSettingsDir) {
|
|
185
|
+
const files = [
|
|
186
|
+
join(folder, ".claude", "settings.local.json"),
|
|
187
|
+
join(folder, ".claude", "settings.json"),
|
|
188
|
+
join(userSettingsDir, "settings.json"),
|
|
189
|
+
];
|
|
190
|
+
let found = null;
|
|
191
|
+
for (const file of files) {
|
|
192
|
+
let settings;
|
|
193
|
+
try {
|
|
194
|
+
settings = JSON.parse(readFileSync(file, "utf8"));
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
if (error.code === "ENOENT")
|
|
198
|
+
continue;
|
|
199
|
+
return "unreadable";
|
|
200
|
+
}
|
|
201
|
+
if (typeof settings !== "object" || settings === null)
|
|
202
|
+
return "unreadable";
|
|
203
|
+
const statusLine = settings.statusLine;
|
|
204
|
+
if (statusLine === undefined || found)
|
|
205
|
+
continue;
|
|
206
|
+
if (typeof statusLine !== "object" || statusLine === null)
|
|
207
|
+
return "unreadable";
|
|
208
|
+
const { command, padding, refreshInterval } = statusLine;
|
|
209
|
+
if (typeof command !== "string")
|
|
210
|
+
return "unreadable";
|
|
211
|
+
found = {
|
|
212
|
+
command,
|
|
213
|
+
...(typeof padding === "number" ? { padding } : {}),
|
|
214
|
+
...(typeof refreshInterval === "number" ? { refreshInterval } : {}),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
return found;
|
|
218
|
+
}
|
|
219
|
+
/** `text` as a single-quoted `sh` word, so nothing in it is expanded or run. */
|
|
220
|
+
function shellWord(text) {
|
|
221
|
+
return `'${text.replaceAll("'", `'\\''`)}'`;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* The status line command every launch sets, which Claude Code runs with its status line
|
|
225
|
+
* input (a JSON object) on stdin. It leaves every input for k-bench in the readings folder,
|
|
226
|
+
* one file per Claude Session named after its id (written beside, then moved in, so k-bench
|
|
227
|
+
* never reads half of one), and signals the channel: each carries the Session's Model and
|
|
228
|
+
* Context used, and some the Usage limits too. The name says whose a reading is even once
|
|
229
|
+
* the Session has stopped. Then it runs the owner's own status line on the same input, so it
|
|
230
|
+
* prints exactly what that prints and exits with its status; with no owner status line it
|
|
231
|
+
* prints nothing.
|
|
232
|
+
*
|
|
233
|
+
* It is plain POSIX `sh` with no `jq`, like the hooks: the server, not the shell, reads the
|
|
234
|
+
* JSON. k-bench's own steps are silenced and can't fail the run. The input is read whole and
|
|
235
|
+
* kept byte for byte: a command substitution drops trailing newlines, so a mark is read after
|
|
236
|
+
* it and dropped. The owner's command, the folder and the file name are single-quoted words,
|
|
237
|
+
* never spliced in as script.
|
|
238
|
+
*/
|
|
239
|
+
function statusLineCommand(owner, readingsDir, sessionId) {
|
|
240
|
+
return [
|
|
241
|
+
`input=$(cat; printf x); input=\${input%x};`,
|
|
242
|
+
"{",
|
|
243
|
+
`dir=${shellWord(readingsDir)}; tmp="$dir/.$$.tmp";`,
|
|
244
|
+
`printf '%s' "$input" >"$tmp" && mv -f "$tmp" "$dir"/${shellWord(`${sessionId}.json`)} &&`,
|
|
245
|
+
`tmux wait-for -S ${READINGS_CHANNEL} || rm -f "$tmp";`,
|
|
246
|
+
"} >/dev/null 2>&1;",
|
|
247
|
+
owner === undefined ? "exit 0" : `printf '%s' "$input" | sh -c ${shellWord(owner)}`,
|
|
248
|
+
].join(" ");
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* The `statusLine` every launch sets: the wrapper above around the owner's own status line,
|
|
252
|
+
* with its `padding` and `refreshInterval`. Undefined when the owner's settings can't be
|
|
253
|
+
* read, so their status line, whatever it is, stays in charge and only the readings stop.
|
|
254
|
+
*/
|
|
255
|
+
function launchStatusLine(folder, sessionId, setup) {
|
|
256
|
+
const owner = ownerStatusLine(folder, setup.userSettingsDir);
|
|
257
|
+
if (owner === "unreadable")
|
|
258
|
+
return undefined;
|
|
259
|
+
return {
|
|
260
|
+
type: "command",
|
|
261
|
+
command: statusLineCommand(owner?.command, setup.readingsDir, sessionId),
|
|
262
|
+
...(owner?.padding === undefined ? {} : { padding: owner.padding }),
|
|
263
|
+
...(owner?.refreshInterval === undefined
|
|
264
|
+
? {}
|
|
265
|
+
: { refreshInterval: owner.refreshInterval }),
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* What k-bench reads from one status line input: the owner's Usage limits, and the Claude
|
|
270
|
+
* Session's report, undefined when the input carries nothing of it. An input that isn't JSON
|
|
271
|
+
* reads as neither (ADR-0005).
|
|
272
|
+
*/
|
|
273
|
+
export function readStatusLine(input) {
|
|
274
|
+
let parsed;
|
|
275
|
+
try {
|
|
276
|
+
parsed = JSON.parse(input);
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
return { usageLimits: {} };
|
|
280
|
+
}
|
|
281
|
+
const report = readClaudeReport(parsed);
|
|
282
|
+
return { usageLimits: readUsageLimits(parsed), ...(report && { report }) };
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* The Usage limits a status line input reports: `rate_limits.five_hour` and
|
|
286
|
+
* `rate_limits.seven_day`, each `{ used_percentage, resets_at }` (epoch seconds). Claude Code
|
|
287
|
+
* leaves out `rate_limits` on some plans and before the first reply, and a window once it has
|
|
288
|
+
* reset, so either may be missing. Anything malformed is left out too (ADR-0005): a window
|
|
289
|
+
* counts only with a finite `used_percentage` and `resets_at`.
|
|
290
|
+
*/
|
|
291
|
+
function readUsageLimits(parsed) {
|
|
292
|
+
const limits = field(parsed, "rate_limits");
|
|
293
|
+
const window = (name) => {
|
|
294
|
+
const value = field(limits, name);
|
|
295
|
+
const used = field(value, "used_percentage");
|
|
296
|
+
const resets = field(value, "resets_at");
|
|
297
|
+
if (!Number.isFinite(used) || !Number.isFinite(resets))
|
|
298
|
+
return undefined;
|
|
299
|
+
return { usedPercentage: used, resetsAt: resets * 1000 };
|
|
300
|
+
};
|
|
301
|
+
const fiveHour = window("five_hour");
|
|
302
|
+
const weekly = window("seven_day");
|
|
303
|
+
return { ...(fiveHour && { fiveHour }), ...(weekly && { weekly }) };
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* The Model and Context used a status line input reports, and the conversation they belong
|
|
307
|
+
* to: `model.display_name`, from `context_window` its `used_percentage`, `total_input_tokens`
|
|
308
|
+
* (the tokens `used_percentage` counts, so taken only beside it) and `context_window_size`,
|
|
309
|
+
* and `session_id`. Claude Code sends `used_percentage` as null, and 0 tokens, until a
|
|
310
|
+
* conversation's or a new process's first reply. A field missing, null or malformed is left
|
|
311
|
+
* out; undefined when the input carries none of them.
|
|
312
|
+
*/
|
|
313
|
+
function readClaudeReport(parsed) {
|
|
314
|
+
const conversationId = field(parsed, "session_id");
|
|
315
|
+
const model = field(field(parsed, "model"), "display_name");
|
|
316
|
+
const context = field(parsed, "context_window");
|
|
317
|
+
const number = (name, valid) => {
|
|
318
|
+
const value = field(context, name);
|
|
319
|
+
return typeof value === "number" && Number.isFinite(value) && valid(value)
|
|
320
|
+
? value
|
|
321
|
+
: undefined;
|
|
322
|
+
};
|
|
323
|
+
const report = {
|
|
324
|
+
...(typeof conversationId === "string" &&
|
|
325
|
+
conversationId !== "" && { conversationId }),
|
|
326
|
+
...(typeof model === "string" && model.trim() !== "" && { model: model.trim() }),
|
|
327
|
+
};
|
|
328
|
+
const contextUsed = number("used_percentage", (value) => value >= 0);
|
|
329
|
+
const tokensUsed = number("total_input_tokens", (value) => value >= 0);
|
|
330
|
+
const contextWindow = number("context_window_size", (value) => value > 0);
|
|
331
|
+
// The share is worked out from these tokens, so they are one measurement: Claude Code sends
|
|
332
|
+
// no tokens beside a null share, before a new process's first reply.
|
|
333
|
+
if (contextUsed !== undefined) {
|
|
334
|
+
report.contextUsed = contextUsed;
|
|
335
|
+
if (tokensUsed !== undefined)
|
|
336
|
+
report.tokensUsed = Math.round(tokensUsed);
|
|
337
|
+
}
|
|
338
|
+
if (contextWindow !== undefined)
|
|
339
|
+
report.contextWindow = Math.round(contextWindow);
|
|
340
|
+
return Object.keys(report).length > 0 ? report : undefined;
|
|
341
|
+
}
|
|
342
|
+
/** `value[name]` when `value` is a JSON object, else undefined. */
|
|
343
|
+
function field(value, name) {
|
|
344
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
345
|
+
? value[name]
|
|
346
|
+
: undefined;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* The `--settings` every launch passes: k-bench's hooks, its status line, Claude Code's
|
|
350
|
+
* `dark` theme and, with Focus view on, its keys. The theme is fixed, not a Launch option:
|
|
351
|
+
* the owner's own theme may be `light`, which colours some text near-black, unreadable on
|
|
352
|
+
* k-bench's dark terminal. Focus view needs both keys: it does nothing without the
|
|
353
|
+
* fullscreen renderer, and fullscreen is not the default on every machine. `--settings`
|
|
354
|
+
* applies to that launch only and adds to the owner's own settings and hooks, or outranks
|
|
355
|
+
* them (the status line replaces theirs, which the wrapper then runs), leaving their files
|
|
175
356
|
* unchanged.
|
|
176
357
|
*/
|
|
177
|
-
function launchSettings(focusView) {
|
|
358
|
+
function launchSettings(focusView, statusLine) {
|
|
178
359
|
return JSON.stringify({
|
|
179
360
|
hooks: launchHooks(),
|
|
361
|
+
...(statusLine ? { statusLine } : {}),
|
|
180
362
|
theme: "dark",
|
|
181
363
|
...(focusView ? { viewMode: "focus", tui: "fullscreen" } : {}),
|
|
182
364
|
});
|
|
@@ -185,16 +367,16 @@ function launchSettings(focusView) {
|
|
|
185
367
|
* The flags that follow the one naming the conversation. This is where Launch options become
|
|
186
368
|
* flags: a Default option adds nothing. Advisor Off is not a flag (there is none): the
|
|
187
369
|
* launcher sets `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1` for it. `--settings` is always passed,
|
|
188
|
-
* for k-bench's hooks and the dark theme.
|
|
370
|
+
* for k-bench's hooks, its status line and the dark theme.
|
|
189
371
|
*/
|
|
190
|
-
function launchOptionArguments(options) {
|
|
372
|
+
function launchOptionArguments(options, statusLine) {
|
|
191
373
|
const { model, effort, advisor, focusView } = options;
|
|
192
374
|
return [
|
|
193
375
|
...(model === "default" ? [] : ["--model", model]),
|
|
194
376
|
...(effort === "default" ? [] : ["--effort", effort]),
|
|
195
377
|
...(advisor === "default" || advisor === "off" ? [] : ["--advisor", advisor]),
|
|
196
378
|
"--settings",
|
|
197
|
-
launchSettings(focusView),
|
|
379
|
+
launchSettings(focusView, statusLine),
|
|
198
380
|
];
|
|
199
381
|
}
|
|
200
382
|
/** Printed, and waited on, when Claude Code exits with an error. */
|
|
@@ -259,7 +441,7 @@ exit "$status"
|
|
|
259
441
|
* script, so nothing in them can break or inject into it.
|
|
260
442
|
*/
|
|
261
443
|
export function claudeCommand(input) {
|
|
262
|
-
const { folder, shell, program, launch } = input;
|
|
444
|
+
const { folder, shell, program, sessionId, statusLine, launch } = input;
|
|
263
445
|
return [
|
|
264
446
|
"/bin/zsh",
|
|
265
447
|
"-f",
|
|
@@ -282,6 +464,6 @@ export function claudeCommand(input) {
|
|
|
282
464
|
launch.options.advisor === "off" ? "1" : "0",
|
|
283
465
|
launch.mode,
|
|
284
466
|
launch.conversationId,
|
|
285
|
-
...launchOptionArguments(launch.options),
|
|
467
|
+
...launchOptionArguments(launch.options, launchStatusLine(folder, sessionId, statusLine)),
|
|
286
468
|
];
|
|
287
469
|
}
|
|
@@ -5,16 +5,35 @@ import { Attachments } from "./attachments.js";
|
|
|
5
5
|
import { EventSockets } from "./events.js";
|
|
6
6
|
import { Service } from "./service.js";
|
|
7
7
|
import { StateFeed } from "./state-feed.js";
|
|
8
|
+
import { StatusLineReadings, statusLineReadingsDir } from "./status-line-readings.js";
|
|
8
9
|
import { Store } from "./store.js";
|
|
9
10
|
import { TerminalSockets } from "./terminal.js";
|
|
10
11
|
import { TmuxDriver } from "./tmux.js";
|
|
11
12
|
/** Boots a server for one instance config. Used by `main.ts` and by the test harness. */
|
|
12
13
|
export async function startServer(config, options = {}) {
|
|
13
14
|
const store = new Store(config.dataDir);
|
|
14
|
-
const
|
|
15
|
+
const readingsDir = statusLineReadingsDir(config.dataDir);
|
|
16
|
+
const tmux = new TmuxDriver(config.tmuxSocket, {
|
|
17
|
+
program: config.claudeProgram,
|
|
18
|
+
userSettingsDir: config.claudeUserSettingsDir,
|
|
19
|
+
readingsDir,
|
|
20
|
+
});
|
|
15
21
|
const service = new Service(store, tmux, { workingQuietMs: config.workingQuietMs });
|
|
16
22
|
// Anything on the socket that the store does not know is left over: clean it up first.
|
|
17
23
|
await service.reconcile();
|
|
24
|
+
// Readings Claude Sessions left while k-bench was down. Each is named after its Session,
|
|
25
|
+
// except an earlier k-bench's, named after its pane: the live Sessions' panes say whose.
|
|
26
|
+
const readings = new StatusLineReadings(readingsDir, store);
|
|
27
|
+
const takeReadings = async () => {
|
|
28
|
+
const live = await tmux.listSessions();
|
|
29
|
+
return readings.take(new Map(live.map((session) => [session.pane, session.id])));
|
|
30
|
+
};
|
|
31
|
+
try {
|
|
32
|
+
await takeReadings();
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
console.error("could not take a status line reading", error);
|
|
36
|
+
}
|
|
18
37
|
// A tmux server that outlived the previous k-bench gets this version's hooks.
|
|
19
38
|
await tmux.configure();
|
|
20
39
|
const attachments = new Attachments(tmux, service);
|
|
@@ -33,6 +52,15 @@ export async function startServer(config, options = {}) {
|
|
|
33
52
|
.then(() => service.reconcile())
|
|
34
53
|
.catch((error) => console.error("could not follow a Claude conversation", error));
|
|
35
54
|
});
|
|
55
|
+
// Likewise a status line reading, on the same chain.
|
|
56
|
+
const statusLines = tmux.watchReadings(() => {
|
|
57
|
+
following = following
|
|
58
|
+
.then(async () => {
|
|
59
|
+
if (await takeReadings())
|
|
60
|
+
feed.notify();
|
|
61
|
+
})
|
|
62
|
+
.catch((error) => console.error("could not take a status line reading", error));
|
|
63
|
+
});
|
|
36
64
|
// The guard sits in front of everything the server answers, so no route or static file
|
|
37
65
|
// (now or added later) can be reached without the allowed login.
|
|
38
66
|
const guard = new AccessGuard(config.allowedLogin);
|
|
@@ -78,6 +106,7 @@ export async function startServer(config, options = {}) {
|
|
|
78
106
|
await bells.stop();
|
|
79
107
|
await activity.stop();
|
|
80
108
|
await conversations.stop();
|
|
109
|
+
await statusLines.stop();
|
|
81
110
|
await following;
|
|
82
111
|
events.closeAll();
|
|
83
112
|
// From here on no tmux client this server started is running or starting.
|
|
@@ -409,6 +409,7 @@ export class Service {
|
|
|
409
409
|
async getState() {
|
|
410
410
|
const live = await this.reconciler.reconcile();
|
|
411
411
|
await this.decayQuietWork(live);
|
|
412
|
+
const reports = this.store.getClaudeReports();
|
|
412
413
|
return {
|
|
413
414
|
openWorkspaceId: this.openWorkspaceId(),
|
|
414
415
|
workspaces: this.store.listWorkspaces().map((workspace) => ({
|
|
@@ -422,9 +423,11 @@ export class Service {
|
|
|
422
423
|
status: live.has(session.id) ? "running" : "stopped",
|
|
423
424
|
bell: live.get(session.id)?.bell ?? false,
|
|
424
425
|
activity: activityOf(session, live.get(session.id)),
|
|
426
|
+
report: reports.get(session.id) ?? null,
|
|
425
427
|
})),
|
|
426
428
|
rightPane: this.rightPane(workspace.id),
|
|
427
429
|
})),
|
|
430
|
+
usageLimits: this.store.getUsageLimits(),
|
|
428
431
|
};
|
|
429
432
|
}
|
|
430
433
|
/**
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, } from "node:fs";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
import { readStatusLine } from "./claude.js";
|
|
4
|
+
/**
|
|
5
|
+
* The folder of an instance's data folder that Claude Sessions leave status line readings in.
|
|
6
|
+
* Named for the Usage limits, which it held first; renaming it would lose a reading left
|
|
7
|
+
* while k-bench was down across an upgrade.
|
|
8
|
+
*/
|
|
9
|
+
export function statusLineReadingsDir(dataDir) {
|
|
10
|
+
return join(dataDir, "usage-readings");
|
|
11
|
+
}
|
|
12
|
+
/** A reading k-bench has claimed, renamed so a newer one from the same Session can land. */
|
|
13
|
+
const CLAIMED = ".claimed-";
|
|
14
|
+
/**
|
|
15
|
+
* How old a reading still being written must be before it counts as abandoned: the wrapper
|
|
16
|
+
* writes one in a moment, so one this old was left by a status line stopped before its `mv`.
|
|
17
|
+
*/
|
|
18
|
+
const ABANDONED_MS = 60_000;
|
|
19
|
+
/**
|
|
20
|
+
* Takes the readings Claude Sessions' status lines leave in the readings folder (see the
|
|
21
|
+
* wrapper in claude.ts) into the store: each one's Model and Context used for the Claude
|
|
22
|
+
* Session that left it, and the owner's Usage limits when it carries them. Each reading is a
|
|
23
|
+
* file holding a whole status line input, named after its Session, so a Session's newer
|
|
24
|
+
* reading replaces one not taken yet, and a reading left by a Session that has stopped since
|
|
25
|
+
* is still its own; its time is when it was written, so readings left while k-bench was down
|
|
26
|
+
* still count from when Claude Code sent them. Files
|
|
27
|
+
* starting with "." other than claimed ones are still being written, and are left alone
|
|
28
|
+
* until they are a minute old, when they are removed as abandoned.
|
|
29
|
+
*/
|
|
30
|
+
export class StatusLineReadings {
|
|
31
|
+
dir;
|
|
32
|
+
store;
|
|
33
|
+
constructor(dir, store) {
|
|
34
|
+
this.dir = dir;
|
|
35
|
+
this.store = store;
|
|
36
|
+
mkdirSync(dir, { recursive: true });
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Records every waiting reading, oldest first, and removes it. `panes` maps each live tmux
|
|
40
|
+
* pane's id (such as `%3`) to its Session, for readings an earlier k-bench's wrapper named
|
|
41
|
+
* after the pane; one whose Session can't be told, or is gone, still counts for the Usage
|
|
42
|
+
* limits. A field or window a reading leaves out, or reports malformed, keeps its last
|
|
43
|
+
* value (but see `Store.setClaudeReport` for a new conversation). Returns whether anything
|
|
44
|
+
* was taken.
|
|
45
|
+
*/
|
|
46
|
+
take(panes) {
|
|
47
|
+
const claimed = [];
|
|
48
|
+
for (const name of readdirSync(this.dir)) {
|
|
49
|
+
if (name.startsWith(CLAIMED)) {
|
|
50
|
+
// Left by a k-bench that stopped while taking it.
|
|
51
|
+
claimed.push(join(this.dir, name));
|
|
52
|
+
}
|
|
53
|
+
else if (name.startsWith(".") && name.endsWith(".tmp")) {
|
|
54
|
+
removeIfAbandoned(join(this.dir, name));
|
|
55
|
+
}
|
|
56
|
+
else if (!name.startsWith(".") && name.endsWith(".json")) {
|
|
57
|
+
const path = join(this.dir, `${CLAIMED}${name}`);
|
|
58
|
+
try {
|
|
59
|
+
// Renamed before reading, so a newer reading moved in meanwhile isn't lost.
|
|
60
|
+
renameSync(join(this.dir, name), path);
|
|
61
|
+
claimed.push(path);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
// Gone already.
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const readings = claimed
|
|
69
|
+
.map((path) => {
|
|
70
|
+
try {
|
|
71
|
+
const receivedAt = Math.round(statSync(path).mtimeMs);
|
|
72
|
+
const input = readFileSync(path, "utf8");
|
|
73
|
+
unlinkSync(path);
|
|
74
|
+
return { receivedAt, sessionId: whose(path, panes), ...readStatusLine(input) };
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
})
|
|
80
|
+
.filter((reading) => reading !== undefined)
|
|
81
|
+
.sort((a, b) => a.receivedAt - b.receivedAt);
|
|
82
|
+
this.store.transaction(() => {
|
|
83
|
+
for (const { receivedAt, sessionId, usageLimits: limits, report } of readings) {
|
|
84
|
+
if (limits.fiveHour)
|
|
85
|
+
this.store.setUsageLimit("fiveHour", { ...limits.fiveHour, receivedAt });
|
|
86
|
+
if (limits.weekly)
|
|
87
|
+
this.store.setUsageLimit("weekly", { ...limits.weekly, receivedAt });
|
|
88
|
+
if (sessionId !== undefined && report)
|
|
89
|
+
this.store.setClaudeReport(sessionId, report, receivedAt);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
return readings.length > 0;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The Session a claimed reading belongs to. The wrapper names a reading `<Session id>.json`.
|
|
97
|
+
* One launched by an earlier k-bench, still running in a Claude Session started before the
|
|
98
|
+
* upgrade, names it after its tmux pane, `<pane id without its %>.json`, all digits: that one
|
|
99
|
+
* is the Session's whose pane it is now, if any.
|
|
100
|
+
*/
|
|
101
|
+
function whose(path, panes) {
|
|
102
|
+
const name = basename(path, ".json").slice(CLAIMED.length);
|
|
103
|
+
return /^\d+$/.test(name) ? panes.get(`%${name}`) : name;
|
|
104
|
+
}
|
|
105
|
+
/** Removes a reading still being written if it has been for too long to be still going. */
|
|
106
|
+
function removeIfAbandoned(path) {
|
|
107
|
+
try {
|
|
108
|
+
if (Date.now() - statSync(path).mtimeMs > ABANDONED_MS)
|
|
109
|
+
unlinkSync(path);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
// Moved into place or removed meanwhile.
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -88,7 +88,37 @@ const MIGRATIONS = [
|
|
|
88
88
|
tabs TEXT NOT NULL
|
|
89
89
|
);
|
|
90
90
|
`,
|
|
91
|
+
// The Host's last reading of each of the owner's Usage limits: the share used, when its
|
|
92
|
+
// window resets and when the reading came (both milliseconds). One row per limit, none
|
|
93
|
+
// until the first reading of it, named as the state protocol names it.
|
|
94
|
+
`
|
|
95
|
+
CREATE TABLE usage_limits (
|
|
96
|
+
name TEXT PRIMARY KEY CHECK (name IN ('fiveHour', 'weekly')),
|
|
97
|
+
used_percentage REAL NOT NULL,
|
|
98
|
+
resets_at INTEGER NOT NULL,
|
|
99
|
+
received_at INTEGER NOT NULL
|
|
100
|
+
);
|
|
101
|
+
`,
|
|
102
|
+
// Each Claude Session's last report from Claude Code's status line: its Model, Context
|
|
103
|
+
// used, tokens used and context window size, each null until a report carries it, and when
|
|
104
|
+
// the newest report came (milliseconds). Dropped with its Session.
|
|
105
|
+
`
|
|
106
|
+
CREATE TABLE claude_reports (
|
|
107
|
+
session_id TEXT PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
|
|
108
|
+
model TEXT,
|
|
109
|
+
context_used REAL,
|
|
110
|
+
tokens_used INTEGER,
|
|
111
|
+
context_window INTEGER,
|
|
112
|
+
received_at INTEGER NOT NULL
|
|
113
|
+
);
|
|
114
|
+
`,
|
|
115
|
+
// The Claude conversation a Claude Session's last report was made on, null until a report
|
|
116
|
+
// names one: Context used belongs to the conversation, so a new one starts it afresh.
|
|
117
|
+
"ALTER TABLE claude_reports ADD COLUMN conversation_id TEXT",
|
|
91
118
|
];
|
|
119
|
+
/** In `setClaudeReport`'s upsert: the report names another conversation than the last did. */
|
|
120
|
+
const NEW_CONVERSATION = "excluded.conversation_id IS NOT NULL AND claude_reports.conversation_id IS NOT NULL" +
|
|
121
|
+
" AND excluded.conversation_id <> claude_reports.conversation_id";
|
|
92
122
|
/**
|
|
93
123
|
* Records a Prime and a Worker for every Workspace. Existing Sessions stay as Other Sessions;
|
|
94
124
|
* one already named "Prime" or "Worker" is renamed first, to "Prime (earlier)" for example,
|
|
@@ -285,6 +315,78 @@ export class Store {
|
|
|
285
315
|
ON CONFLICT (id) DO UPDATE SET workspace_id = excluded.workspace_id`)
|
|
286
316
|
.run(workspaceId);
|
|
287
317
|
}
|
|
318
|
+
/** The last reading of each Usage limit; null for one never read. */
|
|
319
|
+
getUsageLimits() {
|
|
320
|
+
const rows = this.db
|
|
321
|
+
.prepare(`SELECT name, used_percentage AS usedPercentage, resets_at AS resetsAt,
|
|
322
|
+
received_at AS receivedAt
|
|
323
|
+
FROM usage_limits`)
|
|
324
|
+
.all();
|
|
325
|
+
const limit = (name) => {
|
|
326
|
+
const row = rows.find((r) => r.name === name);
|
|
327
|
+
return row
|
|
328
|
+
? {
|
|
329
|
+
usedPercentage: row.usedPercentage,
|
|
330
|
+
resetsAt: row.resetsAt,
|
|
331
|
+
receivedAt: row.receivedAt,
|
|
332
|
+
}
|
|
333
|
+
: null;
|
|
334
|
+
};
|
|
335
|
+
return { fiveHour: limit("fiveHour"), weekly: limit("weekly") };
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Records a reading of one Usage limit in place of the last, unless the last was received
|
|
339
|
+
* later: the newest reading wins whatever order they are recorded in.
|
|
340
|
+
*/
|
|
341
|
+
setUsageLimit(limit, reading) {
|
|
342
|
+
this.db
|
|
343
|
+
.prepare(`INSERT INTO usage_limits (name, used_percentage, resets_at, received_at)
|
|
344
|
+
VALUES (?, ?, ?, ?)
|
|
345
|
+
ON CONFLICT (name) DO UPDATE SET
|
|
346
|
+
used_percentage = excluded.used_percentage,
|
|
347
|
+
resets_at = excluded.resets_at,
|
|
348
|
+
received_at = excluded.received_at
|
|
349
|
+
WHERE excluded.received_at >= usage_limits.received_at`)
|
|
350
|
+
.run(limit, reading.usedPercentage, reading.resetsAt, reading.receivedAt);
|
|
351
|
+
}
|
|
352
|
+
/** Every Claude Session's last report, by Session id; a Session with none is left out. */
|
|
353
|
+
getClaudeReports() {
|
|
354
|
+
const rows = this.db
|
|
355
|
+
.prepare(`SELECT session_id AS sessionId, model, context_used AS contextUsed,
|
|
356
|
+
tokens_used AS tokensUsed, context_window AS contextWindow
|
|
357
|
+
FROM claude_reports`)
|
|
358
|
+
.all();
|
|
359
|
+
return new Map(rows.map(({ sessionId, model, contextUsed, tokensUsed, contextWindow }) => [
|
|
360
|
+
sessionId,
|
|
361
|
+
{ model, contextUsed, tokensUsed, contextWindow },
|
|
362
|
+
]));
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Records a Claude Session's report over its last: a field the report leaves out keeps its
|
|
366
|
+
* last value, except that a report on another Claude conversation than the last (after
|
|
367
|
+
* `/clear`, say) replaces Context used and its tokens outright, even with nothing. A report
|
|
368
|
+
* that names no conversation, or follows one that named none, counts as the same one. A
|
|
369
|
+
* report received before the last is ignored, and a Session that is gone, or is a shell, is
|
|
370
|
+
* left alone.
|
|
371
|
+
*/
|
|
372
|
+
setClaudeReport(sessionId, report, receivedAt) {
|
|
373
|
+
this.db
|
|
374
|
+
.prepare(`INSERT INTO claude_reports
|
|
375
|
+
(session_id, model, context_used, tokens_used, context_window, conversation_id,
|
|
376
|
+
received_at)
|
|
377
|
+
SELECT id, ?, ?, ?, ?, ?, ? FROM sessions WHERE id = ? AND kind = 'claude'
|
|
378
|
+
ON CONFLICT (session_id) DO UPDATE SET
|
|
379
|
+
model = COALESCE(excluded.model, claude_reports.model),
|
|
380
|
+
context_used = CASE WHEN ${NEW_CONVERSATION} THEN excluded.context_used
|
|
381
|
+
ELSE COALESCE(excluded.context_used, claude_reports.context_used) END,
|
|
382
|
+
tokens_used = CASE WHEN ${NEW_CONVERSATION} THEN excluded.tokens_used
|
|
383
|
+
ELSE COALESCE(excluded.tokens_used, claude_reports.tokens_used) END,
|
|
384
|
+
context_window = COALESCE(excluded.context_window, claude_reports.context_window),
|
|
385
|
+
conversation_id = COALESCE(excluded.conversation_id, claude_reports.conversation_id),
|
|
386
|
+
received_at = excluded.received_at
|
|
387
|
+
WHERE excluded.received_at >= claude_reports.received_at`)
|
|
388
|
+
.run(report.model ?? null, report.contextUsed ?? null, report.tokensUsed ?? null, report.contextWindow ?? null, report.conversationId ?? null, receivedAt, sessionId);
|
|
389
|
+
}
|
|
288
390
|
/**
|
|
289
391
|
* Records the Claude conversation a Claude Session is now on, in place: no history is kept.
|
|
290
392
|
* A shell Session, or one not stored yet, is left alone.
|
|
@@ -2,7 +2,7 @@ import { execFile, spawn } from "node:child_process";
|
|
|
2
2
|
import { userInfo } from "node:os";
|
|
3
3
|
import { promisify } from "node:util";
|
|
4
4
|
import * as pty from "node-pty";
|
|
5
|
-
import { ACTIVITY_AT_OPTION, ACTIVITY_CHANNEL, ACTIVITY_OPTION, CONVERSATION_CHANNEL, CONVERSATION_OPTION, claudeCommand, } from "./claude.js";
|
|
5
|
+
import { ACTIVITY_AT_OPTION, ACTIVITY_CHANNEL, ACTIVITY_OPTION, CONVERSATION_CHANNEL, CONVERSATION_OPTION, claudeCommand, READINGS_CHANNEL, } from "./claude.js";
|
|
6
6
|
const execFileAsync = promisify(execFile);
|
|
7
7
|
/** Every Session is a tmux session named `kb-<session id>` on the instance's socket. */
|
|
8
8
|
const PREFIX = "kb-";
|
|
@@ -130,11 +130,11 @@ export class TmuxDriver {
|
|
|
130
130
|
socket;
|
|
131
131
|
/** Channel watches, which a new tmux server must wake (see `watchBells`). */
|
|
132
132
|
watches = new Set();
|
|
133
|
-
/**
|
|
134
|
-
|
|
135
|
-
constructor(socket,
|
|
133
|
+
/** How a Claude Session is launched on this Host; without it, only shells can start. */
|
|
134
|
+
claude;
|
|
135
|
+
constructor(socket, claude) {
|
|
136
136
|
this.socket = socket;
|
|
137
|
-
this.
|
|
137
|
+
this.claude = claude;
|
|
138
138
|
}
|
|
139
139
|
env() {
|
|
140
140
|
// A k-bench server started from inside a tmux pane must not think it is nested, and
|
|
@@ -166,14 +166,23 @@ export class TmuxDriver {
|
|
|
166
166
|
* or, given `claude`, Claude Code.
|
|
167
167
|
*/
|
|
168
168
|
async createSession(id, folder, claude) {
|
|
169
|
-
|
|
170
|
-
|
|
169
|
+
let command;
|
|
170
|
+
if (claude) {
|
|
171
|
+
if (!this.claude)
|
|
172
|
+
throw new Error("this TmuxDriver can't launch Claude Code");
|
|
173
|
+
const { program, ...statusLine } = this.claude;
|
|
174
|
+
command = claudeCommand({
|
|
171
175
|
folder,
|
|
172
176
|
shell: ownerShell(),
|
|
173
|
-
program
|
|
177
|
+
program,
|
|
178
|
+
sessionId: id,
|
|
179
|
+
statusLine,
|
|
174
180
|
launch: claude,
|
|
175
|
-
})
|
|
176
|
-
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
command = sessionCommand(folder);
|
|
185
|
+
}
|
|
177
186
|
await this.run(...serverConfiguration(), [
|
|
178
187
|
"new-session",
|
|
179
188
|
"-d",
|
|
@@ -225,6 +234,15 @@ export class TmuxDriver {
|
|
|
225
234
|
watchActivity(onChange) {
|
|
226
235
|
return this.watchChannel(ACTIVITY_CHANNEL, onChange);
|
|
227
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* Calls `onChange` soon after Claude Code in any Claude Session leaves a status line
|
|
239
|
+
* reading (and now and then when none did), until stopped; `StatusLineReadings` then has it.
|
|
240
|
+
* Like the Bells, signals are missed only while no tmux server runs; the reading itself
|
|
241
|
+
* waits in its folder.
|
|
242
|
+
*/
|
|
243
|
+
watchReadings(onChange) {
|
|
244
|
+
return this.watchChannel(READINGS_CHANNEL, onChange);
|
|
245
|
+
}
|
|
228
246
|
watchChannel(channel, onChange) {
|
|
229
247
|
const watch = new ChannelWatcher([...this.baseArgs(), "wait-for", channel], this.env(), {
|
|
230
248
|
onChange,
|
|
@@ -255,7 +273,7 @@ export class TmuxDriver {
|
|
|
255
273
|
"list-sessions",
|
|
256
274
|
"-F",
|
|
257
275
|
// The conversation goes last: it is read as the rest of the line.
|
|
258
|
-
`#{session_name}\t#{${BELL_OPTION}}\t#{${ACTIVITY_OPTION}}\t#{${ACTIVITY_AT_OPTION}}\t#{window_activity}\t#{${CONVERSATION_OPTION}}`,
|
|
276
|
+
`#{session_name}\t#{pane_id}\t#{${BELL_OPTION}}\t#{${ACTIVITY_OPTION}}\t#{${ACTIVITY_AT_OPTION}}\t#{window_activity}\t#{${CONVERSATION_OPTION}}`,
|
|
259
277
|
]);
|
|
260
278
|
}
|
|
261
279
|
catch (error) {
|
|
@@ -267,9 +285,10 @@ export class TmuxDriver {
|
|
|
267
285
|
.split("\n")
|
|
268
286
|
.filter((line) => line.startsWith(PREFIX))
|
|
269
287
|
.map((line) => {
|
|
270
|
-
const [name = "", bell = "", activity = "", at = "", output = "", ...conversation] = line.split("\t");
|
|
288
|
+
const [name = "", pane = "", bell = "", activity = "", at = "", output = "", ...conversation] = line.split("\t");
|
|
271
289
|
return {
|
|
272
290
|
id: name.slice(PREFIX.length),
|
|
291
|
+
pane,
|
|
273
292
|
bell: bell !== "",
|
|
274
293
|
activity: activityOf(activity),
|
|
275
294
|
lastChange: Math.max(Number(at) || 0, Number(output) || 0),
|