@k-electron/k-bench 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -24
- package/dist/js/src/server/app.js +37 -8
- package/dist/js/src/server/attachments.js +38 -0
- package/dist/js/src/server/claude.js +146 -8
- package/dist/js/src/server/config.js +1 -0
- package/dist/js/src/server/directories.js +6 -3
- package/dist/js/src/server/reconciler.js +13 -3
- package/dist/js/src/server/server.js +13 -1
- package/dist/js/src/server/service.js +274 -26
- package/dist/js/src/server/store.js +183 -20
- package/dist/js/src/server/tmux.js +131 -26
- package/dist/js/src/shared/launch-options.js +9 -0
- package/dist/js/src/shared/session-roles.js +11 -0
- package/dist/web/assets/index-BtYgPWZ6.js +74 -0
- package/dist/web/assets/index-CWZyOJf0.css +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +5 -6
- package/dist/web/assets/index-BStYcuMO.css +0 -1
- package/dist/web/assets/index-QWsANvSc.js +0 -74
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Persistent terminal Sessions on your Mac, organised into Workspaces, reachable from any browser on your tailnet. It launches Claude Code, and resumes it when you restart.
|
|
4
4
|
|
|
5
|
-

|
|
6
6
|
|
|
7
7
|
k-bench is macOS-only, and Tailscale is the only way in. It runs on your Mac as a background service and shows your terminals in a web page that only your own tailnet login can open.
|
|
8
8
|
|
|
@@ -19,43 +19,32 @@ It is not only for Claude Code. **New shell** gives you a plain shell Session, s
|
|
|
19
19
|
|
|
20
20
|
## What you get
|
|
21
21
|
|
|
22
|
-
- **Sessions that keep running** when you close the tab, lock your phone or lose your connection. Come back from any
|
|
23
|
-
- **
|
|
24
|
-
- **
|
|
25
|
-
- **
|
|
26
|
-
- **
|
|
27
|
-
- **
|
|
22
|
+
- **Sessions that keep running** when you close the browser tab, lock your phone or lose your connection. Come back from any Device and pick up where you left off.
|
|
23
|
+
- **A Workspace per project.** A Workspace points at a project folder on your Mac, and its Sessions start there.
|
|
24
|
+
- **A Prime and a Worker in every Workspace.** Two Claude Sessions that k-bench launches with fixed Launch options: the Prime plans in the left Pane, and the Worker builds in the right one. Opening the Workspace starts them, and a restart resumes each one's Claude conversation, even after a reboot or a `/clear`.
|
|
25
|
+
- **The Open Workspace follows you between Devices.** Open a Workspace on your laptop, and your phone shows it too.
|
|
26
|
+
- **Other Sessions in the right Pane's Tabs.** **New shell** for a dev server or a test watcher, or **New Claude…** to launch Claude Code with the model, effort, advisor and Focus view you choose.
|
|
27
|
+
- **Room when you need it.** Drag the divider to an edge to shut a Pane, and give the other one the whole width.
|
|
28
|
+
- **Bells.** When a Session rings the terminal bell, the sidebar marks it until you look at it.
|
|
29
|
+
- **A Phone layout** with a drawer for your Workspaces and Extra keys (Esc, Tab, Shift-Tab, Ctrl, the arrows and Enter) for the keys a phone keyboard lacks.
|
|
28
30
|
- **Access only for your tailnet login.** k-bench listens on localhost only and is published with `tailscale serve`. It admits only requests that carry your own tailnet login.
|
|
29
31
|
|
|
30
|
-

|
|
31
33
|
|
|
32
34
|
## Quick start
|
|
33
35
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
- A Mac (k-bench is macOS-only).
|
|
37
|
-
- [Node](https://nodejs.org/) 26 or later.
|
|
38
|
-
- tmux (`brew install tmux`).
|
|
39
|
-
- [Tailscale](https://tailscale.com/download), signed in, with HTTPS certificates turned on for your tailnet. [Setup](docs/guide/setup.md#1-set-up-tailscale) has the steps.
|
|
40
|
-
|
|
41
|
-
**Then:**
|
|
36
|
+
First get what [Setup](docs/guide/setup.md) says you need, and [set up Tailscale](docs/guide/setup.md#1-set-up-tailscale). Then:
|
|
42
37
|
|
|
43
38
|
```sh
|
|
44
39
|
npm i -g @k-electron/k-bench
|
|
45
40
|
k-bench install
|
|
46
41
|
```
|
|
47
42
|
|
|
48
|
-
`k-bench install`
|
|
49
|
-
|
|
50
|
-
Something not working? Run `k-bench status`: it checks each part and says how to fix what fails.
|
|
43
|
+
`k-bench install` publishes k-bench on your tailnet and prints its URL. Open that URL from any device signed in to your tailnet with the same login. [Setup](docs/guide/setup.md) covers the install, updating and uninstalling. If something isn't working, run `k-bench status`.
|
|
51
44
|
|
|
52
45
|
## Guide
|
|
53
46
|
|
|
54
|
-
- [The guide](docs/guide/README.md), with
|
|
55
|
-
- [Setup](docs/guide/setup.md): Tailscale, installing, updating, uninstalling.
|
|
56
|
-
- [Using k-bench](docs/guide/using-k-bench.md): Workspaces, Sessions, Claude Sessions, Panes, Bells, scrolling and copying, the phone layout.
|
|
57
|
-
- [Using k-bench with Claude Code](docs/guide/claude-code.md): Claude Sessions and the New Claude dialog, Focus view, resuming on restart, making Claude Code ring the Bell, and working with several conversations.
|
|
58
|
-
- [Troubleshooting](docs/guide/troubleshooting.md): start from `k-bench status`.
|
|
47
|
+
- [The guide](docs/guide/README.md): setup, using k-bench, using it with Claude Code, and troubleshooting.
|
|
59
48
|
- [CHANGELOG](CHANGELOG.md): what changed in each version.
|
|
60
49
|
|
|
61
50
|
## Security
|
|
@@ -30,7 +30,7 @@ function optionalString(value) {
|
|
|
30
30
|
return typeof value === "string" ? value : undefined;
|
|
31
31
|
}
|
|
32
32
|
/** The JSON HTTP API. */
|
|
33
|
-
export function createApp(service, options
|
|
33
|
+
export function createApp(service, options) {
|
|
34
34
|
const app = new Hono();
|
|
35
35
|
app.onError((error, c) => {
|
|
36
36
|
if (error instanceof HTTPException) {
|
|
@@ -38,7 +38,7 @@ export function createApp(service, options = {}) {
|
|
|
38
38
|
}
|
|
39
39
|
if (error instanceof ServiceError) {
|
|
40
40
|
const status = error.kind === "not_found" ? 404 : error.kind === "conflict" ? 409 : 422;
|
|
41
|
-
return c.json({ error: error.message }, status);
|
|
41
|
+
return c.json({ ...error.details, error: error.message }, status);
|
|
42
42
|
}
|
|
43
43
|
console.error(error);
|
|
44
44
|
return c.json({ error: "Internal error" }, 500);
|
|
@@ -56,13 +56,14 @@ export function createApp(service, options = {}) {
|
|
|
56
56
|
// caller must send the owner's login.
|
|
57
57
|
app.get("/api/health", (c) => c.json({ status: "ok" }));
|
|
58
58
|
app.get("/api/state", async (c) => c.json(await service.getState()));
|
|
59
|
-
// The folder picker.
|
|
59
|
+
// The folder picker. Without a path it lists where the picker opens; every answer names
|
|
60
|
+
// the picker root (Home), which the picker shows among its Places.
|
|
60
61
|
app.get("/api/directories", (c) => {
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
throw new ServiceError("invalid", "path is required");
|
|
62
|
+
const root = options.pickerRoot;
|
|
63
|
+
const path = c.req.query("path") || service.pickerStart(root);
|
|
64
64
|
try {
|
|
65
|
-
|
|
65
|
+
const hidden = c.req.query("hidden") === "1";
|
|
66
|
+
return c.json({ ...listDirectories(path, { hidden }), root });
|
|
66
67
|
}
|
|
67
68
|
catch (error) {
|
|
68
69
|
if (error instanceof DirectoryError) {
|
|
@@ -79,6 +80,7 @@ export function createApp(service, options = {}) {
|
|
|
79
80
|
const workspace = service.createWorkspace({
|
|
80
81
|
folder,
|
|
81
82
|
name: optionalString(body.name),
|
|
83
|
+
createMissingFolders: body.createMissingFolders === true,
|
|
82
84
|
});
|
|
83
85
|
return c.json(workspace, 201);
|
|
84
86
|
});
|
|
@@ -93,16 +95,43 @@ export function createApp(service, options = {}) {
|
|
|
93
95
|
});
|
|
94
96
|
app.patch("/api/workspaces/:id", async (c) => {
|
|
95
97
|
const body = await jsonBody(c.req.raw);
|
|
96
|
-
const workspace = service.updateWorkspace(c.req.param("id"), {
|
|
98
|
+
const workspace = await service.updateWorkspace(c.req.param("id"), {
|
|
97
99
|
name: optionalString(body.name),
|
|
98
100
|
folder: optionalString(body.folder),
|
|
101
|
+
createMissingFolders: body.createMissingFolders === true,
|
|
99
102
|
});
|
|
100
103
|
return c.json(workspace);
|
|
101
104
|
});
|
|
105
|
+
app.post("/api/workspaces/:id/open", async (c) => {
|
|
106
|
+
const body = await jsonBody(c.req.raw);
|
|
107
|
+
return c.json(await service.openWorkspace(c.req.param("id"), {
|
|
108
|
+
showWorker: body.showWorker === true,
|
|
109
|
+
}));
|
|
110
|
+
});
|
|
111
|
+
// The whole record: the tabs in order, and the one shown (null for the Worker).
|
|
112
|
+
app.put("/api/workspaces/:id/right-pane", async (c) => {
|
|
113
|
+
const { shown, tabs } = await jsonBody(c.req.raw);
|
|
114
|
+
if (!Array.isArray(tabs) || !tabs.every((id) => typeof id === "string")) {
|
|
115
|
+
throw new ServiceError("invalid", "tabs must be a list of Session ids");
|
|
116
|
+
}
|
|
117
|
+
if (shown !== null && typeof shown !== "string") {
|
|
118
|
+
throw new ServiceError("invalid", "shown must be a Session id or null");
|
|
119
|
+
}
|
|
120
|
+
service.setRightPane(c.req.param("id"), { shown, tabs });
|
|
121
|
+
return c.json({ shown, tabs });
|
|
122
|
+
});
|
|
102
123
|
app.delete("/api/workspaces/:id", async (c) => {
|
|
103
124
|
await service.deleteWorkspace(c.req.param("id"));
|
|
104
125
|
return c.body(null, 204);
|
|
105
126
|
});
|
|
127
|
+
app.put("/api/workspaces/:id/sessions/order", async (c) => {
|
|
128
|
+
const { ids } = await jsonBody(c.req.raw);
|
|
129
|
+
if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) {
|
|
130
|
+
throw new ServiceError("invalid", "ids must be a list of Session ids");
|
|
131
|
+
}
|
|
132
|
+
service.reorderSessions(c.req.param("id"), ids);
|
|
133
|
+
return c.json({ ids });
|
|
134
|
+
});
|
|
106
135
|
app.post("/api/workspaces/:id/sessions", async (c) => {
|
|
107
136
|
const body = await jsonBody(c.req.raw);
|
|
108
137
|
// `claude` makes it a Claude Session; its Launch options are checked before anything starts.
|
|
@@ -20,10 +20,34 @@ export class Attachments {
|
|
|
20
20
|
constructor(tmux, sessions) {
|
|
21
21
|
/** Per Session, the terminal the window was last sized for (see `writeSizedToTyper`). */
|
|
22
22
|
const lastTyper = new Map();
|
|
23
|
+
/**
|
|
24
|
+
* Per Session with an `endWaiting` under way, whether another key came meanwhile. A run
|
|
25
|
+
* of keys asks tmux one at a time, and once more after the last, so no key is dropped.
|
|
26
|
+
*/
|
|
27
|
+
const endingWaiting = new Map();
|
|
28
|
+
const endWaiting = (sessionId) => {
|
|
29
|
+
endingWaiting.set(sessionId, false);
|
|
30
|
+
// A Session that went away has no state to end; its tmux client's exit reports it.
|
|
31
|
+
void tmux
|
|
32
|
+
.endWaiting(sessionId)
|
|
33
|
+
.catch(() => { })
|
|
34
|
+
.finally(() => {
|
|
35
|
+
const again = endingWaiting.get(sessionId);
|
|
36
|
+
endingWaiting.delete(sessionId);
|
|
37
|
+
if (again)
|
|
38
|
+
endWaiting(sessionId);
|
|
39
|
+
});
|
|
40
|
+
};
|
|
23
41
|
this.context = {
|
|
24
42
|
tmux,
|
|
25
43
|
sessions,
|
|
26
44
|
lastTyper,
|
|
45
|
+
ownerTyped: (sessionId) => {
|
|
46
|
+
if (endingWaiting.has(sessionId))
|
|
47
|
+
endingWaiting.set(sessionId, true);
|
|
48
|
+
else
|
|
49
|
+
endWaiting(sessionId);
|
|
50
|
+
},
|
|
27
51
|
forget: (terminal) => {
|
|
28
52
|
this.terminals.delete(terminal);
|
|
29
53
|
if (lastTyper.get(terminal.sessionId) === terminal) {
|
|
@@ -145,6 +169,8 @@ class Terminal {
|
|
|
145
169
|
if (this.phase === "looking-up")
|
|
146
170
|
this.pendingInput.push({ data, automatic });
|
|
147
171
|
else if (this.phase === "attached") {
|
|
172
|
+
if (!automatic && !isOnlyMouseReports(data))
|
|
173
|
+
this.context.ownerTyped(this.sessionId);
|
|
148
174
|
const write = automatic
|
|
149
175
|
? () => this.write(data)
|
|
150
176
|
: () => this.writeSizedToTyper(data);
|
|
@@ -258,6 +284,18 @@ class Terminal {
|
|
|
258
284
|
}
|
|
259
285
|
}
|
|
260
286
|
}
|
|
287
|
+
/**
|
|
288
|
+
* Whether `data` is nothing but mouse reports: what xterm.js sends for a click, a drag or the
|
|
289
|
+
* wheel once tmux asks for the mouse, as SGR (`ESC[<b;x;yM`) or legacy (`ESC[M` and three
|
|
290
|
+
* bytes, none of them ESC). Scrolling or clicking is not the owner answering a Session, so
|
|
291
|
+
* it doesn't end Waiting.
|
|
292
|
+
*/
|
|
293
|
+
function isOnlyMouseReports(data) {
|
|
294
|
+
const [before, ...reports] = data.split("\x1b");
|
|
295
|
+
return (before === "" &&
|
|
296
|
+
reports.length > 0 &&
|
|
297
|
+
reports.every((report) => /^\[<\d+;\d+;\d+[Mm]$/.test(report) || /^\[M.{3}$/su.test(report)));
|
|
298
|
+
}
|
|
261
299
|
/** Whether `promise` settles within `ms`. */
|
|
262
300
|
async function settlesWithin(promise, ms) {
|
|
263
301
|
let timer;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Launching Claude Code for a Claude Session (ADR-0005). k-bench starts it through its
|
|
3
|
-
* documented command-line flags and
|
|
4
|
-
* k-bench knows about Claude Code is in
|
|
5
|
-
* script that runs it.
|
|
3
|
+
* documented command-line flags and learns which conversation it is on, and whether it is
|
|
4
|
+
* Working, Waiting or Idle, through silent hooks, so everything k-bench knows about Claude Code is in
|
|
5
|
+
* this file: the flags it passes, the hooks, and the launcher script that runs it.
|
|
6
6
|
*/
|
|
7
7
|
import { DEFAULT_LAUNCH_OPTIONS, LAUNCH_CHOICES, } from "../shared/launch-options.js";
|
|
8
8
|
/**
|
|
@@ -36,15 +36,152 @@ export function parseLaunchOptions(value) {
|
|
|
36
36
|
return { options };
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
|
-
*
|
|
39
|
+
* The tmux pane user option the conversation hook writes the conversation ID to, on the pane
|
|
40
|
+
* Claude Code runs in, and the tmux `wait-for` channel it signals after (see `TmuxDriver`).
|
|
41
|
+
*/
|
|
42
|
+
export const CONVERSATION_OPTION = "@kb-conversation";
|
|
43
|
+
export const CONVERSATION_CHANNEL = "kb-conversation-changed";
|
|
44
|
+
/**
|
|
45
|
+
* Claude Code runs this `SessionStart` hook whenever a conversation starts in the Session,
|
|
46
|
+
* whatever started it: the launch, `/clear`, `/resume`, `/branch`, compaction (which keeps
|
|
47
|
+
* the ID) or a `/restart`. It takes `session_id` from the JSON on stdin and records it on its
|
|
48
|
+
* own tmux pane, then signals the channel, as the Bell does.
|
|
49
|
+
*
|
|
50
|
+
* Claude Code adds a `SessionStart` hook's output to the conversation, so it prints nothing,
|
|
51
|
+
* and it exits 0 whatever happens, so a missing tool never shows in Claude Code (ADR-0005).
|
|
52
|
+
* It is one line of plain POSIX `sh` with tools every Mac has (no `jq`), because it runs
|
|
53
|
+
* under the owner's own environment. Bare `tmux` reaches k-bench's socket through `$TMUX`,
|
|
54
|
+
* which tmux sets in the pane. The ID is passed as an argument, so it cannot inject into a
|
|
55
|
+
* tmux command; k-bench ignores one that isn't UUID-shaped.
|
|
56
|
+
*/
|
|
57
|
+
const CONVERSATION_HOOK = [
|
|
58
|
+
"{",
|
|
59
|
+
`id=$(tr -d '\\n' | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p');`,
|
|
60
|
+
'[ -n "$id" ] && [ -n "$TMUX_PANE" ] &&',
|
|
61
|
+
`tmux set-option -p -t "$TMUX_PANE" ${CONVERSATION_OPTION} "$id" &&`,
|
|
62
|
+
`tmux wait-for -S ${CONVERSATION_CHANNEL};`,
|
|
63
|
+
"} >/dev/null 2>&1; exit 0",
|
|
64
|
+
].join(" ");
|
|
65
|
+
/**
|
|
66
|
+
* The tmux pane user option the activity hooks write a Claude Session's state to (a
|
|
67
|
+
* `SessionActivity`), on the pane Claude Code runs in, and the tmux `wait-for` channel they
|
|
68
|
+
* signal after, so the state feed re-reads at once (see `TmuxDriver`). It is empty until a
|
|
69
|
+
* hook has run, which reads as Idle.
|
|
70
|
+
*/
|
|
71
|
+
export const ACTIVITY_OPTION = "@kb-activity";
|
|
72
|
+
export const ACTIVITY_CHANNEL = "kb-activity-changed";
|
|
73
|
+
/**
|
|
74
|
+
* The pane option every write of `ACTIVITY_OPTION` stamps with the time, in epoch seconds, so
|
|
75
|
+
* a state written moments ago is never taken for a quiet one (see `TmuxDriver.decayWorking`).
|
|
76
|
+
*/
|
|
77
|
+
export const ACTIVITY_AT_OPTION = "@kb-activity-at";
|
|
78
|
+
/**
|
|
79
|
+
* Matches the stdin of an event fired inside a subagent (or a teammate), which carries an
|
|
80
|
+
* `agent_id` key. It can't match inside a value, such as a prompt, since JSON escapes a `"`
|
|
81
|
+
* there. A subagent's turn, its tools and its finish say nothing about the Session's own
|
|
82
|
+
* turn, so most activity hooks ignore such events (see `ACTIVITY_EVENTS`). The hooks
|
|
83
|
+
* reference documents `agent_id` as the subagent's or teammate's ID; the main agent started
|
|
84
|
+
* with `--agent` carries only `agent_type`, so that is never tested.
|
|
85
|
+
*/
|
|
86
|
+
const FROM_AN_AGENT = '"agent_id"[[:space:]]*:';
|
|
87
|
+
/**
|
|
88
|
+
* The hook that records `activity`, and the time, on its own tmux pane in one tmux call, and
|
|
89
|
+
* signals the channel, unless its stdin matches one of `ignore` (extended regexes). It is
|
|
90
|
+
* built like the conversation hook, for the same reasons: it prints nothing, exits 0
|
|
91
|
+
* whatever happens, and is one line of plain `sh` with no `jq`. The state it writes is
|
|
92
|
+
* k-bench's own word, never taken from stdin.
|
|
93
|
+
*/
|
|
94
|
+
function activityHook(activity, ignore) {
|
|
95
|
+
// With nothing to ignore there is no test at all: an empty pattern would match anything.
|
|
96
|
+
const skip = ignore.length
|
|
97
|
+
? `printf '%s' "$input" | grep -Eq '${ignore.join("|")}'`
|
|
98
|
+
: "false";
|
|
99
|
+
return [
|
|
100
|
+
"{",
|
|
101
|
+
// Read whole either way, so Claude Code never writes to a hook that has gone.
|
|
102
|
+
"input=$(tr -d '\\n');",
|
|
103
|
+
`if ${skip}; then :;`,
|
|
104
|
+
'elif [ -n "$TMUX_PANE" ]; then',
|
|
105
|
+
// Stamped first, so a decay never sees the new state with the old time.
|
|
106
|
+
`tmux set-option -p -t "$TMUX_PANE" ${ACTIVITY_AT_OPTION} "$(date +%s)"`,
|
|
107
|
+
`\\; set-option -p -t "$TMUX_PANE" ${ACTIVITY_OPTION} ${activity} &&`,
|
|
108
|
+
`tmux wait-for -S ${ACTIVITY_CHANNEL};`,
|
|
109
|
+
"fi;",
|
|
110
|
+
"} >/dev/null 2>&1; exit 0",
|
|
111
|
+
].join(" ");
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Which Claude Code hook events set which state (see Working, Waiting and Idle in the
|
|
115
|
+
* glossary):
|
|
116
|
+
* - `SessionStart`: a new or restarted Claude Session, or a new conversation in one, starts
|
|
117
|
+
* Idle. Not on compaction, which can happen mid-turn and keeps the turn going.
|
|
118
|
+
* - `UserPromptSubmit`: a turn starts, so Working.
|
|
119
|
+
* - `PermissionRequest` (a permission prompt), `PreToolUse` for `AskUserQuestion` (a
|
|
120
|
+
* question) and `ExitPlanMode` (a plan to approve), and `Elicitation` (an MCP server's
|
|
121
|
+
* question): Claude Code stops mid-turn for the owner, so Waiting. `PermissionRequest` fires
|
|
122
|
+
* as the prompt shows; the `Notification` for it waits about six seconds, so it isn't used.
|
|
123
|
+
* The hooks reference doesn't say whether approving a plan is a permission prompt, so
|
|
124
|
+
* `ExitPlanMode` is matched as well; if it is, the two agree.
|
|
125
|
+
* - `PostToolUse`, `PostToolUseFailure` and `ElicitationResult`: the owner answered, or a
|
|
126
|
+
* tool finished, so Working. No hook fires when the owner denies a tool, so the owner's
|
|
127
|
+
* own key ends Waiting too (see `TmuxDriver.endWaiting`).
|
|
128
|
+
* - `Stop`, and `StopFailure` (fired instead when an API error ends the turn): the turn is
|
|
129
|
+
* over, so Idle. Neither fires for a subagent.
|
|
130
|
+
* `matcher` is the hook group's tool name matcher, for a tool event. Each hook ignores an
|
|
131
|
+
* event from a subagent (`FROM_AN_AGENT`), except a `PermissionRequest` or `Elicitation`
|
|
132
|
+
* (`anyAgent`): a prompt needs the owner whoever asked. A subagent's Waiting then ends as any
|
|
133
|
+
* other does, by the owner's key or the main agent's next event.
|
|
134
|
+
*/
|
|
135
|
+
const ACTIVITY_EVENTS = [
|
|
136
|
+
{
|
|
137
|
+
event: "SessionStart",
|
|
138
|
+
activity: "idle",
|
|
139
|
+
ignore: '"source"[[:space:]]*:[[:space:]]*"compact"',
|
|
140
|
+
},
|
|
141
|
+
{ event: "UserPromptSubmit", activity: "working" },
|
|
142
|
+
{ event: "PermissionRequest", activity: "waiting", anyAgent: true },
|
|
143
|
+
{ event: "PreToolUse", activity: "waiting", matcher: "AskUserQuestion|ExitPlanMode" },
|
|
144
|
+
{ event: "Elicitation", activity: "waiting", anyAgent: true },
|
|
145
|
+
{ event: "PostToolUse", activity: "working" },
|
|
146
|
+
{ event: "PostToolUseFailure", activity: "working" },
|
|
147
|
+
{ event: "ElicitationResult", activity: "working" },
|
|
148
|
+
{ event: "Stop", activity: "idle" },
|
|
149
|
+
{ event: "StopFailure", activity: "idle" },
|
|
150
|
+
];
|
|
151
|
+
/** Every hook k-bench passes, by Claude Code hook event: the conversation's, then the states'. */
|
|
152
|
+
function launchHooks() {
|
|
153
|
+
const hooks = {
|
|
154
|
+
SessionStart: [{ hooks: [{ type: "command", command: CONVERSATION_HOOK }] }],
|
|
155
|
+
};
|
|
156
|
+
for (const { event, activity, matcher, ignore, anyAgent } of ACTIVITY_EVENTS) {
|
|
157
|
+
const ignored = [...(anyAgent ? [] : [FROM_AN_AGENT]), ...(ignore ? [ignore] : [])];
|
|
158
|
+
hooks[event] = [
|
|
159
|
+
...(hooks[event] ?? []),
|
|
160
|
+
{
|
|
161
|
+
...(matcher ? { matcher } : {}),
|
|
162
|
+
hooks: [{ type: "command", command: activityHook(activity, ignored) }],
|
|
163
|
+
},
|
|
164
|
+
];
|
|
165
|
+
}
|
|
166
|
+
return hooks;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* The `--settings` every launch passes: k-bench's hooks and, with Focus view on, its keys.
|
|
170
|
+
* Focus view needs both keys: it does nothing without the fullscreen renderer, and
|
|
40
171
|
* fullscreen is not the default on every machine. `--settings` applies to that launch only
|
|
41
|
-
* and
|
|
172
|
+
* and adds to the owner's own settings and hooks, leaving their files unchanged.
|
|
42
173
|
*/
|
|
43
|
-
|
|
174
|
+
function launchSettings(focusView) {
|
|
175
|
+
return JSON.stringify({
|
|
176
|
+
hooks: launchHooks(),
|
|
177
|
+
...(focusView ? { viewMode: "focus", tui: "fullscreen" } : {}),
|
|
178
|
+
});
|
|
179
|
+
}
|
|
44
180
|
/**
|
|
45
181
|
* The flags that follow the one naming the conversation. This is where Launch options become
|
|
46
182
|
* flags: a Default option adds nothing. Advisor Off is not a flag (there is none): the
|
|
47
|
-
* launcher sets `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1` for it.
|
|
183
|
+
* launcher sets `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1` for it. `--settings` is always passed,
|
|
184
|
+
* for k-bench's hooks.
|
|
48
185
|
*/
|
|
49
186
|
function launchOptionArguments(options) {
|
|
50
187
|
const { model, effort, advisor, focusView } = options;
|
|
@@ -52,7 +189,8 @@ function launchOptionArguments(options) {
|
|
|
52
189
|
...(model === "default" ? [] : ["--model", model]),
|
|
53
190
|
...(effort === "default" ? [] : ["--effort", effort]),
|
|
54
191
|
...(advisor === "default" || advisor === "off" ? [] : ["--advisor", advisor]),
|
|
55
|
-
|
|
192
|
+
"--settings",
|
|
193
|
+
launchSettings(focusView),
|
|
56
194
|
];
|
|
57
195
|
}
|
|
58
196
|
/** Printed, and waited on, when Claude Code exits with an error. */
|
|
@@ -11,8 +11,11 @@ function isDirectory(path) {
|
|
|
11
11
|
return false;
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
-
/**
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* The subfolders of `path`, for the folder picker. Symlinks to folders count as folders.
|
|
16
|
+
* Hidden folders are left out unless `hidden` is set (for the path field's suggestions).
|
|
17
|
+
*/
|
|
18
|
+
export function listDirectories(path, { hidden = false } = {}) {
|
|
16
19
|
if (!isAbsolute(path))
|
|
17
20
|
throw new DirectoryError(`Path must be absolute: ${path}`);
|
|
18
21
|
const folder = resolve(path);
|
|
@@ -26,7 +29,7 @@ export function listDirectories(path) {
|
|
|
26
29
|
throw new DirectoryError(`Cannot read folder: ${folder}`);
|
|
27
30
|
}
|
|
28
31
|
const directories = names
|
|
29
|
-
.filter((name) => !name.startsWith(".") && isDirectory(join(folder, name)))
|
|
32
|
+
.filter((name) => (hidden || !name.startsWith(".")) && isDirectory(join(folder, name)))
|
|
30
33
|
.sort((a, b) => a.localeCompare(b, "en", { sensitivity: "base" }))
|
|
31
34
|
.map((name) => ({ name, path: join(folder, name) }));
|
|
32
35
|
const parent = dirname(folder);
|
|
@@ -1,7 +1,11 @@
|
|
|
1
|
+
/** A conversation ID as Claude Code makes them. Anything else a hook reports is ignored. */
|
|
2
|
+
const CONVERSATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1
3
|
/**
|
|
2
4
|
* Compares the store with what is alive in tmux (ADR-0002). A Session in the store with no
|
|
3
5
|
* live tmux session is Stopped, which callers learn from the returned live ids. A live tmux
|
|
4
|
-
* session on this instance's socket with no store row is an orphan and is killed.
|
|
6
|
+
* session on this instance's socket with no store row is an orphan and is killed. A live
|
|
7
|
+
* Claude Session whose Claude Code reported moving to another conversation has the new one
|
|
8
|
+
* stored, so a restart resumes it (ADR-0005).
|
|
5
9
|
*/
|
|
6
10
|
export class Reconciler {
|
|
7
11
|
store;
|
|
@@ -26,10 +30,16 @@ export class Reconciler {
|
|
|
26
30
|
this.starting.delete(id);
|
|
27
31
|
}
|
|
28
32
|
}
|
|
29
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Kills orphans, stores the conversation each live Claude Session is on, and returns the
|
|
35
|
+
* Sessions that are alive, by id.
|
|
36
|
+
*/
|
|
30
37
|
async reconcile() {
|
|
31
38
|
const live = new Map((await this.tmux.listSessions()).map((s) => [s.id, s]));
|
|
32
|
-
for (const id of [...live
|
|
39
|
+
for (const [id, session] of [...live]) {
|
|
40
|
+
if (CONVERSATION_ID.test(session.conversation)) {
|
|
41
|
+
this.store.setConversationId(id, session.conversation);
|
|
42
|
+
}
|
|
33
43
|
// Order matters: a Session no longer starting already has its store row.
|
|
34
44
|
if (this.starting.has(id) || this.store.getSession(id))
|
|
35
45
|
continue;
|
|
@@ -12,7 +12,7 @@ import { TmuxDriver } from "./tmux.js";
|
|
|
12
12
|
export async function startServer(config, options = {}) {
|
|
13
13
|
const store = new Store(config.dataDir);
|
|
14
14
|
const tmux = new TmuxDriver(config.tmuxSocket, config.claudeProgram);
|
|
15
|
-
const service = new Service(store, tmux);
|
|
15
|
+
const service = new Service(store, tmux, { workingQuietMs: config.workingQuietMs });
|
|
16
16
|
// Anything on the socket that the store does not know is left over: clean it up first.
|
|
17
17
|
await service.reconcile();
|
|
18
18
|
// A tmux server that outlived the previous k-bench gets this version's hooks.
|
|
@@ -24,6 +24,15 @@ export async function startServer(config, options = {}) {
|
|
|
24
24
|
});
|
|
25
25
|
const events = new EventSockets(feed);
|
|
26
26
|
const bells = tmux.watchBells(() => feed.notify());
|
|
27
|
+
const activity = tmux.watchActivity(() => feed.notify());
|
|
28
|
+
// A Claude Session's new conversation is stored at once, whether or not anyone is viewing
|
|
29
|
+
// it. One reconcile at a time; stopping waits for the last before the database closes.
|
|
30
|
+
let following = Promise.resolve();
|
|
31
|
+
const conversations = tmux.watchConversations(() => {
|
|
32
|
+
following = following
|
|
33
|
+
.then(() => service.reconcile())
|
|
34
|
+
.catch((error) => console.error("could not follow a Claude conversation", error));
|
|
35
|
+
});
|
|
27
36
|
// The guard sits in front of everything the server answers, so no route or static file
|
|
28
37
|
// (now or added later) can be reached without the allowed login.
|
|
29
38
|
const guard = new AccessGuard(config.allowedLogin);
|
|
@@ -67,6 +76,9 @@ export async function startServer(config, options = {}) {
|
|
|
67
76
|
const stop = () => {
|
|
68
77
|
stopping ??= (async () => {
|
|
69
78
|
await bells.stop();
|
|
79
|
+
await activity.stop();
|
|
80
|
+
await conversations.stop();
|
|
81
|
+
await following;
|
|
70
82
|
events.closeAll();
|
|
71
83
|
// From here on no tmux client this server started is running or starting.
|
|
72
84
|
await attachments.stop();
|